From 6565c4bea1163b8247b02b30b588127d6803129a Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 08:58:18 -0700 Subject: [PATCH 01/19] Use for-of in the parser. --- src/compiler/parser.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 6e444eb23c7..3fcd5fd9fda 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -27,8 +27,8 @@ module ts { function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { if (nodes) { - for (var i = 0, len = nodes.length; i < len; i++) { - var result = cbNode(nodes[i]); + for (let node of nodes) { + var result = cbNode(node); if (result) { return result; } @@ -436,8 +436,8 @@ module ts { array.pos += delta; array.end += delta; - for (var i = 0, n = array.length; i < n; i++) { - visitNode(array[i]); + for (let node of array) { + visitNode(node); } } } @@ -589,8 +589,8 @@ module ts { // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var i = 0, n = array.length; i < n; i++) { - visitNode(array[i]); + for (let node of array) { + visitNode(node); } return; } @@ -948,7 +948,7 @@ module ts { if (position >= array.pos && position < array.end) { // position was in this array. Search through this array to see if we find a // viable element. - for (var i = 0, n = array.length; i < n; i++) { + for (let i = 0, n = array.length; i < n; i++) { var child = array[i]; if (child) { if (child.pos === position) { From 31b066ec1719e0f0cb636185b3fef7ee7fce6510 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 09:03:31 -0700 Subject: [PATCH 02/19] Use for-of in core.ts --- src/compiler/core.ts | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 463473497cb..0b296233f70 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -25,7 +25,7 @@ module ts { export function forEach(array: T[], callback: (element: T, index: number) => U): U { if (array) { - for (var i = 0, len = array.length; i < len; i++) { + for (let i = 0, len = array.length; i < len; i++) { var result = callback(array[i], i); if (result) { return result; @@ -37,8 +37,8 @@ module ts { export function contains(array: T[], value: T): boolean { if (array) { - for (var i = 0, len = array.length; i < len; i++) { - if (array[i] === value) { + for (let v of array) { + if (v === value) { return true; } } @@ -60,8 +60,8 @@ module ts { export function countWhere(array: T[], predicate: (x: T) => boolean): number { var count = 0; if (array) { - for (var i = 0, len = array.length; i < len; i++) { - if (predicate(array[i])) { + for (let v of array) { + if (predicate(v)) { count++; } } @@ -72,8 +72,7 @@ module ts { export function filter(array: T[], f: (x: T) => boolean): T[] { if (array) { var result: T[] = []; - for (var i = 0, len = array.length; i < len; i++) { - var item = array[i]; + for (let item of array) { if (f(item)) { result.push(item); } @@ -85,8 +84,8 @@ module ts { export function map(array: T[], f: (x: T) => U): U[] { if (array) { var result: U[] = []; - for (var i = 0, len = array.length; i < len; i++) { - result.push(f(array[i])); + for (let v of array) { + result.push(f(v)); } } return result; @@ -102,9 +101,10 @@ module ts { export function deduplicate(array: T[]): T[] { if (array) { var result: T[] = []; - for (var i = 0, len = array.length; i < len; i++) { - var item = array[i]; - if (!contains(result, item)) result.push(item); + for (let item of array) { + if (!contains(result, item)) { + result.push(item); + } } } return result; @@ -119,8 +119,8 @@ module ts { } export function addRange(to: T[], from: T[]): void { - for (var i = 0, n = from.length; i < n; i++) { - to.push(from[i]); + for (let v of from) { + to.push(v); } } From 4642b869faedc4bb686a5ac864ef89a441b8966d Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 09:08:27 -0700 Subject: [PATCH 03/19] Use for-of in emitter.ts --- src/compiler/emitter.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 3e7d64eedc9..1db7bb30ebe 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -555,19 +555,19 @@ module ts { } function emitLines(nodes: Node[]) { - for (var i = 0, n = nodes.length; i < n; i++) { - emit(nodes[i]); + for (let node of nodes) { + emit(node); } } function emitSeparatedList(nodes: Node[], separator: string, eachNodeEmitFn: (node: Node) => void) { var currentWriterPos = writer.getTextPos(); - for (var i = 0, n = nodes.length; i < n; i++) { + for (let node of nodes) { if (currentWriterPos !== writer.getTextPos()) { write(separator); } currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(nodes[i]); + eachNodeEmitFn(node); } } @@ -4488,9 +4488,9 @@ module ts { var preambleEmitted = writer.getTextPos() !== initialTextPos; if (preserveNewLines && !preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var i = 0, n = body.statements.length; i < n; i++) { + for (let statement of body.statements) { write(" "); - emit(body.statements[i]); + emit(statement); } emitTempDeclarations(/*newLine*/ false); write(" "); From 6e8a83af081370335d5801f74520454d461cb460 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 09:16:29 -0700 Subject: [PATCH 04/19] Use for-of in the checker --- src/compiler/checker.ts | 27 +++++++++++++-------------- src/compiler/utilities.ts | 6 +++--- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1500a47f197..2148c9e456e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1290,8 +1290,8 @@ module ts { } if (accessibleSymbolChain) { - for (var i = 0, n = accessibleSymbolChain.length; i < n; i++) { - appendParentTypeArgumentsAndSymbolName(accessibleSymbolChain[i]); + for (let accessibleSymbol of accessibleSymbolChain) { + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } else { @@ -3278,14 +3278,14 @@ module ts { } function addTypesToSortedSet(sortedTypes: Type[], types: Type[]) { - for (var i = 0, len = types.length; i < len; i++) { - addTypeToSortedSet(sortedTypes, types[i]); + for (let type of types) { + addTypeToSortedSet(sortedTypes, type); } } function isSubtypeOfAny(candidate: Type, types: Type[]): boolean { - for (var i = 0, len = types.length; i < len; i++) { - if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { + for (let type of types) { + if (candidate !== type && isTypeSubtypeOf(candidate, type)) { return true; } } @@ -3805,8 +3805,8 @@ module ts { function unionTypeRelatedToUnionType(source: UnionType, target: UnionType): Ternary { var result = Ternary.True; var sourceTypes = source.types; - for (var i = 0, len = sourceTypes.length; i < len; i++) { - var related = typeRelatedToUnionType(sourceTypes[i], target, false); + for (let sourceType of sourceTypes) { + var related = typeRelatedToUnionType(sourceType, target, false); if (!related) { return Ternary.False; } @@ -3829,8 +3829,8 @@ module ts { function unionTypeRelatedToType(source: UnionType, target: Type, reportErrors: boolean): Ternary { var result = Ternary.True; var sourceTypes = source.types; - for (var i = 0, len = sourceTypes.length; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors); + for (let sourceType of sourceTypes) { + var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return Ternary.False; } @@ -4066,8 +4066,7 @@ module ts { return Ternary.False; } var result = Ternary.True; - for (var i = 0, len = sourceProperties.length; i < len; ++i) { - var sourceProp = sourceProperties[i]; + for (let sourceProp of sourceProperties) { var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return Ternary.False; @@ -4332,8 +4331,8 @@ module ts { } function isSupertypeOfEach(candidate: Type, types: Type[]): boolean { - for (var i = 0, len = types.length; i < len; i++) { - if (candidate !== types[i] && !isTypeSubtypeOf(types[i], candidate)) return false; + for (let type of types) { + if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } return true; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index b0e2540bdf0..4c4c4afd6c4 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -852,9 +852,9 @@ module ts { export function getHeritageClause(clauses: NodeArray, kind: SyntaxKind) { if (clauses) { - for (var i = 0, n = clauses.length; i < n; i++) { - if (clauses[i].token === kind) { - return clauses[i]; + for (let clause of clauses) { + if (clause.token === kind) { + return clause; } } } From d50f7b5ddba83b6280f5ad9619b5b3997e513a27 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 09:28:17 -0700 Subject: [PATCH 05/19] Use for-of in the checker. --- src/compiler/checker.ts | 52 +++++++++++++++-------------------------- 1 file changed, 19 insertions(+), 33 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2148c9e456e..75fb5211611 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6583,9 +6583,9 @@ module ts { // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var i = 0, n = candidates.length; i < n; i++) { - if (hasCorrectArity(node, args, candidates[i])) { - return candidates[i]; + for (let candidate of candidates) { + if (hasCorrectArity(node, args, candidate)) { + return candidate; } } } @@ -7843,8 +7843,8 @@ module ts { if (indexSymbol) { var seenNumericIndexer = false; var seenStringIndexer = false; - for (var i = 0, len = indexSymbol.declarations.length; i < len; ++i) { - var declaration = indexSymbol.declarations[i]; + for (let decl of indexSymbol.declarations) { + var declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: @@ -8319,9 +8319,9 @@ module ts { // function g(x: string, y: string) { } // // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (var i = 0, len = signatures.length; i < len; ++i) { - if (!signatures[i].hasStringLiterals && !isSignatureAssignableTo(bodySignature, signatures[i])) { - error(signatures[i].declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + for (let signature of signatures) { + if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { + error(signature.declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; } } @@ -9473,8 +9473,8 @@ module ts { // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfObjectType(baseType); - for (var i = 0, len = baseProperties.length; i < len; ++i) { - var base = getTargetSymbol(baseProperties[i]); + for (let baseProperty of baseProperties) { + var base = getTargetSymbol(baseProperty); if (base.flags & SymbolFlags.Prototype) { continue; @@ -9566,11 +9566,9 @@ module ts { forEach(type.declaredProperties, p => { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; - for (var i = 0, len = type.baseTypes.length; i < len; ++i) { - var base = type.baseTypes[i]; + for (let base of type.baseTypes) { var properties = getPropertiesOfObjectType(base); - for (var j = 0, proplen = properties.length; j < proplen; ++j) { - var prop = properties[j]; + for (let prop of properties) { if (!hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } @@ -11191,9 +11189,7 @@ module ts { var lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node; var flags = 0; - for (var i = 0, n = node.modifiers.length; i < n; i++) { - var modifier = node.modifiers[i]; - + for (let modifier of node.modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: @@ -11420,8 +11416,7 @@ module ts { function checkGrammarForOmittedArgument(node: CallExpression, arguments: NodeArray): boolean { if (arguments) { var sourceFile = getSourceFileOfNode(node); - for (var i = 0, n = arguments.length; i < n; i++) { - var arg = arguments[i]; + for (let arg of arguments) { if (arg.kind === SyntaxKind.OmittedExpression) { return grammarErrorAtPos(sourceFile, arg.pos, 0, Diagnostics.Argument_expression_expected); } @@ -11451,10 +11446,7 @@ module ts { var seenImplementsClause = false; if (!checkGrammarModifiers(node) && node.heritageClauses) { - for (var i = 0, n = node.heritageClauses.length; i < n; i++) { - Debug.assert(i <= 2); - var heritageClause = node.heritageClauses[i]; - + for (let heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen) @@ -11489,10 +11481,7 @@ module ts { var seenExtendsClause = false; if (node.heritageClauses) { - for (var i = 0, n = node.heritageClauses.length; i < n; i++) { - Debug.assert(i <= 1); - var heritageClause = node.heritageClauses[i]; - + for (let heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); @@ -11550,8 +11539,7 @@ module ts { var GetOrSetAccessor = GetAccessor | SetAccesor; var inStrictMode = (node.parserContextFlags & ParserContextFlags.StrictMode) !== 0; - for (var i = 0, n = node.properties.length; i < n; i++) { - var prop = node.properties[i]; + for (let prop of node.properties) { var name = prop.name; if (prop.kind === SyntaxKind.OmittedExpression || name.kind === SyntaxKind.ComputedPropertyName) { @@ -11939,8 +11927,7 @@ module ts { if (!enumIsConst) { var inConstantEnumMemberSection = true; var inAmbientContext = isInAmbientContext(enumDecl); - for (var i = 0, n = enumDecl.members.length; i < n; i++) { - var node = enumDecl.members[i]; + for (let node of enumDecl.members) { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. @@ -12062,8 +12049,7 @@ module ts { } function checkGrammarTopLevelElementsForRequiredDeclareModifier(file: SourceFile): boolean { - for (var i = 0, n = file.statements.length; i < n; i++) { - var decl = file.statements[i]; + for (let decl of file.statements) { if (isDeclaration(decl) || decl.kind === SyntaxKind.VariableStatement) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; From 29bfc15d9ba074e8427593ac646cefa70f062447 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 09:41:54 -0700 Subject: [PATCH 06/19] use for-of in more places. --- src/compiler/checker.ts | 55 ++++++++++++++------------------------- src/compiler/core.ts | 6 ++--- src/compiler/emitter.ts | 8 +++--- src/compiler/sys.ts | 3 +-- src/compiler/utilities.ts | 3 +-- 5 files changed, 26 insertions(+), 49 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 75fb5211611..25e451d0948 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -850,8 +850,7 @@ module ts { function findConstructorDeclaration(node: ClassDeclaration): ConstructorDeclaration { var members = node.members; - for (var i = 0; i < members.length; i++) { - var member = members[i]; + for (let member of members) { if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { return member; } @@ -1549,8 +1548,7 @@ module ts { writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - for (var i = 0; i < resolved.properties.length; i++) { - var p = resolved.properties[i]; + for (let p of resolved.properties) { var t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { var signatures = getSignaturesOfType(t, SignatureKind.Call); @@ -2402,8 +2400,7 @@ module ts { function createSymbolTable(symbols: Symbol[]): SymbolTable { var result: SymbolTable = {}; - for (var i = 0; i < symbols.length; i++) { - var symbol = symbols[i]; + for (let symbol of symbols) { result[symbol.name] = symbol; } return result; @@ -2411,16 +2408,14 @@ module ts { function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper): SymbolTable { var result: SymbolTable = {}; - for (var i = 0; i < symbols.length; i++) { - var symbol = symbols[i]; + for (let symbol of symbols) { result[symbol.name] = instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols: SymbolTable, baseSymbols: Symbol[]) { - for (var i = 0; i < baseSymbols.length; i++) { - var s = baseSymbols[i]; + for (let s of baseSymbols) { if (!hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -2728,8 +2723,7 @@ module ts { } var propTypes: Type[] = []; var declarations: Declaration[] = []; - for (var i = 0; i < props.length; i++) { - var prop = props[i]; + for (let prop of props) { if (prop.declarations) { declarations.push.apply(declarations, prop.declarations); } @@ -3181,8 +3175,7 @@ module ts { function getTypeDeclaration(symbol: Symbol): Declaration { var declarations = symbol.declarations; - for (var i = 0; i < declarations.length; i++) { - var declaration = declarations[i]; + for (let declaration of declarations) { switch (declaration.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: @@ -3982,8 +3975,7 @@ module ts { var result = Ternary.True; var properties = getPropertiesOfObjectType(target); var requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); - for (var i = 0; i < properties.length; i++) { - var targetProp = properties[i]; + for (let targetProp of properties) { var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -4091,8 +4083,7 @@ module ts { var targetSignatures = getSignaturesOfType(target, kind); var result = Ternary.True; var saveErrorInfo = errorInfo; - outer: for (var i = 0; i < targetSignatures.length; i++) { - var t = targetSignatures[i]; + outer: for (let t of targetSignatures) { if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) { var localErrors = reportErrors; for (var j = 0; j < sourceSignatures.length; j++) { @@ -4608,8 +4599,7 @@ module ts { var typeParameterCount = 0; var typeParameter: TypeParameter; // First infer to each type in union that isn't a type parameter - for (var i = 0; i < targetTypes.length; i++) { - var t = targetTypes[i]; + for (let t of targetTypes) { if (t.flags & TypeFlags.TypeParameter && contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -4656,8 +4646,7 @@ module ts { function inferFromProperties(source: Type, target: Type) { var properties = getPropertiesOfObjectType(target); - for (var i = 0; i < properties.length; i++) { - var targetProp = properties[i]; + for (let targetProp of properties) { var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -5789,8 +5778,7 @@ module ts { var contextualType = getContextualType(node); var typeFlags: TypeFlags; - for (var i = 0; i < node.properties.length; i++) { - var memberDecl = node.properties[i]; + for (let memberDecl of node.properties) { var member = memberDecl.symbol; if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || @@ -6167,8 +6155,7 @@ module ts { var specializedIndex: number = -1; var spliceIndex: number; Debug.assert(!result.length); - for (var i = 0; i < signatures.length; i++) { - var signature = signatures[i]; + for (let signature of signatures) { var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -7272,8 +7259,7 @@ module ts { function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type, contextualMapper?: TypeMapper): Type { var properties = node.properties; - for (var i = 0; i < properties.length; i++) { - var p = properties[i]; + for (let p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { // TODO(andersh): Computed property support var name = (p).name; @@ -8097,8 +8083,7 @@ module ts { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (var i = 0; i < signaturesToCheck.length; i++) { - var otherSignature = signaturesToCheck[i]; + for (let otherSignature of signaturesToCheck) { if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -9281,8 +9266,7 @@ module ts { if (type.flags & TypeFlags.Class && type.symbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration) { var classDeclaration = type.symbol.valueDeclaration; - for (var i = 0; i < classDeclaration.members.length; i++) { - var member = classDeclaration.members[i]; + for (let 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. @@ -9371,12 +9355,12 @@ module ts { // Check each type parameter and check that list has no duplicate type parameter declarations function checkTypeParameters(typeParameterDeclarations: TypeParameterDeclaration[]) { if (typeParameterDeclarations) { - for (var i = 0; i < typeParameterDeclarations.length; i++) { + for (let i = 0, n = typeParameterDeclarations.length; i < n; i++) { var node = typeParameterDeclarations[i]; checkTypeParameter(node); if (produceDiagnostics) { - for (var j = 0; j < i; j++) { + for (let j = 0; j < i; j++) { if (typeParameterDeclarations[j].symbol === node.symbol) { error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); } @@ -9855,8 +9839,7 @@ module ts { function getFirstNonAmbientClassOrFunctionDeclaration(symbol: Symbol): Declaration { var declarations = symbol.declarations; - for (var i = 0; i < declarations.length; i++) { - var declaration = declarations[i]; + for (let declaration of declarations) { if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && !isInAmbientContext(declaration)) { return declaration; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 0b296233f70..941f3097585 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -427,8 +427,7 @@ module ts { function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { var parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); var normalized: string[] = []; - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; + for (let part of parts) { if (part !== ".") { if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { normalized.pop(); @@ -603,8 +602,7 @@ module ts { var supportedExtensions = [".d.ts", ".ts", ".js"]; export function removeFileExtension(path: string): string { - for (var i = 0; i < supportedExtensions.length; i++) { - var ext = supportedExtensions[i]; + for (let ext of supportedExtensions) { if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 1db7bb30ebe..da789b6ffef 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2433,7 +2433,7 @@ module ts { headEmitted = true; } - for (var i = 0; i < node.templateSpans.length; i++) { + for (let i = 0, n = node.templateSpans.length; i < n; i++) { var templateSpan = node.templateSpans[i]; // Check if the expression has operands and binds its operands less closely than binary '+'. @@ -3952,8 +3952,7 @@ module ts { // to ensure value is evaluated exactly once. value = ensureIdentifier(value); } - for (var i = 0; i < properties.length; i++) { - var p = properties[i]; + for (let p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { // TODO(andersh): Computed property support var propName = ((p).name); @@ -5148,8 +5147,7 @@ module ts { function getExternalImportInfo(node: ImportDeclaration | ImportEqualsDeclaration): ExternalImportInfo { if (externalImports) { - for (var i = 0; i < externalImports.length; i++) { - var info = externalImports[i]; + for (let info of externalImports) { if (info.rootNode === node) { return info; } diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 5f10a747d42..c86be03d322 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -124,8 +124,7 @@ module ts { function visitDirectory(path: string) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var i = 0; i < files.length; i++) { - var name = files[i]; + for (let name of files) { if (!extension || fileExtensionIs(name, extension)) { result.push(combinePaths(path, name)); } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 4c4c4afd6c4..ea362eb2220 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -15,8 +15,7 @@ module ts { export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { var declarations = symbol.declarations; - for (var i = 0; i < declarations.length; i++) { - var declaration = declarations[i]; + for (let declaration of declarations) { if (declaration.kind === kind) { return declaration; } From a6a6a0edef194d9d519882d0455c68d98e4002e3 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 09:45:57 -0700 Subject: [PATCH 07/19] More usage of for-of --- src/compiler/checker.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 25e451d0948..9348a083e6b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4086,8 +4086,7 @@ module ts { outer: for (let t of targetSignatures) { if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) { var localErrors = reportErrors; - for (var j = 0; j < sourceSignatures.length; j++) { - var s = sourceSignatures[j]; + for (let s of sourceSignatures) { if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) { var related = signatureRelatedTo(s, t, localErrors); if (related) { @@ -10042,16 +10041,14 @@ module ts { var declarations = moduleSymbol.declarations; for (var i = 0; i < declarations.length; i++) { var statements = getModuleStatements(declarations[i]); - for (var j = 0; j < statements.length; j++) { - var node = statements[j]; + for (let node of statements) { if (node.kind === SyntaxKind.ExportDeclaration) { var exportClause = (node).exportClause; if (!exportClause) { return true; } var specifiers = exportClause.elements; - for (var k = 0; k < specifiers.length; k++) { - var specifier = specifiers[k]; + for (let specifier of specifiers) { if (!(specifier.propertyName && specifier.name && specifier.name.text === "default")) { return true; } From 224de1db722cd461511d338d96107c1660cc38f4 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:03:01 -0700 Subject: [PATCH 08/19] use for-of in more places. --- src/services/formatting/formatting.ts | 10 +++--- .../formatting/ruleOperationContext.ts | 4 +-- src/services/formatting/rulesMap.ts | 6 ++-- src/services/navigateTo.ts | 11 +++---- src/services/navigationBar.ts | 14 +++----- src/services/patternMatcher.ts | 7 ++-- src/services/services.ts | 33 ++++++++----------- src/services/signatureHelp.ts | 3 +- src/services/utilities.ts | 7 ++-- 9 files changed, 38 insertions(+), 57 deletions(-) diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index dd12b452b57..b20d8fea22d 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -609,8 +609,8 @@ module ts.formatting { } var inheritedIndentation = Constants.Unknown; - for (var i = 0, len = nodes.length; i < len; ++i) { - inheritedIndentation = processChildNode(nodes[i], inheritedIndentation, node, listDynamicIndentation, startLine, /*isListElement*/ true) + for (let child of nodes) { + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, /*isListElement*/ true) } if (listEndToken !== SyntaxKind.Unknown) { @@ -668,8 +668,7 @@ module ts.formatting { if (indentToken) { var indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { - for (var i = 0, len = currentTokenInfo.leadingTrivia.length; i < len; ++i) { - var triviaItem = currentTokenInfo.leadingTrivia[i]; + for (let triviaItem of currentTokenInfo.leadingTrivia) { if (!rangeContainsRange(originalRange, triviaItem)) { continue; } @@ -709,8 +708,7 @@ module ts.formatting { } function processTrivia(trivia: TextRangeWithKind[], parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): void { - for (var i = 0, len = trivia.length; i < len; ++i) { - var triviaItem = trivia[i]; + for (let triviaItem of trivia) { if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); diff --git a/src/services/formatting/ruleOperationContext.ts b/src/services/formatting/ruleOperationContext.ts index d037f8e70d7..dc4e5d4f105 100644 --- a/src/services/formatting/ruleOperationContext.ts +++ b/src/services/formatting/ruleOperationContext.ts @@ -36,8 +36,8 @@ module ts.formatting { return true; } - for (var i = 0, len = this.customContextChecks.length; i < len; i++) { - if (!this.customContextChecks[i](context)) { + for (let check of this.customContextChecks) { + if (!check(context)) { return false; } } diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index d25320f16a8..634ec61de9c 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -76,10 +76,10 @@ module ts.formatting { var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); var bucket = this.map[bucketIndex]; if (bucket != null) { - for (var i = 0, len = bucket.Rules().length; i < len; i++) { - var rule = bucket.Rules()[i]; - if (rule.Operation.Context.InContext(context)) + for (let rule of bucket.Rules()) { + if (rule.Operation.Context.InContext(context)) { return rule; + } } } return null; diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index b3f72d83cb3..7757a7acf3a 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -10,8 +10,7 @@ module ts.NavigateTo { cancellationToken.throwIfCancellationRequested(); var declarations = sourceFile.getNamedDeclarations(); - for (var i = 0, n = declarations.length; i < n; i++) { - var declaration = declarations[i]; + for (let declaration of declarations) { var name = getDeclarationName(declaration); if (name !== undefined) { @@ -58,8 +57,8 @@ module ts.NavigateTo { Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var i = 0, n = matches.length; i < n; i++) { - if (!matches[i].isCaseSensitive) { + for (let match of matches) { + if (!match.isCaseSensitive) { return false; } } @@ -167,8 +166,8 @@ module ts.NavigateTo { Debug.assert(matches.length > 0); var bestMatchKind = PatternMatchKind.camelCase; - for (var i = 0, n = matches.length; i < n; i++) { - var kind = matches[i].kind; + for (let match of matches) { + var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; } diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 20e80cc88c0..1f67fef5e71 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -150,8 +150,7 @@ module ts.NavigationBar { function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void { nodes = sortNodes(nodes); - for (var i = 0, n = nodes.length; i < n; i++) { - var node = nodes[i]; + for (let node of nodes) { switch (node.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: @@ -204,8 +203,7 @@ module ts.NavigationBar { var keyToItem: Map = {}; - for (var i = 0, n = nodes.length; i < n; i++) { - var child = nodes[i]; + for (let child of nodes) { var item = createItem(child); if (item !== undefined) { if (item.text.length > 0) { @@ -238,12 +236,8 @@ module ts.NavigationBar { // Next, recursively merge or add any children in the source as appropriate. outer: - for (var i = 0, n = source.childItems.length; i < n; i++) { - var sourceChild = source.childItems[i]; - - for (var j = 0, m = target.childItems.length; j < m; j++) { - var targetChild = target.childItems[j]; - + for (let sourceChild of source.childItems) { + for (let targetChild of target.childItems) { if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { // Found a match. merge them. merge(targetChild, sourceChild); diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index 9bcd3e1d000..f7874519334 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -221,8 +221,7 @@ module ts { // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); - for (var i = 0, n = wordSpans.length; i < n; i++) { - var span = wordSpans[i] + for (let span of wordSpans) { if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); @@ -339,9 +338,7 @@ module ts { var subWordTextChunks = segment.subWordTextChunks; var matches: PatternMatch[] = undefined; - for (var i = 0, n = subWordTextChunks.length; i < n; i++) { - var subWordTextChunk = subWordTextChunks[i]; - + for (let subWordTextChunk of subWordTextChunks) { // Try to match the candidate with this word var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); if (!result) { diff --git a/src/services/services.ts b/src/services/services.ts index 61d7a0736b0..f0e934ed6a2 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -196,8 +196,7 @@ module ts { var list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, NodeFlags.Synthetic, this); list._children = []; var pos = nodes.pos; - for (var i = 0, len = nodes.length; i < len; i++) { - var node = nodes[i]; + for (let node of nodes) { if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -255,8 +254,7 @@ module ts { public getFirstToken(sourceFile?: SourceFile): Node { var children = this.getChildren(); - for (var i = 0; i < children.length; i++) { - var child = children[i]; + for (let child of children) { if (child.kind < SyntaxKind.FirstNode) { return child; } @@ -1523,8 +1521,8 @@ module ts { // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); - for (var i = 0, n = rootFileNames.length; i < n; i++) { - this.createEntry(rootFileNames[i]); + for (let fileName of rootFileNames) { + this.createEntry(fileName); } // store the compilation settings @@ -2252,8 +2250,8 @@ module ts { // not part of the new program. if (program) { var oldSourceFiles = program.getSourceFiles(); - for (var i = 0, n = oldSourceFiles.length; i < n; i++) { - var fileName = oldSourceFiles[i].fileName; + for (let oldSourceFile of oldSourceFiles) { + var fileName = oldSourceFile.fileName; if (!newProgram.getSourceFile(fileName) || changesInCompilationSettingsAffectSyntax) { documentRegistry.releaseDocument(fileName, oldSettings); } @@ -2329,8 +2327,8 @@ module ts { } // If any file is not up-to-date, then the whole program is not up-to-date - for (var i = 0, n = rootFileNames.length; i < n; i++) { - if (!sourceFileUpToDate(program.getSourceFile(rootFileNames[i]))) { + for (let fileName of rootFileNames) { + if (!sourceFileUpToDate(program.getSourceFile(fileName))) { return false; } } @@ -4314,8 +4312,8 @@ module ts { var declarations = symbol.getDeclarations(); if (declarations) { - for (var i = 0, n = declarations.length; i < n; i++) { - var container = getContainerNode(declarations[i]); + for (let declaration of declarations) { + var container = getContainerNode(declaration); if (!container) { return undefined; @@ -4831,8 +4829,8 @@ module ts { // Remember the last meaning var lastIterationMeaning = meaning; - for (var i = 0, n = declarations.length; i < n; i++) { - var declarationMeaning = getMeaningFromDeclaration(declarations[i]); + for (let declaration of declarations) { + var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -5401,8 +5399,7 @@ module ts { // Ignore nodes that don't intersect the original span to classify. if (textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { var children = element.getChildren(); - for (var i = 0, n = children.length; i < n; i++) { - var child = children[i]; + for (let child of children) { if (isToken(child)) { classifyToken(child); } @@ -5435,9 +5432,7 @@ module ts { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); - for (var i = 0, n = childNodes.length; i < n; i++) { - var current = childNodes[i]; - + for (let current of childNodes) { if (current.kind === matchKind) { var range1 = createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); var range2 = createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 52a7b41d8a7..3a677c9506c 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -318,8 +318,7 @@ module ts.SignatureHelp { // arg index. var argumentIndex = 0; var listChildren = argumentsList.getChildren(); - for (var i = 0, n = listChildren.length; i < n; i++) { - var child = listChildren[i]; + for (let child of listChildren) { if (child === node) { break; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index f2403217c24..332ddffc910 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -184,8 +184,7 @@ module ts { } var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; ++i) { - var child = children[i]; + for (let child of children) { var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || @@ -221,8 +220,8 @@ module ts { } var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; ++i) { - var child = children[i]; + for (var i = 0, len = children.length; i < len; i++) { + let child = children[i]; if (nodeHasTokens(child)) { if (position <= child.end) { if (child.getStart(sourceFile) >= position) { From 5f89a8e3f682db5548b53d2475dd3fcaaef19626 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:27:31 -0700 Subject: [PATCH 09/19] Use more for-of --- src/compiler/checker.ts | 57 +++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9348a083e6b..c20f15a0d63 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1507,16 +1507,16 @@ module ts { writePunctuation(writer, SyntaxKind.OpenBraceToken); writer.writeLine(); writer.increaseIndent(); - for (var i = 0; i < resolved.callSignatures.length; i++) { - buildSignatureDisplay(resolved.callSignatures[i], writer, enclosingDeclaration, globalFlagsToPass, typeStack); + for (let signature of resolved.callSignatures) { + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - for (var i = 0; i < resolved.constructSignatures.length; i++) { + for (let signature of resolved.constructSignatures) { writeKeyword(writer, SyntaxKind.NewKeyword); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[i], writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -1552,12 +1552,12 @@ module ts { var t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { var signatures = getSignaturesOfType(t, SignatureKind.Call); - for (var j = 0; j < signatures.length; j++) { + for (let signature of signatures) { buildSymbolDisplay(p, writer); if (p.flags & SymbolFlags.Optional) { writePunctuation(writer, SyntaxKind.QuestionToken); } - buildSignatureDisplay(signatures[j], writer, enclosingDeclaration, globalFlagsToPass, typeStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, typeStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } @@ -2424,8 +2424,8 @@ module ts { function addInheritedSignatures(signatures: Signature[], baseSignatures: Signature[]) { if (baseSignatures) { - for (var i = 0; i < baseSignatures.length; i++) { - signatures.push(baseSignatures[i]); + for (let signature of baseSignatures) { + signatures.push(signature); } } } @@ -2536,8 +2536,8 @@ module ts { function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] { var signatureLists = map(types, t => getSignaturesOfType(t, kind)); var signatures = signatureLists[0]; - for (var i = 0; i < signatures.length; i++) { - if (signatures[i].typeParameters) { + for (let signature of signatures) { + if (signature.typeParameters) { return emptyArray; } } @@ -2558,8 +2558,8 @@ module ts { function getUnionIndexType(types: Type[], kind: IndexKind): Type { var indexTypes: Type[] = []; - for (var i = 0; i < types.length; i++) { - var indexType = getIndexTypeOfType(types[i], kind); + for (let type of types) { + var indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; } @@ -2706,8 +2706,8 @@ module ts { function createUnionProperty(unionType: UnionType, name: string): Symbol { var types = unionType.types; var props: Symbol[]; - for (var i = 0; i < types.length; i++) { - var type = getApparentType(types[i]); + for (let current of types) { + var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); if (!prop) { @@ -3042,7 +3042,10 @@ module ts { default: var result = ""; for (var i = 0; i < types.length; i++) { - if (i > 0) result += ","; + if (i > 0) { + result += ","; + } + result += types[i].id; } return result; @@ -3054,8 +3057,8 @@ module ts { // of an object literal (since those types have widening related information we need to track). function getWideningFlagsOfTypes(types: Type[]): TypeFlags { var result: TypeFlags = 0; - for (var i = 0; i < types.length; i++) { - result |= types[i].flags; + for (let type of types) { + result |= type.flags; } return result & TypeFlags.RequiresWidening; } @@ -3296,8 +3299,8 @@ module ts { } function containsAnyType(types: Type[]) { - for (var i = 0; i < types.length; i++) { - if (types[i].flags & TypeFlags.Any) { + for (let type of types) { + if (type.flags & TypeFlags.Any) { return true; } } @@ -3423,8 +3426,8 @@ module ts { function instantiateList(items: T[], mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): T[] { if (items && items.length) { var result: T[] = []; - for (var i = 0; i < items.length; i++) { - result.push(instantiator(items[i], mapper)); + for (let v of items) { + result.push(instantiator(v, mapper)); } return result; } @@ -3446,7 +3449,9 @@ module ts { } return t => { for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) return targets[i]; + if (t === sources[i]) { + return targets[i]; + } } return t; }; @@ -3466,8 +3471,10 @@ module ts { case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return t => { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) return anyType; + for (let source of sources) { + if (t === source) { + return anyType; + } } return t; }; @@ -4528,7 +4535,7 @@ module ts { function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { var inferences: TypeInferences[] = []; - for (var i = 0; i < typeParameters.length; i++) { + for (let unused of typeParameters) { inferences.push({ primary: undefined, secondary: undefined }); } return { From d10a54c6b0cd24ec112c0ca0eada0cc3ad460c64 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:36:29 -0700 Subject: [PATCH 10/19] Use for-of in more places. --- src/compiler/checker.ts | 40 ++++++++++++++++++++-------------------- src/compiler/core.ts | 4 ++-- src/compiler/sys.ts | 12 ++++++------ src/services/services.ts | 4 ++-- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c20f15a0d63..e18748835c9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4624,8 +4624,8 @@ module ts { else if (source.flags & TypeFlags.Union) { // Source is a union type, infer from each consituent type var sourceTypes = (source).types; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], target); + for (let sourceType of sourceTypes) { + inferFromTypes(sourceType, target); } } else if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) || @@ -5451,8 +5451,8 @@ module ts { var types = (type).types; var mappedType: Type; var mappedTypes: Type[]; - for (var i = 0; i < types.length; i++) { - var t = mapper(types[i]); + for (let current of types) { + var t = mapper(current); if (t) { if (!mappedType) { mappedType = t; @@ -5628,15 +5628,15 @@ module ts { } var signatureList: Signature[]; var types = (type).types; - for (var i = 0; i < types.length; i++) { + for (let current of types) { // The signature set of all constituent type with call signatures should match // So number of signatures allowed is either 0 or 1 if (signatureList && - getSignaturesOfObjectOrUnionType(types[i], SignatureKind.Call).length > 1) { + getSignaturesOfObjectOrUnionType(current, SignatureKind.Call).length > 1) { return undefined; } - var signature = getNonGenericSignature(types[i]); + var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -6586,12 +6586,12 @@ module ts { return resolveErrorCall(node); function chooseOverload(candidates: Signature[], relation: Map) { - for (var i = 0; i < candidates.length; i++) { - if (!hasCorrectArity(node, args, candidates[i])) { + for (let current of candidates) { + if (!hasCorrectArity(node, args, current)) { continue; } - var originalCandidate = candidates[i]; + var originalCandidate = current; var inferenceResult: InferenceContext; while (true) { @@ -7198,8 +7198,8 @@ module ts { } if (type.flags & TypeFlags.Union) { var types = (type).types; - for (var i = 0; i < types.length; i++) { - if (types[i].flags & kind) { + for (let current of types) { + if (current.flags & kind) { return true; } } @@ -7215,8 +7215,8 @@ module ts { } if (type.flags & TypeFlags.Union) { var types = (type).types; - for (var i = 0; i < types.length; i++) { - if (!(types[i].flags & kind)) { + for (let current of types) { + if (!(current.flags & kind)) { return false; } } @@ -8219,8 +8219,8 @@ module ts { var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var i = 0; i < declarations.length; i++) { - var node = declarations[i]; + for (let current of declarations) { + var node = current; var inAmbientContext = isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext; if (inAmbientContextOrInterface) { @@ -10046,8 +10046,8 @@ module ts { function hasExportedMembers(moduleSymbol: Symbol) { var declarations = moduleSymbol.declarations; - for (var i = 0; i < declarations.length; i++) { - var statements = getModuleStatements(declarations[i]); + for (let current of declarations) { + var statements = getModuleStatements(current); for (let node of statements) { if (node.kind === SyntaxKind.ExportDeclaration) { var exportClause = (node).exportClause; @@ -11840,8 +11840,8 @@ module ts { } else { var elements = (name).elements; - for (var i = 0; i < elements.length; ++i) { - checkGrammarNameInLetOrConstDeclarations(elements[i].name); + for (let element of elements) { + checkGrammarNameInLetOrConstDeclarations(element.name); } } } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 941f3097585..8939262b6d6 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -112,8 +112,8 @@ module ts { export function sum(array: any[], prop: string): number { var result = 0; - for (var i = 0; i < array.length; i++) { - result += array[i][prop]; + for (let v of array) { + result += v[prop]; } return result; } diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index c86be03d322..f89c474ce7f 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -130,8 +130,8 @@ module ts { } } var subfolders = getNames(folder.subfolders); - for (var i = 0; i < subfolders.length; i++) { - visitDirectory(combinePaths(path, subfolders[i])); + for (let current of subfolders) { + visitDirectory(combinePaths(path, current)); } } } @@ -229,8 +229,8 @@ module ts { function visitDirectory(path: string) { var files = _fs.readdirSync(path || ".").sort(); var directories: string[] = []; - for (var i = 0; i < files.length; i++) { - var name = combinePaths(path, files[i]); + for (let current of files) { + var name = combinePaths(path, current); var stat = _fs.lstatSync(name); if (stat.isFile()) { if (!extension || fileExtensionIs(name, extension)) { @@ -241,8 +241,8 @@ module ts { directories.push(name); } } - for (var i = 0; i < directories.length; i++) { - visitDirectory(directories[i]); + for (let current of directories) { + visitDirectory(current); } } } diff --git a/src/services/services.ts b/src/services/services.ts index f0e934ed6a2..b4c0ef2bbd8 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -5674,8 +5674,8 @@ module ts { // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); if (defaultLibFileName) { - for (var i = 0; i < declarations.length; i++) { - var sourceFile = declarations[i].getSourceFile(); + for (let current of declarations) { + var sourceFile = current.getSourceFile(); if (sourceFile && getCanonicalFileName(ts.normalizePath(sourceFile.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { return getRenameInfoError(getLocaleSpecificMessage(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library.key)); } From 069661e6ef07d4bc55820a272b2a069a45081c39 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:43:42 -0700 Subject: [PATCH 11/19] Use for-of in more places. --- src/compiler/checker.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e18748835c9..5c571d8e0e3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2999,8 +2999,8 @@ module ts { var indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { var len = indexSymbol.declarations.length; - for (var i = 0; i < len; i++) { - var node = indexSymbol.declarations[i]; + for (let decl of indexSymbol.declarations) { + var node = decl; if (node.parameters.length === 1) { var parameter = node.parameters[0]; if (parameter && parameter.type && parameter.type.kind === syntaxKind) { @@ -4556,7 +4556,9 @@ module ts { function isInProcess(source: Type, target: Type) { for (var i = 0; i < depth; i++) { - if (source === sourceStack[i] && target === targetStack[i]) return true; + if (source === sourceStack[i] && target === targetStack[i]) { + return true; + } } return false; } @@ -4567,7 +4569,9 @@ module ts { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & TypeFlags.Reference && (t).target === target) count++; + if (t.flags & TypeFlags.Reference && (t).target === target) { + count++; + } } return count < 5; } From 2383fcfb25bcf8e05b958c35d038b1c6f20a3bea Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:49:32 -0700 Subject: [PATCH 12/19] Use 'let' in core.ts. --- src/compiler/core.ts | 145 ++++++++++++++++++++++--------------------- 1 file changed, 74 insertions(+), 71 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 8939262b6d6..27fc152f534 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -26,7 +26,7 @@ module 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++) { - var result = callback(array[i], i); + let result = callback(array[i], i); if (result) { return result; } @@ -48,7 +48,7 @@ module ts { export function indexOf(array: T[], value: T): number { if (array) { - for (var i = 0, len = array.length; i < len; i++) { + for (let i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } @@ -58,7 +58,7 @@ module ts { } export function countWhere(array: T[], predicate: (x: T) => boolean): number { - var count = 0; + let count = 0; if (array) { for (let v of array) { if (predicate(v)) { @@ -69,9 +69,10 @@ module ts { return count; } - export function filter(array: T[], f: (x: T) => boolean): T[] { + export function filter(array: T[], f: (x: T) => boolean): T[]{ + let result: T[]; if (array) { - var result: T[] = []; + result = []; for (let item of array) { if (f(item)) { result.push(item); @@ -81,9 +82,10 @@ module ts { return result; } - export function map(array: T[], f: (x: T) => U): U[] { + export function map(array: T[], f: (x: T) => U): U[]{ + let result: U[]; if (array) { - var result: U[] = []; + result = []; for (let v of array) { result.push(f(v)); } @@ -98,9 +100,10 @@ module ts { return array1.concat(array2); } - export function deduplicate(array: T[]): T[] { + export function deduplicate(array: T[]): T[]{ + let result: T[]; if (array) { - var result: T[] = []; + result = []; for (let item of array) { if (!contains(result, item)) { result.push(item); @@ -111,7 +114,7 @@ module ts { } export function sum(array: any[], prop: string): number { - var result = 0; + let result = 0; for (let v of array) { result += v[prop]; } @@ -136,12 +139,12 @@ module ts { } export function binarySearch(array: number[], value: number): number { - var low = 0; - var high = array.length - 1; + let low = 0; + let high = array.length - 1; while (low <= high) { - var middle = low + ((high - low) >> 1); - var midValue = array[middle]; + let middle = low + ((high - low) >> 1); + let midValue = array[middle]; if (midValue === value) { return middle; @@ -157,7 +160,7 @@ module ts { return ~low; } - var hasOwnProperty = Object.prototype.hasOwnProperty; + let hasOwnProperty = Object.prototype.hasOwnProperty; export function hasProperty(map: Map, key: string): boolean { return hasOwnProperty.call(map, key); @@ -168,7 +171,7 @@ module ts { } export function isEmpty(map: Map) { - for (var id in map) { + for (let id in map) { if (hasProperty(map, id)) { return false; } @@ -177,19 +180,19 @@ module ts { } export function clone(object: T): T { - var result: any = {}; - for (var id in object) { + let result: any = {}; + for (let id in object) { result[id] = (object)[id]; } return result; } export function extend(first: Map, second: Map): Map { - var result: Map = {}; - for (var id in first) { + let result: Map = {}; + for (let id in first) { result[id] = first[id]; } - for (var id in second) { + for (let id in second) { if (!hasProperty(result, id)) { result[id] = second[id]; } @@ -198,16 +201,16 @@ module ts { } export function forEachValue(map: Map, callback: (value: T) => U): U { - var result: U; - for (var id in map) { + let result: U; + for (let id in map) { if (result = callback(map[id])) break; } return result; } export function forEachKey(map: Map, callback: (key: string) => U): U { - var result: U; - for (var id in map) { + let result: U; + for (let id in map) { if (result = callback(id)) break; } return result; @@ -218,9 +221,9 @@ module ts { } export function mapToArray(map: Map): T[] { - var result: T[] = []; + let result: T[] = []; - for (var id in map) { + for (let id in map) { result.push(map[id]); } @@ -228,7 +231,7 @@ module ts { } export function copyMap(source: Map, target: Map): void { - for (var p in source) { + for (let p in source) { target[p] = source[p]; } } @@ -244,7 +247,7 @@ module ts { * index in the array will be the one associated with the produced key. */ export function arrayToMap(array: T[], makeKey: (value: T) => string): Map { - var result: Map = {}; + let result: Map = {}; forEach(array, value => { result[makeKey(value)] = value; @@ -259,7 +262,7 @@ module ts { return text.replace(/{(\d+)}/g, (match, index?) => args[+index + baseIndex]); } - export var localizedDiagnosticMessages: Map = undefined; + export let localizedDiagnosticMessages: Map = undefined; export function getLocaleSpecificMessage(message: string) { return localizedDiagnosticMessages && localizedDiagnosticMessages[message] @@ -269,14 +272,14 @@ module 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 { - var end = start + length; + let 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); Debug.assert(start <= file.text.length, `start must be within the bounds of the file. ${ start } > ${ file.text.length }`); Debug.assert(end <= file.text.length, `end must be the bounds of the file. ${ end } > ${ file.text.length }`); - var text = getLocaleSpecificMessage(message.key); + let text = getLocaleSpecificMessage(message.key); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); @@ -295,7 +298,7 @@ module ts { export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { - var text = getLocaleSpecificMessage(message.key); + let text = getLocaleSpecificMessage(message.key); if (arguments.length > 1) { text = formatStringFromArgs(text, arguments, 1); @@ -314,7 +317,7 @@ module ts { export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; export function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage): DiagnosticMessageChain { - var text = getLocaleSpecificMessage(message.key); + let text = getLocaleSpecificMessage(message.key); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); @@ -358,10 +361,10 @@ module ts { function compareMessageText(text1: string | DiagnosticMessageChain, text2: string | DiagnosticMessageChain): Comparison { while (text1 && text2) { // We still have both chains. - var string1 = typeof text1 === "string" ? text1 : text1.messageText; - var string2 = typeof text2 === "string" ? text2 : text2.messageText; + let string1 = typeof text1 === "string" ? text1 : text1.messageText; + let string2 = typeof text2 === "string" ? text2 : text2.messageText; - var res = compareValues(string1, string2); + let res = compareValues(string1, string2); if (res) { return res; } @@ -388,11 +391,11 @@ module ts { return diagnostics; } - var newDiagnostics = [diagnostics[0]]; - var previousDiagnostic = diagnostics[0]; - for (var i = 1; i < diagnostics.length; i++) { - var currentDiagnostic = diagnostics[i]; - var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === Comparison.EqualTo; + let 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; if (!isDupe) { newDiagnostics.push(currentDiagnostic); previousDiagnostic = currentDiagnostic; @@ -410,9 +413,9 @@ module ts { export function getRootLength(path: string): number { if (path.charCodeAt(0) === CharacterCodes.slash) { if (path.charCodeAt(1) !== CharacterCodes.slash) return 1; - var p1 = path.indexOf("/", 2); + let p1 = path.indexOf("/", 2); if (p1 < 0) return 2; - var p2 = path.indexOf("/", p1 + 1); + let p2 = path.indexOf("/", p1 + 1); if (p2 < 0) return p1 + 1; return p2 + 1; } @@ -423,10 +426,10 @@ module ts { return 0; } - export var directorySeparator = "/"; + export let directorySeparator = "/"; function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { - var parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); - var normalized: string[] = []; + let parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); + let normalized: string[] = []; for (let part of parts) { if (part !== ".") { if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { @@ -446,9 +449,9 @@ module ts { } export function normalizePath(path: string): string { - var path = normalizeSlashes(path); - var rootLength = getRootLength(path); - var normalized = getNormalizedParts(path, rootLength); + path = normalizeSlashes(path); + let rootLength = getRootLength(path); + let normalized = getNormalizedParts(path, rootLength); return path.substr(0, rootLength) + normalized.join(directorySeparator); } @@ -465,13 +468,13 @@ module ts { } function normalizedPathComponents(path: string, rootLength: number) { - var normalizedParts = getNormalizedParts(path, rootLength); + let normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); } export function getNormalizedPathComponents(path: string, currentDirectory: string) { - var path = normalizeSlashes(path); - var rootLength = getRootLength(path); + path = normalizeSlashes(path); + let rootLength = getRootLength(path); if (rootLength == 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path); @@ -496,9 +499,9 @@ module ts { // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - var urlLength = url.length; + let urlLength = url.length; // Initial root length is http:// part - var rootLength = url.indexOf("://") + "://".length; + let rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { // Consume all immediate slashes in the protocol // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// @@ -517,7 +520,7 @@ module ts { } // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - var indexOfNextSlash = url.indexOf(directorySeparator, rootLength); + let 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 @@ -543,8 +546,8 @@ module ts { } export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); + let pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); + let directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { // 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"] @@ -560,8 +563,8 @@ module ts { // Get the relative path if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); + let relativePath = ""; + let relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { if (directoryComponents[joinStartIndex] !== "") { relativePath = relativePath + ".." + directorySeparator; @@ -572,7 +575,7 @@ module ts { } // Cant find the relative path, get the absolute path - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); + let absolutePath = getNormalizedPathFromPathComponents(pathComponents); if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { absolutePath = "file:///" + absolutePath; } @@ -581,7 +584,7 @@ module ts { } export function getBaseFileName(path: string) { - var i = path.lastIndexOf(directorySeparator); + let i = path.lastIndexOf(directorySeparator); return i < 0 ? path : path.substring(i + 1); } @@ -594,12 +597,12 @@ module ts { } export function fileExtensionIs(path: string, extension: string): boolean { - var pathLen = path.length; - var extLen = extension.length; + let pathLen = path.length; + let extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } - var supportedExtensions = [".d.ts", ".ts", ".js"]; + let supportedExtensions = [".d.ts", ".ts", ".js"]; export function removeFileExtension(path: string): string { for (let ext of supportedExtensions) { @@ -612,9 +615,9 @@ module ts { return path; } - var backslashOrDoubleQuote = /[\"\\]/g; - var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap: Map = { + let backslashOrDoubleQuote = /[\"\\]/g; + let escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + let escapedCharsMap: Map = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -653,7 +656,7 @@ module ts { function Signature(checker: TypeChecker) { } - export var objectAllocator: ObjectAllocator = { + export let objectAllocator: ObjectAllocator = { getNodeConstructor: kind => { function Node() { } @@ -679,7 +682,7 @@ module ts { } export module Debug { - var currentAssertionLevel = AssertionLevel.None; + let currentAssertionLevel = AssertionLevel.None; export function shouldAssert(level: AssertionLevel): boolean { return currentAssertionLevel >= level; @@ -687,7 +690,7 @@ module ts { export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void { if (!expression) { - var verboseDebugString = ""; + let verboseDebugString = ""; if (verboseDebugInfo) { verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); } From a4bf56f2116e6c686420b339cc495e55b4695501 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:54:54 -0700 Subject: [PATCH 13/19] Use 'let' in the scanner. --- src/compiler/scanner.ts | 174 ++++++++++++++++++++-------------------- 1 file changed, 87 insertions(+), 87 deletions(-) diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 9bb66f10f41..835a5b838d0 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -37,7 +37,7 @@ module ts { tryScan(callback: () => T): T; } - var textToToken: Map = { + let textToToken: Map = { "any": SyntaxKind.AnyKeyword, "as": SyntaxKind.AsKeyword, "boolean": SyntaxKind.BooleanKeyword, @@ -170,8 +170,8 @@ module 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 */ - var 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, ]; - var 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, ]; + 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, ]; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers @@ -195,8 +195,8 @@ module 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 */ - var 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, ]; - var 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, ]; + 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, ]; function lookupInUnicodeMap(code: number, map: number[]): boolean { // Bail out quickly if it couldn't possibly be in the map. @@ -205,9 +205,9 @@ module ts { } // Perform binary search in one of the Unicode range maps - var lo: number = 0; - var hi: number = map.length; - var mid: number; + let lo: number = 0; + let hi: number = map.length; + let mid: number; while (lo + 1 < hi) { mid = lo + (hi - lo) / 2; @@ -241,8 +241,8 @@ module ts { } function makeReverseMap(source: Map): string[] { - var result: string[] = []; - for (var name in source) { + let result: string[] = []; + for (let name in source) { if (source.hasOwnProperty(name)) { result[source[name]] = name; } @@ -250,18 +250,18 @@ module ts { return result; } - var tokenStrings = makeReverseMap(textToToken); + let tokenStrings = makeReverseMap(textToToken); export function tokenToString(t: SyntaxKind): string { return tokenStrings[t]; } export function computeLineStarts(text: string): number[] { - var result: number[] = new Array(); - var pos = 0; - var lineStart = 0; + let result: number[] = new Array(); + let pos = 0; + let lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + let ch = text.charCodeAt(pos++); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos) === CharacterCodes.lineFeed) { @@ -297,7 +297,7 @@ module ts { } export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) { - var lineNumber = binarySearch(lineStarts, position); + let lineNumber = binarySearch(lineStarts, position); if (lineNumber < 0) { // If the actual position was not found, // the binary search returns the negative value of the next line start @@ -315,7 +315,7 @@ module ts { return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); } - var hasOwnProperty = Object.prototype.hasOwnProperty; + let hasOwnProperty = Object.prototype.hasOwnProperty; export function isWhiteSpace(ch: number): boolean { return ch === CharacterCodes.space || ch === CharacterCodes.tab || ch === CharacterCodes.verticalTab || ch === CharacterCodes.formFeed || @@ -337,7 +337,7 @@ module ts { export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number { while (true) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { @@ -401,17 +401,17 @@ module ts { // All conflict markers consist of the same character repeated seven times. If it is // a <<<<<<< or >>>>>>> marker then it is also followd by a space. - var mergeConflictMarkerLength = "<<<<<<<".length; + let 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))) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); if ((pos + mergeConflictMarkerLength) < text.length) { - for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) { + for (let i = 0, n = mergeConflictMarkerLength; i < n; i++) { if (text.charCodeAt(pos + i) !== ch) { return false; } @@ -430,8 +430,8 @@ module ts { error(Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); } - var ch = text.charCodeAt(pos); - var len = text.length; + let ch = text.charCodeAt(pos); + let len = text.length; if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { while (pos < len && !isLineBreak(text.charCodeAt(pos))) { @@ -443,7 +443,7 @@ module ts { // Consume everything from the start of the mid-conlict marker to the start of the next // end-conflict marker. while (pos < len) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); if (ch === CharacterCodes.greaterThan && isConflictMarkerTrivia(text, pos)) { break; } @@ -461,10 +461,10 @@ module ts { // comment. Single-line comment ranges include the beginning '//' characters but not the ending line break. Multi-line comment // ranges include the beginning '/* and ending '*/' characters. The return value is undefined if no comments were found. function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] { - var result: CommentRange[]; - var collecting = trailing || pos === 0; + let result: CommentRange[]; + let collecting = trailing || pos === 0; while (true) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) pos++; @@ -485,10 +485,10 @@ module ts { pos++; continue; case CharacterCodes.slash: - var nextChar = text.charCodeAt(pos + 1); - var hasTrailingNewLine = false; + let nextChar = text.charCodeAt(pos + 1); + let hasTrailingNewLine = false; if (nextChar === CharacterCodes.slash || nextChar === CharacterCodes.asterisk) { - var startPos = pos; + let startPos = pos; pos += 2; if (nextChar === CharacterCodes.slash) { while (pos < text.length) { @@ -550,15 +550,15 @@ module ts { } export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback): Scanner { - var pos: number; // Current position (end position of text of current token) - var len: number; // Length of text - var startPos: number; // Start position of whitespace before current token - var tokenPos: number; // Start position of text of current token - var token: SyntaxKind; - var tokenValue: string; - var precedingLineBreak: boolean; - var hasExtendedUnicodeEscape: boolean; - var tokenIsUnterminated: boolean; + let pos: number; // Current position (end position of text of current token) + let len: number; // Length of text + let startPos: number; // Start position of whitespace before current token + let tokenPos: number; // Start position of text of current token + let token: SyntaxKind; + let tokenValue: string; + let precedingLineBreak: boolean; + let hasExtendedUnicodeEscape: boolean; + let tokenIsUnterminated: boolean; function error(message: DiagnosticMessage, length?: number): void { if (onError) { @@ -579,13 +579,13 @@ module ts { } function scanNumber(): number { - var start = pos; + let start = pos; while (isDigit(text.charCodeAt(pos))) pos++; if (text.charCodeAt(pos) === CharacterCodes.dot) { pos++; while (isDigit(text.charCodeAt(pos))) pos++; } - var end = pos; + let end = pos; if (text.charCodeAt(pos) === CharacterCodes.E || text.charCodeAt(pos) === CharacterCodes.e) { pos++; if (text.charCodeAt(pos) === CharacterCodes.plus || text.charCodeAt(pos) === CharacterCodes.minus) pos++; @@ -602,7 +602,7 @@ module ts { } function scanOctalDigits(): number { - var start = pos; + let start = pos; while (isOctalDigit(text.charCodeAt(pos))) { pos++; } @@ -626,10 +626,10 @@ module ts { } function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean): number { - var digits = 0; - var value = 0; + let digits = 0; + let value = 0; while (digits < minCount || scanAsManyAsPossible) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); if (ch >= CharacterCodes._0 && ch <= CharacterCodes._9) { value = value * 16 + ch - CharacterCodes._0; } @@ -652,9 +652,9 @@ module ts { } function scanString(): string { - var quote = text.charCodeAt(pos++); - var result = ""; - var start = pos; + let quote = text.charCodeAt(pos++); + let result = ""; + let start = pos; while (true) { if (pos >= len) { result += text.substring(start, pos); @@ -662,7 +662,7 @@ module ts { error(Diagnostics.Unterminated_string_literal); break; } - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); if (ch === quote) { result += text.substring(start, pos); pos++; @@ -690,12 +690,12 @@ module ts { * a literal component of a TemplateExpression. */ function scanTemplateAndSetTokenValue(): SyntaxKind { - var startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick; + let startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick; pos++; - var start = pos; - var contents = "" - var resultingToken: SyntaxKind; + let start = pos; + let contents = "" + let resultingToken: SyntaxKind; while (true) { if (pos >= len) { @@ -706,7 +706,7 @@ module ts { break; } - var currChar = text.charCodeAt(pos); + let currChar = text.charCodeAt(pos); // '`' if (currChar === CharacterCodes.backtick) { @@ -762,7 +762,7 @@ module ts { error(Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + let ch = text.charCodeAt(pos++); switch (ch) { case CharacterCodes._0: return "\0"; @@ -814,7 +814,7 @@ module ts { } function scanHexadecimalEscape(numDigits: number): string { - var escapedValue = scanExactNumberOfHexDigits(numDigits); + let escapedValue = scanExactNumberOfHexDigits(numDigits); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); @@ -826,8 +826,8 @@ module ts { } function scanExtendedUnicodeEscape(): string { - var escapedValue = scanMinimumNumberOfHexDigits(1); - var isInvalidExtendedEscape = false; + let escapedValue = scanMinimumNumberOfHexDigits(1); + let isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { @@ -867,8 +867,8 @@ module ts { return String.fromCharCode(codePoint); } - var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; - var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + let codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + let codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; return String.fromCharCode(codeUnit1, codeUnit2); } @@ -877,9 +877,9 @@ module ts { // and return code point value if valid Unicode escape is found. Otherwise return -1. function peekUnicodeEscape(): number { if (pos + 5 < len && text.charCodeAt(pos + 1) === CharacterCodes.u) { - var start = pos; + let start = pos; pos += 2; - var value = scanExactNumberOfHexDigits(4); + let value = scanExactNumberOfHexDigits(4); pos = start; return value; } @@ -887,10 +887,10 @@ module ts { } function scanIdentifierParts(): string { - var result = ""; - var start = pos; + let result = ""; + let start = pos; while (pos < len) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); if (isIdentifierPart(ch)) { pos++; } @@ -915,9 +915,9 @@ module ts { function getIdentifierToken(): SyntaxKind { // Reserved words are between 2 and 11 characters long and start with a lowercase letter - var len = tokenValue.length; + let len = tokenValue.length; if (len >= 2 && len <= 11) { - var ch = tokenValue.charCodeAt(0); + let ch = tokenValue.charCodeAt(0); if (ch >= CharacterCodes.a && ch <= CharacterCodes.z && hasOwnProperty.call(textToToken, tokenValue)) { return token = textToToken[tokenValue]; } @@ -928,13 +928,13 @@ module ts { function scanBinaryOrOctalDigits(base: number): number { Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); - var value = 0; + let value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - var numberOfDigits = 0; + let numberOfDigits = 0; while (true) { - var ch = text.charCodeAt(pos); - var valueOfCh = ch - CharacterCodes._0; + let ch = text.charCodeAt(pos); + let valueOfCh = ch - CharacterCodes._0; if (!isDigit(ch) || valueOfCh >= base) { break; } @@ -1079,9 +1079,9 @@ module ts { if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) { pos += 2; - var commentClosed = false; + let commentClosed = false; while (pos < len) { - var ch = text.charCodeAt(pos); + let ch = text.charCodeAt(pos); if (ch === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { pos += 2; @@ -1117,7 +1117,7 @@ module ts { case CharacterCodes._0: if (pos + 2 < len && (text.charCodeAt(pos + 1) === CharacterCodes.X || text.charCodeAt(pos + 1) === CharacterCodes.x)) { pos += 2; - var value = scanMinimumNumberOfHexDigits(1); + let value = scanMinimumNumberOfHexDigits(1); if (value < 0) { error(Diagnostics.Hexadecimal_digit_expected); value = 0; @@ -1127,7 +1127,7 @@ module ts { } else if (pos + 2 < len && (text.charCodeAt(pos + 1) === CharacterCodes.B || text.charCodeAt(pos + 1) === CharacterCodes.b)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 2); + let value = scanBinaryOrOctalDigits(/* base */ 2); if (value < 0) { error(Diagnostics.Binary_digit_expected); value = 0; @@ -1137,7 +1137,7 @@ module ts { } else if (pos + 2 < len && (text.charCodeAt(pos + 1) === CharacterCodes.O || text.charCodeAt(pos + 1) === CharacterCodes.o)) { pos += 2; - var value = scanBinaryOrOctalDigits(/* base */ 8); + let value = scanBinaryOrOctalDigits(/* base */ 8); if (value < 0) { error(Diagnostics.Octal_digit_expected); value = 0; @@ -1304,9 +1304,9 @@ module ts { function reScanSlashToken(): SyntaxKind { if (token === SyntaxKind.SlashToken || token === SyntaxKind.SlashEqualsToken) { - var p = tokenPos + 1; - var inEscape = false; - var inCharacterClass = false; + let p = tokenPos + 1; + let inEscape = false; + let inCharacterClass = false; while (true) { // If we reach the end of a file, or hit a newline, then this is an unterminated // regex. Report error and return what we have so far. @@ -1316,7 +1316,7 @@ module ts { break; } - var ch = text.charCodeAt(p); + let ch = text.charCodeAt(p); if (isLineBreak(ch)) { tokenIsUnterminated = true; error(Diagnostics.Unterminated_regular_expression_literal) @@ -1366,13 +1366,13 @@ module ts { } function speculationHelper(callback: () => T, isLookahead: boolean): T { - var savePos = pos; - var saveStartPos = startPos; - var saveTokenPos = tokenPos; - var saveToken = token; - var saveTokenValue = tokenValue; - var savePrecedingLineBreak = precedingLineBreak; - var result = callback(); + let savePos = pos; + let saveStartPos = startPos; + let saveTokenPos = tokenPos; + let saveToken = token; + let saveTokenValue = tokenValue; + let savePrecedingLineBreak = precedingLineBreak; + let result = callback(); // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. From 0f498ab414638ece5d0520dd29d0f568237eb838 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 10:59:25 -0700 Subject: [PATCH 14/19] Use 'let' in the parser. --- src/compiler/parser.ts | 586 ++++++++++++++++++++--------------------- 1 file changed, 293 insertions(+), 293 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 3fcd5fd9fda..474203702ed 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2,8 +2,8 @@ /// module ts { - var nodeConstructors = new Array Node>(SyntaxKind.Count); - /* @internal */ export var parseTime = 0; + let nodeConstructors = new Array Node>(SyntaxKind.Count); + /* @internal */ export let parseTime = 0; export function getNodeConstructor(kind: SyntaxKind): new () => Node { return nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind)); @@ -28,7 +28,7 @@ module ts { function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { if (nodes) { for (let node of nodes) { - var result = cbNode(node); + let result = cbNode(node); if (result) { return result; } @@ -47,8 +47,8 @@ module 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. - var visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; - var cbNodes = cbNodeArray || cbNode; + let visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; + let cbNodes = cbNodeArray || cbNode; switch (node.kind) { case SyntaxKind.QualifiedName: return visitNode(cbNode, (node).left) || @@ -373,7 +373,7 @@ module ts { // overhead. This functions allows us to set all the parents, without all the expense of // binding. - var parent: Node = sourceFile; + let parent: Node = sourceFile; forEachChild(sourceFile, visitNode); return; @@ -384,7 +384,7 @@ module ts { if (n.parent !== parent) { n.parent = parent; - var saveParent = parent; + let saveParent = parent; parent = n; forEachChild(n, visitNode); parent = saveParent; @@ -519,7 +519,7 @@ module ts { function checkNodePositions(node: Node, aggressiveChecks: boolean) { if (aggressiveChecks) { - var pos = node.pos; + let pos = node.pos; forEachChild(node, child => { Debug.assert(child.pos >= pos); pos = child.end; @@ -553,7 +553,7 @@ module 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. - var fullEnd = child.end; + let fullEnd = child.end; if (fullEnd >= changeStart) { child.intersectsChange = true; child._children = undefined; @@ -582,7 +582,7 @@ module 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. - var fullEnd = array.end; + let fullEnd = array.end; if (fullEnd >= changeStart) { array.intersectsChange = true; array._children = undefined; @@ -611,35 +611,35 @@ module 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. - var maxLookahead = 1; + let maxLookahead = 1; - var start = changeRange.span.start; + let start = changeRange.span.start; // the first iteration aligns us with the change start. subsequent iteration move us to // the left by maxLookahead tokens. We only need to do this as long as we're not at the // start of the tree. - for (var i = 0; start > 0 && i <= maxLookahead; i++) { - var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + for (let i = 0; start > 0 && i <= maxLookahead; i++) { + let nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); Debug.assert(nearestNode.pos <= start); - var position = nearestNode.pos; + let position = nearestNode.pos; start = Math.max(0, position - 1); } - var finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); - var finalLength = changeRange.newLength + (changeRange.span.start - start); + let finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); + let finalLength = changeRange.newLength + (changeRange.span.start - start); return createTextChangeRange(finalSpan, finalLength); } function findNearestNodeStartingBeforeOrAtPosition(sourceFile: SourceFile, position: number): Node { - var bestResult: Node = sourceFile; - var lastNodeEntirelyBeforePosition: Node; + let bestResult: Node = sourceFile; + let lastNodeEntirelyBeforePosition: Node; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + let lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } @@ -649,7 +649,7 @@ module ts { function getLastChild(node: Node): Node { while (true) { - var lastChild = getLastChildWorker(node); + let lastChild = getLastChildWorker(node); if (lastChild) { node = lastChild; } @@ -660,7 +660,7 @@ module ts { } function getLastChildWorker(node: Node): Node { - var last: Node = undefined; + let last: Node = undefined; forEachChild(node, child => { if (nodeIsPresent(child)) { last = child; @@ -728,17 +728,17 @@ module ts { } function checkChangeRange(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks: boolean) { - var oldText = sourceFile.text; + let oldText = sourceFile.text; if (textChangeRange) { Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); if (aggressiveChecks || Debug.shouldAssert(AssertionLevel.VeryAggressive)) { - var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - var newTextPrefix = newText.substr(0, textChangeRange.span.start); + let oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + let newTextPrefix = newText.substr(0, textChangeRange.span.start); Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); - var newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); + let oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); + let newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); Debug.assert(oldTextSuffix === newTextSuffix); } } @@ -774,16 +774,16 @@ module 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. - var incrementalSourceFile = sourceFile; + let incrementalSourceFile = sourceFile; Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); incrementalSourceFile.hasBeenIncrementallyParsed = true; - var oldText = sourceFile.text; - var syntaxCursor = createSyntaxCursor(sourceFile); + let oldText = sourceFile.text; + let syntaxCursor = createSyntaxCursor(sourceFile); // Make the actual change larger so that we know to reparse anything whose lookahead // might have intersected the change. - var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + let changeRange = extendToAffectedRange(sourceFile, textChangeRange); checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); // Ensure that extending the affected range only moved the start of the change range @@ -795,7 +795,7 @@ module 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). - var delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + let 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 @@ -829,7 +829,7 @@ module 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. - var result = parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true) + let result = parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true) return result; } @@ -842,7 +842,7 @@ module ts { /// Should be called only on prologue directives (isPrologueDirective(node) should be true) function isUseStrictPrologueDirective(sourceFile: SourceFile, node: Node): boolean { Debug.assert(isPrologueDirective(node)); - var nodeText = getSourceTextOfNodeFromSourceFile(sourceFile,(node).expression); + let nodeText = getSourceTextOfNodeFromSourceFile(sourceFile,(node).expression); // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the // string to contain unicode escapes (as per ES5). @@ -876,12 +876,12 @@ module ts { } function createSyntaxCursor(sourceFile: SourceFile): SyntaxCursor { - var currentArray: NodeArray = sourceFile.statements; - var currentArrayIndex = 0; + let currentArray: NodeArray = sourceFile.statements; + let currentArrayIndex = 0; Debug.assert(currentArrayIndex < currentArray.length); - var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = InvalidPosition.Value; + let current = currentArray[currentArrayIndex]; + let lastQueriedPosition = InvalidPosition.Value; return { currentNode(position: number) { @@ -949,7 +949,7 @@ module 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++) { - var child = array[i]; + let child = array[i]; if (child) { if (child.pos === position) { // Found the right node. We're done. @@ -977,21 +977,21 @@ module ts { } export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false): SourceFile { - var start = new Date().getTime(); - var result = parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + let start = new Date().getTime(); + let result = parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); parseTime += new Date().getTime() - start; return result; } function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: SyntaxCursor, setParentNodes = false): SourceFile { - var parsingContext: ParsingContext = 0; - var identifiers: Map = {}; - var identifierCount = 0; - var nodeCount = 0; - var token: SyntaxKind; + let parsingContext: ParsingContext = 0; + let identifiers: Map = {}; + let identifierCount = 0; + let nodeCount = 0; + let token: SyntaxKind; - var sourceFile = createNode(SyntaxKind.SourceFile, /*pos*/ 0); + let sourceFile = createNode(SyntaxKind.SourceFile, /*pos*/ 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; @@ -1049,7 +1049,7 @@ module ts { // Note: it should not be necessary to save/restore these flags during speculative/lookahead // parsing. These context flags are naturally stored and restored through normal recursive // descent parsing and unwinding. - var contextFlags: ParserContextFlags = 0; + let contextFlags: ParserContextFlags = 0; // Whether or not we've had a parse error since creating the last AST node. If we have // encountered an error, it will be stored on the next AST node we create. Parse errors @@ -1078,10 +1078,10 @@ module ts { // // Note: any errors at the end of the file that do not precede a regular node, should get // attached to the EOF token. - var parseErrorBeforeNextFinishedNode: boolean = false; + let parseErrorBeforeNextFinishedNode: boolean = false; // Create and prime the scanner before parsing the source elements. - var scanner = createScanner(languageVersion, /*skipTrivia*/ true, sourceText, scanError); + let scanner = createScanner(languageVersion, /*skipTrivia*/ true, sourceText, scanError); token = nextToken(); processReferenceComments(sourceFile); @@ -1131,7 +1131,7 @@ module ts { function allowInAnd(func: () => T): T { if (contextFlags & ParserContextFlags.DisallowIn) { setDisallowInContext(false); - var result = func(); + let result = func(); setDisallowInContext(true); return result; } @@ -1147,7 +1147,7 @@ module ts { } setDisallowInContext(true); - var result = func(); + let result = func(); setDisallowInContext(false); return result; } @@ -1159,7 +1159,7 @@ module ts { } setYieldContext(true); - var result = func(); + let result = func(); setYieldContext(false); return result; } @@ -1167,7 +1167,7 @@ module ts { function doOutsideOfYieldContext(func: () => T): T { if (contextFlags & ParserContextFlags.Yield) { setYieldContext(false); - var result = func(); + let result = func(); setYieldContext(true); return result; } @@ -1193,15 +1193,15 @@ module ts { } function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; + let start = scanner.getTokenPos(); + let 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. - var lastError = lastOrUndefined(sourceFile.parseDiagnostics); + let lastError = lastOrUndefined(sourceFile.parseDiagnostics); if (!lastError || start !== lastError.start) { sourceFile.parseDiagnostics.push(createFileDiagnostic(sourceFile, start, length, message, arg0)); } @@ -1212,7 +1212,7 @@ module ts { } function scanError(message: DiagnosticMessage, length?: number) { - var pos = scanner.getTextPos(); + let pos = scanner.getTextPos(); parseErrorAtPosition(pos, length || 0, message); } @@ -1247,20 +1247,20 @@ module 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). - var saveToken = token; - var saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + let saveToken = token; + let saveParseDiagnosticsLength = sourceFile.parseDiagnostics.length; + let saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restorating 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. - var saveContextFlags = contextFlags; + let 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. - var result = isLookAhead + let result = isLookAhead ? scanner.lookAhead(callback) : scanner.tryScan(callback); @@ -1343,7 +1343,7 @@ module ts { } function parseTokenNode(): T { - var node = createNode(token); + let node = createNode(token); nextToken(); return finishNode(node); } @@ -1374,7 +1374,7 @@ module ts { function createNode(kind: SyntaxKind, pos?: number): Node { nodeCount++; - var node = new (nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind)))(); + let node = new (nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind)))(); if (!(pos >= 0)) { pos = scanner.getStartPos(); } @@ -1410,7 +1410,7 @@ module ts { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - var result = createNode(kind, scanner.getStartPos()); + let result = createNode(kind, scanner.getStartPos()); (result).text = ""; return finishNode(result); } @@ -1426,7 +1426,7 @@ module ts { function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage): Identifier { identifierCount++; if (isIdentifier) { - var node = createNode(SyntaxKind.Identifier); + let node = createNode(SyntaxKind.Identifier); node.text = internIdentifier(scanner.getTokenValue()); nextToken(); return finishNode(node); @@ -1468,13 +1468,13 @@ module ts { // ComputedPropertyName[Yield] : // [ AssignmentExpression[In, ?Yield] ] // - var node = createNode(SyntaxKind.ComputedPropertyName); + let node = createNode(SyntaxKind.ComputedPropertyName); parseExpected(SyntaxKind.OpenBracketToken); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. - var yieldContext = inYieldContext(); + let yieldContext = inYieldContext(); if (inGeneratorParameterContext()) { setYieldContext(false); } @@ -1534,7 +1534,7 @@ module ts { // True if positioned at the start of a list element function isListElement(parsingContext: ParsingContext, inErrorRecovery: boolean): boolean { - var node = currentNode(parsingContext); + let node = currentNode(parsingContext); if (node) { return true; } @@ -1674,7 +1674,7 @@ module ts { // True if positioned at element or terminator of the current list or any enclosing list function isInSomeParsingContext(): boolean { - for (var kind = 0; kind < ParsingContext.Count; kind++) { + for (let kind = 0; kind < ParsingContext.Count; kind++) { if (parsingContext & (1 << kind)) { if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { return true; @@ -1687,15 +1687,15 @@ module ts { // Parses a list of elements function parseList(kind: ParsingContext, checkForStrictMode: boolean, parseElement: () => T): NodeArray { - var saveParsingContext = parsingContext; + let saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = >[]; + let result = >[]; result.pos = getNodePos(); - var savedStrictModeContext = inStrictModeContext(); + let savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, /* inErrorRecovery */ false)) { - var element = parseListElement(kind, parseElement); + let element = parseListElement(kind, parseElement); result.push(element); // test elements only if we are not already in strict mode @@ -1726,7 +1726,7 @@ module ts { } function parseListElement(parsingContext: ParsingContext, parseElement: () => T): T { - var node = currentNode(parsingContext); + let node = currentNode(parsingContext); if (node) { return consumeNode(node); } @@ -1751,7 +1751,7 @@ module ts { return undefined; } - var node = syntaxCursor.currentNode(scanner.getStartPos()); + let node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. if (nodeIsMissing(node)) { @@ -1780,7 +1780,7 @@ module ts { // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; + let nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -1978,19 +1978,19 @@ module ts { // Very subtle incremental parsing bug. Consider the following code: // - // var v = new List < A, B + // let v = new List < A, B // // This is actually legal code. It's a list of variable declarators "v = new List() + // let v = new List < A, B >() // // then we have a problem. "v = new Listnode; + let variableDeclarator = node; return variableDeclarator.initializer === undefined; } @@ -2000,7 +2000,7 @@ module ts { } // See the comment in isReusableVariableDeclaration for why we do this. - var parameter = node; + let parameter = node; return parameter.initializer === undefined; } @@ -2017,12 +2017,12 @@ module ts { // Parses a comma-delimited list of elements function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimeter?: boolean): NodeArray { - var saveParsingContext = parsingContext; + let saveParsingContext = parsingContext; parsingContext |= 1 << kind; - var result = >[]; + let result = >[]; result.pos = getNodePos(); - var commaStart = -1; // Meaning the previous token was not a comma + let commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /* inErrorRecovery */ false)) { result.push(parseListElement(kind, parseElement)); @@ -2076,8 +2076,8 @@ module ts { } function createMissingList(): NodeArray { - var pos = getNodePos(); - var result = >[]; + let pos = getNodePos(); + let result = >[]; result.pos = pos; result.end = pos; return result; @@ -2085,7 +2085,7 @@ module ts { function parseBracketedList(kind: ParsingContext, parseElement: () => T, open: SyntaxKind, close: SyntaxKind): NodeArray { if (parseExpected(open)) { - var result = parseDelimitedList(kind, parseElement); + let result = parseDelimitedList(kind, parseElement); parseExpected(close); return result; } @@ -2095,9 +2095,9 @@ module ts { // The allowReservedWords parameter controls whether reserved words are permitted after the first dot function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName { - var entity: EntityName = parseIdentifier(diagnosticMessage); + let entity: EntityName = parseIdentifier(diagnosticMessage); while (parseOptional(SyntaxKind.DotToken)) { - var node = createNode(SyntaxKind.QualifiedName, entity.pos); + let node = createNode(SyntaxKind.QualifiedName, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -2126,7 +2126,7 @@ module ts { // In the first case though, ASI will not take effect because there is not a // line terminator after the keyword. if (scanner.hasPrecedingLineBreak() && scanner.isReservedWord()) { - var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + let matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -2140,12 +2140,12 @@ module ts { } function parseTemplateExpression(): TemplateExpression { - var template = createNode(SyntaxKind.TemplateExpression); + let template = createNode(SyntaxKind.TemplateExpression); template.head = parseLiteralNode(); Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind"); - var templateSpans = >[]; + let templateSpans = >[]; templateSpans.pos = getNodePos(); do { @@ -2160,10 +2160,10 @@ module ts { } function parseTemplateSpan(): TemplateSpan { - var span = createNode(SyntaxKind.TemplateSpan); + let span = createNode(SyntaxKind.TemplateSpan); span.expression = allowInAnd(parseExpression); - var literal: LiteralExpression; + let literal: LiteralExpression; if (token === SyntaxKind.CloseBraceToken) { reScanTemplateToken() @@ -2178,8 +2178,8 @@ module ts { } function parseLiteralNode(internName?: boolean): LiteralExpression { - var node = createNode(token); - var text = scanner.getTokenValue(); + let node = createNode(token); + let text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -2190,7 +2190,7 @@ module ts { node.isUnterminated = true; } - var tokenPos = scanner.getTokenPos(); + let tokenPos = scanner.getTokenPos(); nextToken(); finishNode(node); @@ -2213,7 +2213,7 @@ module ts { // TYPES function parseTypeReference(): TypeReferenceNode { - var node = createNode(SyntaxKind.TypeReference); + let node = createNode(SyntaxKind.TypeReference); node.typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token === SyntaxKind.LessThanToken) { node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); @@ -2222,14 +2222,14 @@ module ts { } function parseTypeQuery(): TypeQueryNode { - var node = createNode(SyntaxKind.TypeQuery); + let node = createNode(SyntaxKind.TypeQuery); parseExpected(SyntaxKind.TypeOfKeyword); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter(): TypeParameterDeclaration { - var node = createNode(SyntaxKind.TypeParameter); + let 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 @@ -2282,7 +2282,7 @@ module ts { } function parseParameter(): ParameterDeclaration { - var node = createNode(SyntaxKind.Parameter); + let node = createNode(SyntaxKind.Parameter); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); @@ -2328,7 +2328,7 @@ module ts { yieldAndGeneratorParameterContext: boolean, requireCompleteParameterList: boolean, signature: SignatureDeclaration): void { - var returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken; + let returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldAndGeneratorParameterContext, requireCompleteParameterList); @@ -2361,13 +2361,13 @@ module ts { // [+GeneratorParameter]BindingIdentifier[Yield]Initializer[In]opt // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt if (parseExpected(SyntaxKind.OpenParenToken)) { - var savedYieldContext = inYieldContext(); - var savedGeneratorParameterContext = inGeneratorParameterContext(); + let savedYieldContext = inYieldContext(); + let savedGeneratorParameterContext = inGeneratorParameterContext(); setYieldContext(yieldAndGeneratorParameterContext); setGeneratorParameterContext(yieldAndGeneratorParameterContext); - var result = parseDelimitedList(ParsingContext.Parameters, parseParameter); + let result = parseDelimitedList(ParsingContext.Parameters, parseParameter); setYieldContext(savedYieldContext); setGeneratorParameterContext(savedGeneratorParameterContext); @@ -2399,7 +2399,7 @@ module ts { } function parseSignatureMember(kind: SyntaxKind): SignatureDeclaration { - var node = createNode(kind); + let node = createNode(kind); if (kind === SyntaxKind.ConstructSignature) { parseExpected(SyntaxKind.NewKeyword); } @@ -2472,8 +2472,8 @@ module ts { } function parseIndexSignatureDeclaration(modifiers: ModifiersArray): IndexSignatureDeclaration { - var fullStart = modifiers ? modifiers.pos : scanner.getStartPos(); - var node = createNode(SyntaxKind.IndexSignature, fullStart); + let fullStart = modifiers ? modifiers.pos : scanner.getStartPos(); + let node = createNode(SyntaxKind.IndexSignature, fullStart); setModifiers(node, modifiers); node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); node.type = parseTypeAnnotation(); @@ -2482,12 +2482,12 @@ module ts { } function parsePropertyOrMethodSignature(): Declaration { - var fullStart = scanner.getStartPos(); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + let fullStart = scanner.getStartPos(); + let name = parsePropertyName(); + let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { - var method = createNode(SyntaxKind.MethodSignature, fullStart); + let method = createNode(SyntaxKind.MethodSignature, fullStart); method.name = name; method.questionToken = questionToken; @@ -2498,7 +2498,7 @@ module ts { return finishNode(method); } else { - var property = createNode(SyntaxKind.PropertySignature, fullStart); + let property = createNode(SyntaxKind.PropertySignature, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -2515,7 +2515,7 @@ module ts { return true; default: if (isModifier(token)) { - var result = lookAhead(isStartOfIndexSignatureDeclaration); + let result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; } @@ -2568,7 +2568,7 @@ module ts { // if it has the same text regardless of whether it is inside a class or an // object type. if (isModifier(token)) { - var result = tryParse(parseIndexSignatureWithModifiers); + let result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; } @@ -2581,7 +2581,7 @@ module ts { } function parseIndexSignatureWithModifiers() { - var modifiers = parseModifiers(); + let modifiers = parseModifiers(); return isIndexSignature() ? parseIndexSignatureDeclaration(modifiers) : undefined; @@ -2593,13 +2593,13 @@ module ts { } function parseTypeLiteral(): TypeLiteralNode { - var node = createNode(SyntaxKind.TypeLiteral); + let node = createNode(SyntaxKind.TypeLiteral); node.members = parseObjectTypeMembers(); return finishNode(node); } function parseObjectTypeMembers(): NodeArray { - var members: NodeArray; + let members: NodeArray; if (parseExpected(SyntaxKind.OpenBraceToken)) { members = parseList(ParsingContext.TypeMembers, /*checkForStrictMode*/ false, parseTypeMember); parseExpected(SyntaxKind.CloseBraceToken); @@ -2612,13 +2612,13 @@ module ts { } function parseTupleType(): TupleTypeNode { - var node = createNode(SyntaxKind.TupleType); + let node = createNode(SyntaxKind.TupleType); node.elementTypes = parseBracketedList(ParsingContext.TupleElementTypes, parseType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); return finishNode(node); } function parseParenthesizedType(): ParenthesizedTypeNode { - var node = createNode(SyntaxKind.ParenthesizedType); + let node = createNode(SyntaxKind.ParenthesizedType); parseExpected(SyntaxKind.OpenParenToken); node.type = parseType(); parseExpected(SyntaxKind.CloseParenToken); @@ -2626,7 +2626,7 @@ module ts { } function parseFunctionOrConstructorType(kind: SyntaxKind): FunctionOrConstructorTypeNode { - var node = createNode(kind); + let node = createNode(kind); if (kind === SyntaxKind.ConstructorType) { parseExpected(SyntaxKind.NewKeyword); } @@ -2635,7 +2635,7 @@ module ts { } function parseKeywordAndNoDot(): TypeNode { - var node = parseTokenNode(); + let node = parseTokenNode(); return token === SyntaxKind.DotToken ? undefined : node; } @@ -2647,7 +2647,7 @@ module ts { case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: // If these are followed by a dot, then parse these out as a dotted type reference instead. - var node = tryParse(parseKeywordAndNoDot); + let node = tryParse(parseKeywordAndNoDot); return node || parseTypeReference(); case SyntaxKind.VoidKeyword: return parseTokenNode(); @@ -2693,10 +2693,10 @@ module ts { } function parseArrayTypeOrHigher(): TypeNode { - var type = parseNonArrayType(); + let type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) { parseExpected(SyntaxKind.CloseBracketToken); - var node = createNode(SyntaxKind.ArrayType, type.pos); + let node = createNode(SyntaxKind.ArrayType, type.pos); node.elementType = type; type = finishNode(node); } @@ -2704,15 +2704,15 @@ module ts { } function parseUnionTypeOrHigher(): TypeNode { - var type = parseArrayTypeOrHigher(); + let type = parseArrayTypeOrHigher(); if (token === SyntaxKind.BarToken) { - var types = >[type]; + let types = >[type]; types.pos = type.pos; while (parseOptional(SyntaxKind.BarToken)) { types.push(parseArrayTypeOrHigher()); } types.end = getNodeEnd(); - var node = createNode(SyntaxKind.UnionType, type.pos); + let node = createNode(SyntaxKind.UnionType, type.pos); node.types = types; type = finishNode(node); } @@ -2760,13 +2760,13 @@ module ts { function parseType(): TypeNode { // The rules about 'yield' only apply to actual code/expression contexts. They don't // apply to 'type' contexts. So we disable these parameters here before moving on. - var savedYieldContext = inYieldContext(); - var savedGeneratorParameterContext = inGeneratorParameterContext(); + let savedYieldContext = inYieldContext(); + let savedGeneratorParameterContext = inGeneratorParameterContext(); setYieldContext(false); setGeneratorParameterContext(false); - var result = parseTypeWorker(); + let result = parseTypeWorker(); setYieldContext(savedYieldContext); setGeneratorParameterContext(savedGeneratorParameterContext); @@ -2847,8 +2847,8 @@ module ts { // AssignmentExpression[in] // Expression[in] , AssignmentExpression[in] - var expr = parseAssignmentExpressionOrHigher(); - var operatorToken: Node; + let expr = parseAssignmentExpressionOrHigher(); + let operatorToken: Node; while ((operatorToken = parseOptionalToken(SyntaxKind.CommaToken))) { expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } @@ -2899,7 +2899,7 @@ module 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. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression(); + let arrowExpression = tryParseParenthesizedArrowFunctionExpression(); if (arrowExpression) { return arrowExpression; } @@ -2913,7 +2913,7 @@ module 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. - var expr = parseBinaryExpressionOrHigher(/*precedence:*/ 0); + let 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 @@ -2976,7 +2976,7 @@ module ts { } function parseYieldExpression(): YieldExpression { - var node = createNode(SyntaxKind.YieldExpression); + let node = createNode(SyntaxKind.YieldExpression); // YieldExpression[In] : // yield @@ -3000,9 +3000,9 @@ module ts { function parseSimpleArrowFunctionExpression(identifier: Identifier): Expression { Debug.assert(token === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node = createNode(SyntaxKind.ArrowFunction, identifier.pos); + let node = createNode(SyntaxKind.ArrowFunction, identifier.pos); - var parameter = createNode(SyntaxKind.Parameter, identifier.pos); + let parameter = createNode(SyntaxKind.Parameter, identifier.pos); parameter.name = identifier; finishNode(parameter); @@ -3017,7 +3017,7 @@ module ts { } function tryParseParenthesizedArrowFunctionExpression(): Expression { - var triState = isParenthesizedArrowFunctionExpression(); + let triState = isParenthesizedArrowFunctionExpression(); if (triState === Tristate.False) { // It's definitely not a parenthesized arrow function expression. @@ -3028,7 +3028,7 @@ module 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. - var arrowFunction = triState === Tristate.True + let arrowFunction = triState === Tristate.True ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity:*/ true) : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); @@ -3070,8 +3070,8 @@ module ts { } function isParenthesizedArrowFunctionExpressionWorker() { - var first = token; - var second = nextToken(); + let first = token; + let second = nextToken(); if (first === SyntaxKind.OpenParenToken) { if (second === SyntaxKind.CloseParenToken) { @@ -3079,7 +3079,7 @@ module 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. - var third = nextToken(); + let third = nextToken(); switch (third) { case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.ColonToken: @@ -3134,7 +3134,7 @@ module ts { } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): FunctionExpression { - var node = createNode(SyntaxKind.ArrowFunction); + let node = createNode(SyntaxKind.ArrowFunction); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -3177,7 +3177,7 @@ module ts { // user meant to supply a block. For example, if the user wrote: // // a => - // var v = 0; + // let v = 0; // } // // they may be missing an open brace. Check to see if that's the case so we can @@ -3193,14 +3193,14 @@ module ts { function parseConditionalExpressionRest(leftOperand: Expression): Expression { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + let 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. - var node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos); + let node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = allowInAnd(parseAssignmentExpressionOrHigher); @@ -3211,7 +3211,7 @@ module ts { } function parseBinaryExpressionOrHigher(precedence: number): Expression { - var leftOperand = parseUnaryExpressionOrHigher(); + let leftOperand = parseUnaryExpressionOrHigher(); return parseBinaryExpressionRest(precedence, leftOperand); } @@ -3225,7 +3225,7 @@ module ts { // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); + let newPrecedence = getBinaryOperatorPrecedence(); // Check the precedence to see if we should "take" this operator if (newPrecedence <= precedence) { @@ -3293,7 +3293,7 @@ module ts { } function makeBinaryExpression(left: Expression, operatorToken: Node, right: Expression): BinaryExpression { - var node = createNode(SyntaxKind.BinaryExpression, left.pos); + let node = createNode(SyntaxKind.BinaryExpression, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; @@ -3301,7 +3301,7 @@ module ts { } function parsePrefixUnaryExpression() { - var node = createNode(SyntaxKind.PrefixUnaryExpression); + let node = createNode(SyntaxKind.PrefixUnaryExpression); node.operator = token; nextToken(); node.operand = parseUnaryExpressionOrHigher(); @@ -3309,21 +3309,21 @@ module ts { } function parseDeleteExpression() { - var node = createNode(SyntaxKind.DeleteExpression); + let node = createNode(SyntaxKind.DeleteExpression); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(SyntaxKind.TypeOfExpression); + let node = createNode(SyntaxKind.TypeOfExpression); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(SyntaxKind.VoidExpression); + let node = createNode(SyntaxKind.VoidExpression); nextToken(); node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); @@ -3352,11 +3352,11 @@ module ts { } function parsePostfixExpressionOrHigher(): PostfixExpression { - var expression = parseLeftHandSideExpressionOrHigher(); + let expression = parseLeftHandSideExpressionOrHigher(); Debug.assert(isLeftHandSideExpression(expression)); if ((token === SyntaxKind.PlusPlusToken || token === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos); + let node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -3397,7 +3397,7 @@ module 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. - var expression = token === SyntaxKind.SuperKeyword + let expression = token === SyntaxKind.SuperKeyword ? parseSuperExpression() : parseMemberExpressionOrHigher(); @@ -3454,19 +3454,19 @@ module 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. - var expression = parsePrimaryExpression(); + let expression = parsePrimaryExpression(); return parseMemberExpressionRest(expression); } function parseSuperExpression(): MemberExpression { - var expression = parseTokenNode(); + let expression = parseTokenNode(); if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.DotToken) { 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. - var node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + let 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); @@ -3474,7 +3474,7 @@ module ts { } function parseTypeAssertion(): TypeAssertion { - var node = createNode(SyntaxKind.TypeAssertionExpression); + let node = createNode(SyntaxKind.TypeAssertionExpression); parseExpected(SyntaxKind.LessThanToken); node.type = parseType(); parseExpected(SyntaxKind.GreaterThanToken); @@ -3484,9 +3484,9 @@ module ts { function parseMemberExpressionRest(expression: LeftHandSideExpression): MemberExpression { while (true) { - var dotToken = parseOptionalToken(SyntaxKind.DotToken); + let dotToken = parseOptionalToken(SyntaxKind.DotToken); if (dotToken) { - var propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + let propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames:*/ true); @@ -3495,7 +3495,7 @@ module ts { } if (parseOptional(SyntaxKind.OpenBracketToken)) { - var indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); + let indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". @@ -3503,7 +3503,7 @@ module ts { if (token !== SyntaxKind.CloseBracketToken) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === SyntaxKind.StringLiteral || indexedAccess.argumentExpression.kind === SyntaxKind.NumericLiteral) { - var literal = indexedAccess.argumentExpression; + let literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } @@ -3514,7 +3514,7 @@ module ts { } if (token === SyntaxKind.NoSubstitutionTemplateLiteral || token === SyntaxKind.TemplateHead) { - var tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos); + let tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos); tagExpression.tag = expression; tagExpression.template = token === SyntaxKind.NoSubstitutionTemplateLiteral ? parseLiteralNode() @@ -3536,12 +3536,12 @@ module 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. - var typeArguments = tryParse(parseTypeArgumentsInExpression); + let typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - var callExpr = createNode(SyntaxKind.CallExpression, expression.pos); + let callExpr = createNode(SyntaxKind.CallExpression, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -3549,7 +3549,7 @@ module ts { continue; } else if (token === SyntaxKind.OpenParenToken) { - var callExpr = createNode(SyntaxKind.CallExpression, expression.pos); + let callExpr = createNode(SyntaxKind.CallExpression, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -3562,7 +3562,7 @@ module ts { function parseArgumentList() { parseExpected(SyntaxKind.OpenParenToken); - var result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); + let result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); parseExpected(SyntaxKind.CloseParenToken); return result; } @@ -3572,7 +3572,7 @@ module ts { return undefined; } - var typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); + let 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; @@ -3656,7 +3656,7 @@ module ts { } function parseParenthesizedExpression(): ParenthesizedExpression { - var node = createNode(SyntaxKind.ParenthesizedExpression); + let node = createNode(SyntaxKind.ParenthesizedExpression); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); @@ -3664,7 +3664,7 @@ module ts { } function parseSpreadElement(): Expression { - var node = createNode(SyntaxKind.SpreadElementExpression); + let node = createNode(SyntaxKind.SpreadElementExpression); parseExpected(SyntaxKind.DotDotDotToken); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -3681,7 +3681,7 @@ module ts { } function parseArrayLiteralExpression(): ArrayLiteralExpression { - var node = createNode(SyntaxKind.ArrayLiteralExpression); + let node = createNode(SyntaxKind.ArrayLiteralExpression); parseExpected(SyntaxKind.OpenBracketToken); if (scanner.hasPrecedingLineBreak()) node.flags |= NodeFlags.MultiLine; node.elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement); @@ -3701,34 +3701,34 @@ module ts { } function parseObjectLiteralElement(): ObjectLiteralElement { - var fullStart = scanner.getStartPos(); - var modifiers = parseModifiers(); + let fullStart = scanner.getStartPos(); + let modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + let accessor = tryParseAccessorDeclaration(fullStart, modifiers); if (accessor) { return accessor; } - var asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - var tokenIsIdentifier = isIdentifier(); - var nameToken = token; - var propertyName = parsePropertyName(); + let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); + let tokenIsIdentifier = isIdentifier(); + let nameToken = token; + let propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { return parseMethodDeclaration(fullStart, modifiers, asteriskToken, propertyName, questionToken); } // Parse to check if it is short-hand property assignment or normal property assignment if ((token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBraceToken) && tokenIsIdentifier) { - var shorthandDeclaration = createNode(SyntaxKind.ShorthandPropertyAssignment, fullStart); + let shorthandDeclaration = createNode(SyntaxKind.ShorthandPropertyAssignment, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; return finishNode(shorthandDeclaration); } else { - var propertyAssignment = createNode(SyntaxKind.PropertyAssignment, fullStart); + let propertyAssignment = createNode(SyntaxKind.PropertyAssignment, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(SyntaxKind.ColonToken); @@ -3738,7 +3738,7 @@ module ts { } function parseObjectLiteralExpression(): ObjectLiteralExpression { - var node = createNode(SyntaxKind.ObjectLiteralExpression); + let node = createNode(SyntaxKind.ObjectLiteralExpression); parseExpected(SyntaxKind.OpenBraceToken); if (scanner.hasPrecedingLineBreak()) { node.flags |= NodeFlags.MultiLine; @@ -3754,7 +3754,7 @@ module ts { // function * BindingIdentifier[Yield]opt (FormalParameters[Yield, GeneratorParameter]) { GeneratorBody[Yield] } // FunctionExpression: // function BindingIdentifieropt(FormalParameters) { FunctionBody } - var node = createNode(SyntaxKind.FunctionExpression); + let node = createNode(SyntaxKind.FunctionExpression); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); node.name = node.asteriskToken ? doInYieldContext(parseOptionalIdentifier) : parseOptionalIdentifier(); @@ -3768,7 +3768,7 @@ module ts { } function parseNewExpression(): NewExpression { - var node = createNode(SyntaxKind.NewExpression); + let node = createNode(SyntaxKind.NewExpression); parseExpected(SyntaxKind.NewKeyword); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -3781,7 +3781,7 @@ module ts { // STATEMENTS function parseBlock(ignoreMissingOpenBrace: boolean, checkForStrictMode: boolean, diagnosticMessage?: DiagnosticMessage): Block { - var node = createNode(SyntaxKind.Block); + let node = createNode(SyntaxKind.Block); if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(ParsingContext.BlockStatements, checkForStrictMode, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); @@ -3793,10 +3793,10 @@ module ts { } function parseFunctionBlock(allowYield: boolean, ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { - var savedYieldContext = inYieldContext(); + let savedYieldContext = inYieldContext(); setYieldContext(allowYield); - var block = parseBlock(ignoreMissingOpenBrace, /*checkForStrictMode*/ true, diagnosticMessage); + let block = parseBlock(ignoreMissingOpenBrace, /*checkForStrictMode*/ true, diagnosticMessage); setYieldContext(savedYieldContext); @@ -3804,13 +3804,13 @@ module ts { } function parseEmptyStatement(): Statement { - var node = createNode(SyntaxKind.EmptyStatement); + let node = createNode(SyntaxKind.EmptyStatement); parseExpected(SyntaxKind.SemicolonToken); return finishNode(node); } function parseIfStatement(): IfStatement { - var node = createNode(SyntaxKind.IfStatement); + let node = createNode(SyntaxKind.IfStatement); parseExpected(SyntaxKind.IfKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -3821,7 +3821,7 @@ module ts { } function parseDoStatement(): DoStatement { - var node = createNode(SyntaxKind.DoStatement); + let node = createNode(SyntaxKind.DoStatement); parseExpected(SyntaxKind.DoKeyword); node.statement = parseStatement(); parseExpected(SyntaxKind.WhileKeyword); @@ -3838,7 +3838,7 @@ module ts { } function parseWhileStatement(): WhileStatement { - var node = createNode(SyntaxKind.WhileStatement); + let node = createNode(SyntaxKind.WhileStatement); parseExpected(SyntaxKind.WhileKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -3848,11 +3848,11 @@ module ts { } function parseForOrForInOrForOfStatement(): Statement { - var pos = getNodePos(); + let pos = getNodePos(); parseExpected(SyntaxKind.ForKeyword); parseExpected(SyntaxKind.OpenParenToken); - var initializer: VariableDeclarationList | Expression = undefined; + let initializer: VariableDeclarationList | Expression = undefined; if (token !== SyntaxKind.SemicolonToken) { if (token === SyntaxKind.VarKeyword || token === SyntaxKind.LetKeyword || token === SyntaxKind.ConstKeyword) { initializer = parseVariableDeclarationList(/*inForStatementInitializer:*/ true); @@ -3861,22 +3861,22 @@ module ts { initializer = disallowInAnd(parseExpression); } } - var forOrForInOrForOfStatement: IterationStatement; + let forOrForInOrForOfStatement: IterationStatement; if (parseOptional(SyntaxKind.InKeyword)) { - var forInStatement = createNode(SyntaxKind.ForInStatement, pos); + let forInStatement = createNode(SyntaxKind.ForInStatement, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(SyntaxKind.OfKeyword)) { - var forOfStatement = createNode(SyntaxKind.ForOfStatement, pos); + let forOfStatement = createNode(SyntaxKind.ForOfStatement, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(SyntaxKind.CloseParenToken); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(SyntaxKind.ForStatement, pos); + let forStatement = createNode(SyntaxKind.ForStatement, pos); forStatement.initializer = initializer; parseExpected(SyntaxKind.SemicolonToken); if (token !== SyntaxKind.SemicolonToken && token !== SyntaxKind.CloseParenToken) { @@ -3896,7 +3896,7 @@ module ts { } function parseBreakOrContinueStatement(kind: SyntaxKind): BreakOrContinueStatement { - var node = createNode(kind); + let node = createNode(kind); parseExpected(kind === SyntaxKind.BreakStatement ? SyntaxKind.BreakKeyword : SyntaxKind.ContinueKeyword); if (!canParseSemicolon()) { @@ -3908,7 +3908,7 @@ module ts { } function parseReturnStatement(): ReturnStatement { - var node = createNode(SyntaxKind.ReturnStatement); + let node = createNode(SyntaxKind.ReturnStatement); parseExpected(SyntaxKind.ReturnKeyword); if (!canParseSemicolon()) { @@ -3920,7 +3920,7 @@ module ts { } function parseWithStatement(): WithStatement { - var node = createNode(SyntaxKind.WithStatement); + let node = createNode(SyntaxKind.WithStatement); parseExpected(SyntaxKind.WithKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -3930,7 +3930,7 @@ module ts { } function parseCaseClause(): CaseClause { - var node = createNode(SyntaxKind.CaseClause); + let node = createNode(SyntaxKind.CaseClause); parseExpected(SyntaxKind.CaseKeyword); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.ColonToken); @@ -3939,7 +3939,7 @@ module ts { } function parseDefaultClause(): DefaultClause { - var node = createNode(SyntaxKind.DefaultClause); + let node = createNode(SyntaxKind.DefaultClause); parseExpected(SyntaxKind.DefaultKeyword); parseExpected(SyntaxKind.ColonToken); node.statements = parseList(ParsingContext.SwitchClauseStatements, /*checkForStrictMode*/ false, parseStatement); @@ -3951,12 +3951,12 @@ module ts { } function parseSwitchStatement(): SwitchStatement { - var node = createNode(SyntaxKind.SwitchStatement); + let node = createNode(SyntaxKind.SwitchStatement); parseExpected(SyntaxKind.SwitchKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); - var caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); + let caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); parseExpected(SyntaxKind.OpenBraceToken); caseBlock.clauses = parseList(ParsingContext.SwitchClauses, /*checkForStrictMode*/ false, parseCaseOrDefaultClause); parseExpected(SyntaxKind.CloseBraceToken); @@ -3973,7 +3973,7 @@ module 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. - var node = createNode(SyntaxKind.ThrowStatement); + let node = createNode(SyntaxKind.ThrowStatement); parseExpected(SyntaxKind.ThrowKeyword); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -3982,7 +3982,7 @@ module ts { // TODO: Review for error recovery function parseTryStatement(): TryStatement { - var node = createNode(SyntaxKind.TryStatement); + let node = createNode(SyntaxKind.TryStatement); parseExpected(SyntaxKind.TryKeyword); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode*/ false); @@ -3999,7 +3999,7 @@ module ts { } function parseCatchClause(): CatchClause { - var result = createNode(SyntaxKind.CatchClause); + let result = createNode(SyntaxKind.CatchClause); parseExpected(SyntaxKind.CatchKeyword); if (parseExpected(SyntaxKind.OpenParenToken)) { result.variableDeclaration = parseVariableDeclaration(); @@ -4011,7 +4011,7 @@ module ts { } function parseDebuggerStatement(): Statement { - var node = createNode(SyntaxKind.DebuggerStatement); + let node = createNode(SyntaxKind.DebuggerStatement); parseExpected(SyntaxKind.DebuggerKeyword); parseSemicolon(); return finishNode(node); @@ -4021,17 +4021,17 @@ module 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. - var fullStart = scanner.getStartPos(); - var expression = allowInAnd(parseExpression); + let fullStart = scanner.getStartPos(); + let expression = allowInAnd(parseExpression); if (expression.kind === SyntaxKind.Identifier && parseOptional(SyntaxKind.ColonToken)) { - var labeledStatement = createNode(SyntaxKind.LabeledStatement, fullStart); + let labeledStatement = createNode(SyntaxKind.LabeledStatement, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(SyntaxKind.ExpressionStatement, fullStart); + let expressionStatement = createNode(SyntaxKind.ExpressionStatement, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -4045,7 +4045,7 @@ module ts { // as the parser will produce the same FunctionDeclaraiton or VariableStatement if it has // the same text regardless of whether it is inside a block or not. if (isModifier(token)) { - var result = lookAhead(parseVariableStatementOrFunctionDeclarationWithModifiers); + let result = lookAhead(parseVariableStatementOrFunctionDeclarationWithModifiers); if (result) { return true; } @@ -4085,7 +4085,7 @@ module ts { // const keyword can precede enum keyword when defining constant enums // 'const enum' do not start statement. // In ES 6 'enum' is a future reserved keyword, so it should not be used as identifier - var isConstEnum = lookAhead(nextTokenIsEnumKeyword); + let isConstEnum = lookAhead(nextTokenIsEnumKeyword); return !isConstEnum; case SyntaxKind.InterfaceKeyword: case SyntaxKind.ClassKeyword: @@ -4175,7 +4175,7 @@ module ts { // same FunctionDeclaraiton or VariableStatement if it has the same text // regardless of whether it is inside a block or not. if (isModifier(token)) { - var result = tryParse(parseVariableStatementOrFunctionDeclarationWithModifiers); + let result = tryParse(parseVariableStatementOrFunctionDeclarationWithModifiers); if (result) { return result; } @@ -4186,11 +4186,11 @@ module ts { } function parseVariableStatementOrFunctionDeclarationWithModifiers(): FunctionDeclaration | VariableStatement { - var start = scanner.getStartPos(); - var modifiers = parseModifiers(); + let start = scanner.getStartPos(); + let modifiers = parseModifiers(); switch (token) { case SyntaxKind.ConstKeyword: - var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword) + let nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword) if (nextTokenIsEnum) { return undefined; } @@ -4226,7 +4226,7 @@ module ts { if (token === SyntaxKind.CommaToken) { return createNode(SyntaxKind.OmittedExpression); } - var node = createNode(SyntaxKind.BindingElement); + let node = createNode(SyntaxKind.BindingElement); node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(/*inParameter*/ false); @@ -4234,9 +4234,9 @@ module ts { } function parseObjectBindingElement(): BindingElement { - var node = createNode(SyntaxKind.BindingElement); + let node = createNode(SyntaxKind.BindingElement); // TODO(andersh): Handle computed properties - var id = parsePropertyName(); + let id = parsePropertyName(); if (id.kind === SyntaxKind.Identifier && token !== SyntaxKind.ColonToken) { node.name = id; } @@ -4250,7 +4250,7 @@ module ts { } function parseObjectBindingPattern(): BindingPattern { - var node = createNode(SyntaxKind.ObjectBindingPattern); + let node = createNode(SyntaxKind.ObjectBindingPattern); parseExpected(SyntaxKind.OpenBraceToken); node.elements = parseDelimitedList(ParsingContext.ObjectBindingElements, parseObjectBindingElement); parseExpected(SyntaxKind.CloseBraceToken); @@ -4258,7 +4258,7 @@ module ts { } function parseArrayBindingPattern(): BindingPattern { - var node = createNode(SyntaxKind.ArrayBindingPattern); + let node = createNode(SyntaxKind.ArrayBindingPattern); parseExpected(SyntaxKind.OpenBracketToken); node.elements = parseDelimitedList(ParsingContext.ArrayBindingElements, parseArrayBindingElement); parseExpected(SyntaxKind.CloseBracketToken); @@ -4280,7 +4280,7 @@ module ts { } function parseVariableDeclaration(): VariableDeclaration { - var node = createNode(SyntaxKind.VariableDeclaration); + let node = createNode(SyntaxKind.VariableDeclaration); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -4290,7 +4290,7 @@ module ts { } function parseVariableDeclarationList(inForStatementInitializer: boolean): VariableDeclarationList { - var node = createNode(SyntaxKind.VariableDeclarationList); + let node = createNode(SyntaxKind.VariableDeclarationList); switch (token) { case SyntaxKind.VarKeyword: @@ -4309,7 +4309,7 @@ module ts { // The user may have written the following: // - // for (var of X) { } + // for (let of X) { } // // In this case, we want to parse an empty declaration list, and then parse 'of' // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. @@ -4320,7 +4320,7 @@ module ts { node.declarations = createMissingList(); } else { - var savedDisallowIn = inDisallowInContext(); + let savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); node.declarations = parseDelimitedList(ParsingContext.VariableDeclarations, parseVariableDeclaration); @@ -4336,7 +4336,7 @@ module ts { } function parseVariableStatement(fullStart: number, modifiers: ModifiersArray): VariableStatement { - var node = createNode(SyntaxKind.VariableStatement, fullStart); + let node = createNode(SyntaxKind.VariableStatement, fullStart); setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer:*/ false); parseSemicolon(); @@ -4344,7 +4344,7 @@ module ts { } function parseFunctionDeclaration(fullStart: number, modifiers: ModifiersArray): FunctionDeclaration { - var node = createNode(SyntaxKind.FunctionDeclaration, fullStart); + let node = createNode(SyntaxKind.FunctionDeclaration, fullStart); setModifiers(node, modifiers); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); @@ -4355,7 +4355,7 @@ module ts { } function parseConstructorDeclaration(pos: number, modifiers: ModifiersArray): ConstructorDeclaration { - var node = createNode(SyntaxKind.Constructor, pos); + let node = createNode(SyntaxKind.Constructor, pos); setModifiers(node, modifiers); parseExpected(SyntaxKind.ConstructorKeyword); fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); @@ -4364,7 +4364,7 @@ module ts { } function parseMethodDeclaration(fullStart: number, modifiers: ModifiersArray, asteriskToken: Node, name: DeclarationName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration { - var method = createNode(SyntaxKind.MethodDeclaration, fullStart); + let method = createNode(SyntaxKind.MethodDeclaration, fullStart); setModifiers(method, modifiers); method.asteriskToken = asteriskToken; method.name = name; @@ -4375,17 +4375,17 @@ module ts { } function parsePropertyOrMethodDeclaration(fullStart: number, modifiers: ModifiersArray): ClassElement { - var asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - var name = parsePropertyName(); + let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); + let 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. - var questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, Diagnostics.or_expected); } else { - var property = createNode(SyntaxKind.PropertyDeclaration, fullStart); + let property = createNode(SyntaxKind.PropertyDeclaration, fullStart); setModifiers(property, modifiers); property.name = name; property.questionToken = questionToken; @@ -4401,7 +4401,7 @@ module ts { } function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, modifiers: ModifiersArray): AccessorDeclaration { - var node = createNode(kind, fullStart); + let node = createNode(kind, fullStart); setModifiers(node, modifiers); node.name = parsePropertyName(); fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); @@ -4410,7 +4410,7 @@ module ts { } function isClassMemberStart(): boolean { - var idToken: SyntaxKind; + let idToken: SyntaxKind; // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. while (isModifier(token)) { @@ -4464,11 +4464,11 @@ module ts { } function parseModifiers(): ModifiersArray { - var flags = 0; - var modifiers: ModifiersArray; + let flags = 0; + let modifiers: ModifiersArray; while (true) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token; + let modifierStart = scanner.getStartPos(); + let modifierKind = token; if (!parseAnyContextualModifier()) { break; @@ -4489,10 +4489,10 @@ module ts { } function parseClassElement(): ClassElement { - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + let fullStart = getNodePos(); + let modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + let accessor = tryParseAccessorDeclaration(fullStart, modifiers); if (accessor) { return accessor; } @@ -4521,7 +4521,7 @@ module ts { } function parseClassDeclaration(fullStart: number, modifiers: ModifiersArray): ClassDeclaration { - var node = createNode(SyntaxKind.ClassDeclaration, fullStart); + let node = createNode(SyntaxKind.ClassDeclaration, fullStart); setModifiers(node, modifiers); parseExpected(SyntaxKind.ClassKeyword); node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier(); @@ -4564,7 +4564,7 @@ module ts { function parseHeritageClause() { if (token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword) { - var node = createNode(SyntaxKind.HeritageClause); + let node = createNode(SyntaxKind.HeritageClause); node.token = token; nextToken(); node.types = parseDelimitedList(ParsingContext.TypeReferences, parseTypeReference); @@ -4583,7 +4583,7 @@ module ts { } function parseInterfaceDeclaration(fullStart: number, modifiers: ModifiersArray): InterfaceDeclaration { - var node = createNode(SyntaxKind.InterfaceDeclaration, fullStart); + let node = createNode(SyntaxKind.InterfaceDeclaration, fullStart); setModifiers(node, modifiers); parseExpected(SyntaxKind.InterfaceKeyword); node.name = parseIdentifier(); @@ -4594,7 +4594,7 @@ module ts { } function parseTypeAliasDeclaration(fullStart: number, modifiers: ModifiersArray): TypeAliasDeclaration { - var node = createNode(SyntaxKind.TypeAliasDeclaration, fullStart); + let node = createNode(SyntaxKind.TypeAliasDeclaration, fullStart); setModifiers(node, modifiers); parseExpected(SyntaxKind.TypeKeyword); node.name = parseIdentifier(); @@ -4609,14 +4609,14 @@ module ts { // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember(): EnumMember { - var node = createNode(SyntaxKind.EnumMember, scanner.getStartPos()); + let node = createNode(SyntaxKind.EnumMember, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart: number, modifiers: ModifiersArray): EnumDeclaration { - var node = createNode(SyntaxKind.EnumDeclaration, fullStart); + let node = createNode(SyntaxKind.EnumDeclaration, fullStart); setModifiers(node, modifiers); parseExpected(SyntaxKind.EnumKeyword); node.name = parseIdentifier(); @@ -4631,7 +4631,7 @@ module ts { } function parseModuleBlock(): ModuleBlock { - var node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); + let node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); if (parseExpected(SyntaxKind.OpenBraceToken)) { node.statements = parseList(ParsingContext.ModuleElements, /*checkForStrictMode*/false, parseModuleElement); parseExpected(SyntaxKind.CloseBraceToken); @@ -4643,7 +4643,7 @@ module ts { } function parseInternalModuleTail(fullStart: number, modifiers: ModifiersArray, flags: NodeFlags): ModuleDeclaration { - var node = createNode(SyntaxKind.ModuleDeclaration, fullStart); + let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); @@ -4654,7 +4654,7 @@ module ts { } function parseAmbientExternalModuleDeclaration(fullStart: number, modifiers: ModifiersArray): ModuleDeclaration { - var node = createNode(SyntaxKind.ModuleDeclaration, fullStart); + let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); setModifiers(node, modifiers); node.name = parseLiteralNode(/*internName:*/ true); node.body = parseModuleBlock(); @@ -4685,16 +4685,16 @@ module ts { function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, modifiers: ModifiersArray): ImportEqualsDeclaration | ImportDeclaration { parseExpected(SyntaxKind.ImportKeyword); - var afterImportPos = scanner.getStartPos(); + let afterImportPos = scanner.getStartPos(); - var identifier: Identifier; + let identifier: Identifier; if (isIdentifier()) { identifier = parseIdentifier(); if (token !== SyntaxKind.CommaToken && token !== SyntaxKind.FromKeyword) { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart); + let importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart); setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; parseExpected(SyntaxKind.EqualsToken); @@ -4705,7 +4705,7 @@ module ts { } // Import statement - var importDeclaration = createNode(SyntaxKind.ImportDeclaration, fullStart); + let importDeclaration = createNode(SyntaxKind.ImportDeclaration, fullStart); setModifiers(importDeclaration, modifiers); // ImportDeclaration: @@ -4731,7 +4731,7 @@ module ts { // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(SyntaxKind.ImportClause, fullStart); + let importClause = createNode(SyntaxKind.ImportClause, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -4755,7 +4755,7 @@ module ts { } function parseExternalModuleReference() { - var node = createNode(SyntaxKind.ExternalModuleReference); + let node = createNode(SyntaxKind.ExternalModuleReference); parseExpected(SyntaxKind.RequireKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = parseModuleSpecifier(); @@ -4767,7 +4767,7 @@ module 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. - var result = parseExpression(); + let 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) { @@ -4779,7 +4779,7 @@ module ts { function parseNamespaceImport(): NamespaceImport { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(SyntaxKind.NamespaceImport); + let namespaceImport = createNode(SyntaxKind.NamespaceImport); parseExpected(SyntaxKind.AsteriskToken); parseExpected(SyntaxKind.AsKeyword); namespaceImport.name = parseIdentifier(); @@ -4787,7 +4787,7 @@ module ts { } function parseNamedImportsOrExports(kind: SyntaxKind): NamedImportsOrExports { - var node = createNode(kind); + let node = createNode(kind); // NamedImports: // { } @@ -4812,13 +4812,13 @@ module ts { } function parseImportOrExportSpecifier(kind: SyntaxKind): ImportOrExportSpecifier { - var node = createNode(kind); + let node = createNode(kind); // ImportSpecifier: // ImportedBinding // IdentifierName as ImportedBinding - var isFirstIdentifierNameNotAnIdentifier = isKeyword(token) && !isIdentifier(); - var start = scanner.getTokenPos(); - var identifierName = parseIdentifierName(); + let isFirstIdentifierNameNotAnIdentifier = isKeyword(token) && !isIdentifier(); + let start = scanner.getTokenPos(); + let identifierName = parseIdentifierName(); if (token === SyntaxKind.AsKeyword) { node.propertyName = identifierName; parseExpected(SyntaxKind.AsKeyword); @@ -4841,7 +4841,7 @@ module ts { } function parseExportDeclaration(fullStart: number, modifiers: ModifiersArray): ExportDeclaration { - var node = createNode(SyntaxKind.ExportDeclaration, fullStart); + let node = createNode(SyntaxKind.ExportDeclaration, fullStart); setModifiers(node, modifiers); if (parseOptional(SyntaxKind.AsteriskToken)) { parseExpected(SyntaxKind.FromKeyword); @@ -4858,7 +4858,7 @@ module ts { } function parseExportAssignment(fullStart: number, modifiers: ModifiersArray): ExportAssignment { - var node = createNode(SyntaxKind.ExportAssignment, fullStart); + let node = createNode(SyntaxKind.ExportAssignment, fullStart); setModifiers(node, modifiers); if (parseOptional(SyntaxKind.EqualsToken)) { node.isExportEquals = true; @@ -4947,8 +4947,8 @@ module ts { } function parseDeclaration(): ModuleElement { - var fullStart = getNodePos(); - var modifiers = parseModifiers(); + let fullStart = getNodePos(); + let modifiers = parseModifiers(); if (token === SyntaxKind.ExportKeyword) { nextToken(); if (token === SyntaxKind.DefaultKeyword || token === SyntaxKind.EqualsToken) { @@ -5002,16 +5002,16 @@ module ts { } function processReferenceComments(sourceFile: SourceFile): void { - var triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, sourceText); - var referencedFiles: FileReference[] = []; - var amdDependencies: {path: string; name: string}[] = []; - var amdModuleName: string; + let triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, sourceText); + let referencedFiles: FileReference[] = []; + let 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) { - var kind = triviaScanner.scan(); + let kind = triviaScanner.scan(); if (kind === SyntaxKind.WhitespaceTrivia || kind === SyntaxKind.NewLineTrivia || kind === SyntaxKind.MultiLineCommentTrivia) { continue; } @@ -5019,14 +5019,14 @@ module ts { break; } - var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos() }; + let range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos() }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = getFileReferenceFromReferencePath(comment, range); + let comment = sourceText.substring(range.pos, range.end); + let referencePathMatchResult = getFileReferenceFromReferencePath(comment, range); if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; + let fileReference = referencePathMatchResult.fileReference; sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + let diagnosticMessage = referencePathMatchResult.diagnosticMessage; if (fileReference) { referencedFiles.push(fileReference); } @@ -5035,8 +5035,8 @@ module ts { } } else { - var amdModuleNameRegEx = /^\/\/\/\s* Date: Fri, 13 Mar 2015 11:10:12 -0700 Subject: [PATCH 15/19] Use 'let' in the binder. --- src/compiler/binder.ts | 55 +++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index e325b2033e7..d0d6005d979 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1,7 +1,7 @@ /// module ts { - /* @internal */ export var bindTime = 0; + /* @internal */ export let bindTime = 0; export const enum ModuleInstanceState { NonInstantiated = 0, @@ -25,7 +25,7 @@ module ts { } // 4. other uninstantiated module declarations. else if (node.kind === SyntaxKind.ModuleBlock) { - var state = ModuleInstanceState.NonInstantiated; + let state = ModuleInstanceState.NonInstantiated; forEachChild(node, n => { switch (getModuleInstanceState(n)) { case ModuleInstanceState.NonInstantiated: @@ -52,18 +52,18 @@ module ts { } export function bindSourceFile(file: SourceFile): void { - var start = new Date().getTime(); + let start = new Date().getTime(); bindSourceFileWorker(file); bindTime += new Date().getTime() - start; } function bindSourceFileWorker(file: SourceFile): void { var parent: Node; - var container: Node; - var blockScopeContainer: Node; - var lastContainer: Node; - var symbolCount = 0; - var Symbol = objectAllocator.getSymbolConstructor(); + let container: Node; + let blockScopeContainer: Node; + let lastContainer: Node; + let symbolCount = 0; + let Symbol = objectAllocator.getSymbolConstructor(); if (!file.locals) { file.locals = {}; @@ -103,7 +103,7 @@ module ts { return '"' + (node.name).text + '"'; } if (node.name.kind === SyntaxKind.ComputedPropertyName) { - var nameExpression = (node.name).expression; + let nameExpression = (node.name).expression; Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); return getPropertyNameForKnownSymbolName((nameExpression).name.text); } @@ -138,10 +138,11 @@ module ts { Debug.assert(!hasDynamicName(node)); // The exported symbol for an export default function/class node is always named "default" - var name = node.flags & NodeFlags.Default && parent ? "default" : getDeclarationName(node); + let name = node.flags & NodeFlags.Default && parent ? "default" : getDeclarationName(node); + let symbol: Symbol; if (name !== undefined) { - var symbol = hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); + symbol = hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); if (symbol.flags & excludes) { if (node.name) { node.name.parent = node; @@ -149,7 +150,7 @@ module ts { // Report errors every position with duplicate declaration // Report errors on previous encountered declarations - var message = symbol.flags & SymbolFlags.BlockScopedVariable + let message = symbol.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; @@ -172,7 +173,7 @@ module 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'. - var prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); + let prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); if (hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; @@ -196,7 +197,7 @@ module ts { } function declareModuleMember(node: Declaration, symbolKind: SymbolFlags, symbolExcludes: SymbolFlags) { - var hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; + let hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; if (symbolKind & SymbolFlags.Alias) { if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) { declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); @@ -218,10 +219,10 @@ module 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 || isAmbientContext(container)) { - var exportKind = (symbolKind & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | + let exportKind = (symbolKind & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | (symbolKind & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | (symbolKind & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0); - var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + let local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); node.localSymbol = local; } @@ -238,9 +239,9 @@ module ts { node.locals = {}; } - var saveParent = parent; - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; + let saveParent = parent; + let saveContainer = container; + let savedBlockScopeContainer = blockScopeContainer; parent = node; if (symbolKind & SymbolFlags.IsContainer) { container = node; @@ -315,7 +316,7 @@ module ts { bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes, /*isBlockScopeContainer*/ true); } else { - var state = getModuleInstanceState(node); + let state = getModuleInstanceState(node); if (state === ModuleInstanceState.NonInstantiated) { bindDeclaration(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes, /*isBlockScopeContainer*/ true); } @@ -341,18 +342,18 @@ module ts { // 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. - var symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); + let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); bindChildren(node, SymbolFlags.Signature, /*isBlockScopeContainer:*/ false); - var typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); + let typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral); typeLiteralSymbol.members = {}; typeLiteralSymbol.members[node.kind === SyntaxKind.FunctionType ? "__call" : "__new"] = symbol } function bindAnonymousDeclaration(node: Declaration, symbolKind: SymbolFlags, name: string, isBlockScopeContainer: boolean) { - var symbol = createSymbol(symbolKind, name); + let symbol = createSymbol(symbolKind, name); addDeclarationToSymbol(symbol, node, symbolKind); bindChildren(node, symbolKind, isBlockScopeContainer); } @@ -525,9 +526,9 @@ module ts { // Otherwise this won't be considered as redeclaration of a block scoped local: // function foo() { // let x; - // var x; + // let x; // } - // 'var x' will be placed into the function locals and 'let x' - into the locals of the block + // 'let x' will be placed into the function locals and 'let x' - into the locals of the block bindChildren(node, 0, /*isBlockScopeContainer*/ !isFunctionLike(node.parent)); break; case SyntaxKind.CatchClause: @@ -538,7 +539,7 @@ module ts { bindChildren(node, 0, /*isBlockScopeContainer*/ true); break; default: - var saveParent = parent; + let saveParent = parent; parent = node; forEachChild(node, bind); parent = saveParent; @@ -559,7 +560,7 @@ module ts { node.parent.kind === SyntaxKind.Constructor && node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - var classDeclaration = node.parent.parent; + let classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); } } From 01d2280dfc479f04c27805764f3938c7f608b1b4 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 12:26:10 -0700 Subject: [PATCH 16/19] Use 'let' in the checker. --- src/compiler/checker.ts | 2252 ++++++++++++++++++++------------------- 1 file changed, 1127 insertions(+), 1125 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5c571d8e0e3..7015c7deb21 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1,28 +1,28 @@ /// module ts { - var nextSymbolId = 1; - var nextNodeId = 1; - var nextMergeId = 1; + let nextSymbolId = 1; + let nextNodeId = 1; + let nextMergeId = 1; - /* @internal */ export var checkTime = 0; + /* @internal */ export let checkTime = 0; export function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker { - var Symbol = objectAllocator.getSymbolConstructor(); - var Type = objectAllocator.getTypeConstructor(); - var Signature = objectAllocator.getSignatureConstructor(); + let Symbol = objectAllocator.getSymbolConstructor(); + let Type = objectAllocator.getTypeConstructor(); + let Signature = objectAllocator.getSignatureConstructor(); - var typeCount = 0; + let typeCount = 0; - var emptyArray: any[] = []; - var emptySymbols: SymbolTable = {}; + let emptyArray: any[] = []; + let emptySymbols: SymbolTable = {}; - var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || ScriptTarget.ES3; + let compilerOptions = host.getCompilerOptions(); + let languageVersion = compilerOptions.target || ScriptTarget.ES3; - var emitResolver = createResolver(); + let emitResolver = createResolver(); - var checker: TypeChecker = { + let checker: TypeChecker = { getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"), getIdentifierCount: () => sum(host.getSourceFiles(), "identifierCount"), getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount"), @@ -61,59 +61,59 @@ module ts { var undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); var argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments"); - var unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); - var resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); + let unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); + let resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); - var anyType = createIntrinsicType(TypeFlags.Any, "any"); - var stringType = createIntrinsicType(TypeFlags.String, "string"); - var numberType = createIntrinsicType(TypeFlags.Number, "number"); - var booleanType = createIntrinsicType(TypeFlags.Boolean, "boolean"); - var esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); - var voidType = createIntrinsicType(TypeFlags.Void, "void"); - var undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); - var nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); - var unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); - var resolvingType = createIntrinsicType(TypeFlags.Any, "__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 resolvingType = createIntrinsicType(TypeFlags.Any, "__resolving__"); - var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var inferenceFailureType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + let emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + let inferenceFailureType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); + let anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); + let unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); - var globals: SymbolTable = {}; + let globals: SymbolTable = {}; - var globalArraySymbol: Symbol; - var globalESSymbolConstructorSymbol: Symbol; + let globalArraySymbol: Symbol; + let globalESSymbolConstructorSymbol: Symbol; - var globalObjectType: ObjectType; - var globalFunctionType: ObjectType; - var globalArrayType: ObjectType; - var globalStringType: ObjectType; - var globalNumberType: ObjectType; - var globalBooleanType: ObjectType; - var globalRegExpType: ObjectType; - var globalTemplateStringsArrayType: ObjectType; - var globalESSymbolType: ObjectType; - var globalIterableType: ObjectType; + let globalObjectType: ObjectType; + let globalFunctionType: ObjectType; + let globalArrayType: ObjectType; + let globalStringType: ObjectType; + let globalNumberType: ObjectType; + let globalBooleanType: ObjectType; + let globalRegExpType: ObjectType; + let globalTemplateStringsArrayType: ObjectType; + let globalESSymbolType: ObjectType; + let globalIterableType: ObjectType; - var anyArrayType: Type; + let anyArrayType: Type; - var tupleTypes: Map = {}; - var unionTypes: Map = {}; - var stringLiteralTypes: Map = {}; - var emitExtends = false; + let tupleTypes: Map = {}; + let unionTypes: Map = {}; + let stringLiteralTypes: Map = {}; + let emitExtends = false; - var mergedSymbols: Symbol[] = []; - var symbolLinks: SymbolLinks[] = []; - var nodeLinks: NodeLinks[] = []; - var potentialThisCollisions: Node[] = []; + let mergedSymbols: Symbol[] = []; + let symbolLinks: SymbolLinks[] = []; + let nodeLinks: NodeLinks[] = []; + let potentialThisCollisions: Node[] = []; - var diagnostics = createDiagnosticCollection(); + let diagnostics = createDiagnosticCollection(); - var primitiveTypeInfo: Map<{ type: Type; flags: TypeFlags }> = { + let primitiveTypeInfo: Map<{ type: Type; flags: TypeFlags }> = { "string": { type: stringType, flags: TypeFlags.StringLike @@ -140,7 +140,7 @@ module ts { } function error(location: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void { - var diagnostic = location + let diagnostic = location ? createDiagnosticForNode(location, message, arg0, arg1, arg2) : createCompilerDiagnostic(message, arg0, arg1, arg2); diagnostics.add(diagnostic); @@ -151,7 +151,7 @@ module ts { } function getExcludedSymbolFlags(flags: SymbolFlags): SymbolFlags { - var result: SymbolFlags = 0; + let result: SymbolFlags = 0; if (flags & SymbolFlags.BlockScopedVariable) result |= SymbolFlags.BlockScopedVariableExcludes; if (flags & SymbolFlags.FunctionScopedVariable) result |= SymbolFlags.FunctionScopedVariableExcludes; if (flags & SymbolFlags.Property) result |= SymbolFlags.PropertyExcludes; @@ -177,7 +177,7 @@ module ts { } function cloneSymbol(symbol: Symbol): Symbol { - var result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name); + let 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; @@ -210,7 +210,7 @@ module ts { recordMergedSymbol(target, source); } else { - var message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable + let 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)); @@ -222,8 +222,8 @@ module ts { } function cloneSymbolTable(symbolTable: SymbolTable): SymbolTable { - var result: SymbolTable = {}; - for (var id in symbolTable) { + let result: SymbolTable = {}; + for (let id in symbolTable) { if (hasProperty(symbolTable, id)) { result[id] = symbolTable[id]; } @@ -232,13 +232,13 @@ module ts { } function mergeSymbolTable(target: SymbolTable, source: SymbolTable) { - for (var id in source) { + for (let id in source) { if (hasProperty(source, id)) { if (!hasProperty(target, id)) { target[id] = source[id]; } else { - var symbol = target[id]; + let symbol = target[id]; if (!(symbol.flags & SymbolFlags.Merged)) { target[id] = symbol = cloneSymbol(symbol); } @@ -269,14 +269,14 @@ module ts { function getSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags): Symbol { if (meaning && hasProperty(symbols, name)) { - var symbol = symbols[name]; + let 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) { - var target = resolveAlias(symbol); + let 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; @@ -289,8 +289,8 @@ module ts { /** Returns true if node1 is defined before node 2**/ function isDefinedBefore(node1: Node, node2: Node): boolean { - var file1 = getSourceFileOfNode(node1); - var file2 = getSourceFileOfNode(node2); + let file1 = getSourceFileOfNode(node1); + let file2 = getSourceFileOfNode(node2); if (file1 === file2) { return node1.pos <= node2.pos; } @@ -299,7 +299,7 @@ module ts { return true; } - var sourceFiles = host.getSourceFiles(); + let sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(file1) <= sourceFiles.indexOf(file2); } @@ -307,10 +307,10 @@ module ts { // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with // the given name can be found. function resolveName(location: Node, name: string, meaning: SymbolFlags, nameNotFoundMessage: DiagnosticMessage, nameArg: string | Identifier): Symbol { - var result: Symbol; - var lastLocation: Node; - var propertyWithInvalidInitializer: Node; - var errorLocation = location; + let result: Symbol; + let lastLocation: Node; + let propertyWithInvalidInitializer: Node; + let errorLocation = location; loop: while (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) @@ -344,7 +344,7 @@ module ts { // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. if (location.parent.kind === SyntaxKind.ClassDeclaration && !(location.flags & NodeFlags.Static)) { - var ctor = findConstructorDeclaration(location.parent); + let 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 @@ -376,7 +376,7 @@ module ts { // } // case SyntaxKind.ComputedPropertyName: - var grandparent = location.parent.parent; + let grandparent = location.parent.parent; if (grandparent.kind === SyntaxKind.ClassDeclaration || grandparent.kind === SyntaxKind.InterfaceDeclaration) { // A reference to this grandparent's type parameters would be an error if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & SymbolFlags.Type)) { @@ -402,7 +402,7 @@ module ts { result = argumentsSymbol; break loop; } - var id = (location).name; + let id = (location).name; if (id && name === id.text) { result = location.symbol; break loop; @@ -429,7 +429,7 @@ module 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. - var propertyName = (propertyWithInvalidInitializer).name; + let 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; @@ -444,12 +444,12 @@ module ts { function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0) // Block-scoped variables cannot be used before their definition - var declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); + let declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); // first check if usage is lexically located after the declaration - var isUsedBeforeDeclaration = !isDefinedBefore(declaration, errorLocation); + let isUsedBeforeDeclaration = !isDefinedBefore(declaration, errorLocation); if (!isUsedBeforeDeclaration) { // lexical check succeeded however code still can be illegal. // - block scoped variables cannot be used in its initializers @@ -459,8 +459,8 @@ module ts { // for (let x of x) // climb up to the variable declaration skipping binding patterns - var variableDeclaration = getAncestor(declaration, SyntaxKind.VariableDeclaration); - var container = getEnclosingBlockScopeContainer(variableDeclaration); + let variableDeclaration = getAncestor(declaration, SyntaxKind.VariableDeclaration); + let container = getEnclosingBlockScopeContainer(variableDeclaration); if (variableDeclaration.parent.parent.kind === SyntaxKind.VariableStatement || variableDeclaration.parent.parent.kind === SyntaxKind.ForStatement) { @@ -471,7 +471,7 @@ module ts { else if (variableDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement || variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement) { // ForIn/ForOf case - use site should not be used in expression part - var expression = (variableDeclaration.parent.parent).expression; + let expression = (variableDeclaration.parent.parent).expression; isUsedBeforeDeclaration = isSameScopeDescendentOf(errorLocation, expression, container); } } @@ -488,7 +488,7 @@ module ts { if (!parent) { return false; } - for (var current = initial; current && current !== stopAt && !isFunctionLike(current); current = current.parent) { + for (let current = initial; current && current !== stopAt && !isFunctionLike(current); current = current.parent) { if (current === parent) { return true; } @@ -518,17 +518,17 @@ module ts { function getTargetOfImportEqualsDeclaration(node: ImportEqualsDeclaration): Symbol { if (node.moduleReference.kind === SyntaxKind.ExternalModuleReference) { - var moduleSymbol = resolveExternalModuleName(node, getExternalModuleImportEqualsDeclarationExpression(node)); - var exportAssignmentSymbol = moduleSymbol && getResolvedExportAssignmentSymbol(moduleSymbol); + let moduleSymbol = resolveExternalModuleName(node, getExternalModuleImportEqualsDeclarationExpression(node)); + let exportAssignmentSymbol = moduleSymbol && getResolvedExportAssignmentSymbol(moduleSymbol); return exportAssignmentSymbol || moduleSymbol; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); } function getTargetOfImportClause(node: ImportClause): Symbol { - var moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); + let moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); if (moduleSymbol) { - var exportAssignmentSymbol = getResolvedExportAssignmentSymbol(moduleSymbol); + let exportAssignmentSymbol = getResolvedExportAssignmentSymbol(moduleSymbol); if (!exportAssignmentSymbol) { error(node.name, Diagnostics.External_module_0_has_no_default_export_or_export_assignment, symbolToString(moduleSymbol)); } @@ -541,11 +541,11 @@ module ts { } function getExternalModuleMember(node: ImportDeclaration | ExportDeclaration, specifier: ImportOrExportSpecifier): Symbol { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + let moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); if (moduleSymbol) { - var name = specifier.propertyName || specifier.name; + let name = specifier.propertyName || specifier.name; if (name.text) { - var symbol = getSymbol(getExportsOfSymbol(moduleSymbol), name.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace); + let symbol = getSymbol(getExportsOfSymbol(moduleSymbol), name.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace); if (!symbol) { error(name, Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), declarationNameToString(name)); return; @@ -588,11 +588,11 @@ module ts { function resolveAlias(symbol: Symbol): Symbol { Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.target) { links.target = resolvingSymbol; - var node = getDeclarationOfAliasSymbol(symbol); - var target = getTargetOfImportDeclaration(node); + let node = getDeclarationOfAliasSymbol(symbol); + let target = getTargetOfImportDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; } @@ -607,8 +607,8 @@ module ts { } function markExportAsReferenced(node: ImportEqualsDeclaration | ExportAssignment | ExportSpecifier) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); + let symbol = getSymbolOfNode(node); + let target = resolveAlias(symbol); if (target && target !== unknownSymbol && target.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(target)) { markAliasSymbolAsReferenced(symbol); } @@ -618,10 +618,10 @@ module 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) { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.referenced) { links.referenced = true; - var node = getDeclarationOfAliasSymbol(symbol); + let node = getDeclarationOfAliasSymbol(symbol); if (node.kind === SyntaxKind.ExportAssignment) { // export default checkExpressionCached((node).expression); @@ -680,11 +680,11 @@ module ts { } } else if (name.kind === SyntaxKind.QualifiedName) { - var namespace = resolveEntityName((name).left, SymbolFlags.Namespace); + let namespace = resolveEntityName((name).left, SymbolFlags.Namespace); if (!namespace || namespace === unknownSymbol || getFullWidth((name).right) === 0) { return undefined; } - var right = (name).right; + let right = (name).right; var symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { error(right, Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), declarationNameToString(right)); @@ -706,26 +706,26 @@ module ts { return; } - var moduleReferenceLiteral = moduleReferenceExpression; - var searchPath = getDirectoryPath(getSourceFile(location).fileName); + let moduleReferenceLiteral = moduleReferenceExpression; + let 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. - var moduleName = escapeIdentifier(moduleReferenceLiteral.text); + let moduleName = escapeIdentifier(moduleReferenceLiteral.text); if (!moduleName) return; - var isRelative = isExternalModuleNameRelative(moduleName); + let isRelative = isExternalModuleNameRelative(moduleName); if (!isRelative) { - var symbol = getSymbol(globals, '"' + moduleName + '"', SymbolFlags.ValueModule); + let symbol = getSymbol(globals, '"' + moduleName + '"', SymbolFlags.ValueModule); if (symbol) { return symbol; } } while (true) { - var fileName = normalizePath(combinePaths(searchPath, moduleName)); + let fileName = normalizePath(combinePaths(searchPath, moduleName)); var sourceFile = host.getSourceFile(fileName + ".ts") || host.getSourceFile(fileName + ".d.ts"); if (sourceFile || isRelative) break; - var parentPath = getDirectoryPath(searchPath); + let parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) break; searchPath = parentPath; } @@ -744,7 +744,7 @@ module ts { } function getResolvedExportAssignmentSymbol(moduleSymbol: Symbol): Symbol { - var symbol = getExportAssignmentSymbol(moduleSymbol); + let symbol = getExportAssignmentSymbol(moduleSymbol); if (symbol) { if (symbol.flags & (SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace)) { return symbol; @@ -760,12 +760,12 @@ module ts { } function getExportsOfModule(moduleSymbol: Symbol): SymbolTable { - var links = getSymbolLinks(moduleSymbol); + let links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } function extendExportSymbols(target: SymbolTable, source: SymbolTable) { - for (var id in source) { + for (let id in source) { if (id !== "default" && !hasProperty(target, id)) { target[id] = source[id]; } @@ -775,15 +775,15 @@ module ts { function getExportsForModule(moduleSymbol: Symbol): SymbolTable { if (compilerOptions.target < ScriptTarget.ES6) { // A default export hides all other exports in CommonJS and AMD modules - var defaultSymbol = getExportAssignmentSymbol(moduleSymbol); + let defaultSymbol = getExportAssignmentSymbol(moduleSymbol); if (defaultSymbol) { return { "default": defaultSymbol }; } } - var result: SymbolTable; - var visitedSymbols: Symbol[] = []; + let result: SymbolTable; + let visitedSymbols: Symbol[] = []; visit(moduleSymbol); return result || moduleSymbol.exports; @@ -799,7 +799,7 @@ module ts { extendExportSymbols(result, symbol.exports); } // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports["__export"]; + let exportStars = symbol.exports["__export"]; if (exportStars) { forEach(exportStars.declarations, node => { visit(resolveExternalModuleName(node, (node).moduleSpecifier)); @@ -810,7 +810,7 @@ module ts { } function getMergedSymbol(symbol: Symbol): Symbol { - var merged: Symbol; + let merged: Symbol; return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; } @@ -849,7 +849,7 @@ module ts { } function findConstructorDeclaration(node: ClassDeclaration): ConstructorDeclaration { - var members = node.members; + let members = node.members; for (let member of members) { if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { return member; @@ -858,19 +858,19 @@ module ts { } function createType(flags: TypeFlags): Type { - var result = new Type(checker, flags); + let result = new Type(checker, flags); result.id = typeCount++; return result; } function createIntrinsicType(kind: TypeFlags, intrinsicName: string): IntrinsicType { - var type = createType(kind); + let type = createType(kind); type.intrinsicName = intrinsicName; return type; } function createObjectType(kind: TypeFlags, symbol?: Symbol): ObjectType { - var type = createType(kind); + let type = createType(kind); type.symbol = symbol; return type; } @@ -887,12 +887,12 @@ module ts { } function getNamedMembers(members: SymbolTable): Symbol[] { - var result: Symbol[]; - for (var id in members) { + let result: Symbol[]; + for (let id in members) { if (hasProperty(members, id)) { if (!isReservedMemberName(id)) { if (!result) result = []; - var symbol = members[id]; + let symbol = members[id]; if (symbolIsValue(symbol)) { result.push(symbol); } @@ -918,8 +918,8 @@ module ts { } function forEachSymbolTableInScope(enclosingDeclaration: Node, callback: (symbolTable: SymbolTable) => T): T { - var result: T; - for (var location = enclosingDeclaration; location; location = location.parent) { + let result: T; + for (let location = enclosingDeclaration; location; location = location.parent) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -962,7 +962,7 @@ module ts { } // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + let accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); return !!accessibleParent; } @@ -988,14 +988,14 @@ module ts { // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + let 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 - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + let accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -1010,7 +1010,7 @@ module ts { } function needsQualification(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags) { - var qualify = false; + let qualify = false; forEachSymbolTableInScope(enclosingDeclaration, symbolTable => { // If symbol of this name is not available in the symbol table we are ok if (!hasProperty(symbolTable, symbol.name)) { @@ -1018,7 +1018,7 @@ module ts { return false; } // If the symbol with this name is present it should refer to the symbol - var symbolFromSymbolTable = symbolTable[symbol.name]; + let symbolFromSymbolTable = symbolTable[symbol.name]; if (symbolFromSymbolTable === symbol) { // No need to qualify return true; @@ -1040,13 +1040,13 @@ module ts { function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult { if (symbol && enclosingDeclaration && !(symbol.flags & SymbolFlags.TypeParameter)) { - var initialSymbol = symbol; - var meaningToLook = meaning; + let initialSymbol = symbol; + let meaningToLook = meaning; while (symbol) { // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); + let accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + let hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); if (!hasAccessibleDeclarations) { return { accessibility: SymbolAccessibility.NotAccessible, @@ -1064,7 +1064,7 @@ module ts { // export class c { // } // } - // var x: typeof m.c + // let 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 @@ -1075,9 +1075,9 @@ module ts { // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); + let symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { - var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + let enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { @@ -1112,7 +1112,7 @@ module ts { } function hasVisibleDeclarations(symbol: Symbol): SymbolVisibilityResult { - var aliasesToMakeVisible: ImportEqualsDeclaration[]; + let aliasesToMakeVisible: ImportEqualsDeclaration[]; if (forEach(symbol.declarations, declaration => !getIsDeclarationVisible(declaration))) { return undefined; } @@ -1147,7 +1147,7 @@ module ts { function isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult { // get symbol of the first identifier of the entityName - var meaning: SymbolFlags; + let meaning: SymbolFlags; if (entityName.parent.kind === SyntaxKind.TypeQuery) { // Typeof value meaning = SymbolFlags.Value | SymbolFlags.ExportValue; @@ -1163,8 +1163,8 @@ module ts { meaning = SymbolFlags.Type; } - var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + let firstIdentifier = getFirstIdentifier(entityName); + let symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol)) || { @@ -1187,23 +1187,23 @@ module ts { } function symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string { - var writer = getSingleLineStringWriter(); + let writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - var result = writer.string(); + let result = writer.string(); releaseStringWriter(writer); return result; } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - var writer = getSingleLineStringWriter(); + let writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - var result = writer.string(); + let result = writer.string(); releaseStringWriter(writer); - var maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; + let maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; if (maxLength && result.length >= maxLength) { result = result.substr(0, maxLength - "...".length) + "..."; } @@ -1213,7 +1213,7 @@ module ts { function getTypeAliasForTypeLiteral(type: Type): Symbol { if (type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral) { - var node = type.symbol.declarations[0].parent; + let node = type.symbol.declarations[0].parent; while (node.kind === SyntaxKind.ParenthesizedType) { node = node.parent; } @@ -1225,7 +1225,7 @@ module ts { } // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder: SymbolDisplayBuilder; + let _displayBuilder: SymbolDisplayBuilder; function getSymbolDisplayBuilder(): SymbolDisplayBuilder { /** * Writes only the name of the symbol out to the writer. Uses the original source text @@ -1233,7 +1233,7 @@ module ts { */ function appendSymbolNameOnly(symbol: Symbol, writer: SymbolWriter): void { if (symbol.declarations && symbol.declarations.length > 0) { - var declaration = symbol.declarations[0]; + let declaration = symbol.declarations[0]; if (declaration.name) { writer.writeSymbol(declarationNameToString(declaration.name), symbol); return; @@ -1248,7 +1248,7 @@ module ts { * Meaning needs to be specified if the enclosing declaration is given */ function buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags, typeFlags?: TypeFormatFlags): void { - var parentSymbol: Symbol; + let parentSymbol: Symbol; function appendParentTypeArgumentsAndSymbolName(symbol: Symbol): void { if (parentSymbol) { // Write type arguments of instantiated class/interface here @@ -1277,7 +1277,7 @@ module ts { writer.trackSymbol(symbol, enclosingDeclaration, meaning); function walkSymbol(symbol: Symbol, meaning: SymbolFlags): void { if (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); + let accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -1312,8 +1312,8 @@ module ts { // Get qualified name if the symbol is not a type parameter // and there is an enclosing declaration or we specifically // asked for it - var isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - var typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; + let isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; + let typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { walkSymbol(symbol, meaning); return; @@ -1323,7 +1323,7 @@ module ts { } function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, typeStack?: Type[]) { - var globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; + let globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; return writeType(type, globalFlags); function writeType(type: Type, flags: TypeFormatFlags) { @@ -1364,7 +1364,7 @@ module ts { } function writeTypeList(types: Type[], union: boolean) { - for (var i = 0; i < types.length; i++) { + for (let i = 0; i < types.length; i++) { if (i > 0) { if (union) { writeSpace(writer); @@ -1417,7 +1417,7 @@ module ts { } else if (typeStack && contains(typeStack, type)) { // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); + let 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); @@ -1438,9 +1438,9 @@ module ts { function shouldWriteTypeOfFunctionSymbol() { if (type.symbol) { - var isStaticMethodSymbol = !!(type.symbol.flags & SymbolFlags.Method && // typeof static method + let isStaticMethodSymbol = !!(type.symbol.flags & SymbolFlags.Method && // typeof static method ts.forEach(type.symbol.declarations, declaration => declaration.flags & NodeFlags.Static)); - var isNonLocalFunctionSymbol = !!(type.symbol.flags & SymbolFlags.Function) && + let isNonLocalFunctionSymbol = !!(type.symbol.flags & SymbolFlags.Function) && (type.symbol.parent || // is exported function symbol ts.forEach(type.symbol.declarations, declaration => declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); @@ -1461,7 +1461,7 @@ module ts { } function getIndexerParameterName(type: ObjectType, indexKind: IndexKind, fallbackName: string): string { - var declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); + let 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 @@ -1472,7 +1472,7 @@ module ts { } function writeLiteralType(type: ObjectType, flags: TypeFormatFlags) { - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, SyntaxKind.OpenBraceToken); @@ -1549,9 +1549,9 @@ module ts { writer.writeLine(); } for (let p of resolved.properties) { - var t = getTypeOfSymbol(p); + let t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, SignatureKind.Call); + let signatures = getSignaturesOfType(t, SignatureKind.Call); for (let signature of signatures) { buildSymbolDisplay(p, writer); if (p.flags & SymbolFlags.Optional) { @@ -1580,7 +1580,7 @@ module ts { } function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags) { - var targetSymbol = getTargetSymbol(symbol); + let targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & SymbolFlags.Class || targetSymbol.flags & SymbolFlags.Interface) { buildDisplayForTypeParametersAndDelimiters(getTypeParametersOfClassOrInterface(symbol), writer, enclosingDeclaraiton, flags); } @@ -1588,7 +1588,7 @@ module ts { function buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); + let constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, SyntaxKind.ExtendsKeyword); @@ -1614,7 +1614,7 @@ module ts { function buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { if (typeParameters && typeParameters.length) { writePunctuation(writer, SyntaxKind.LessThanToken); - for (var i = 0; i < typeParameters.length; i++) { + for (let i = 0; i < typeParameters.length; i++) { if (i > 0) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); @@ -1628,7 +1628,7 @@ module ts { function buildDisplayForTypeArgumentsAndDelimiters(typeParameters: TypeParameter[], mapper: TypeMapper, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { if (typeParameters && typeParameters.length) { writePunctuation(writer, SyntaxKind.LessThanToken); - for (var i = 0; i < typeParameters.length; i++) { + for (let i = 0; i < typeParameters.length; i++) { if (i > 0) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); @@ -1641,7 +1641,7 @@ module ts { function buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, typeStack?: Type[]) { writePunctuation(writer, SyntaxKind.OpenParenToken); - for (var i = 0; i < parameters.length; i++) { + for (let i = 0; i < parameters.length; i++) { if (i > 0) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); @@ -1710,13 +1710,13 @@ module ts { function isUsedInExportAssignment(node: Node) { // Get source File and see if it is external module and has export assigned symbol - var externalModule = getContainingExternalModule(node); + let externalModule = getContainingExternalModule(node); if (externalModule) { // This is export assigned symbol node - var externalModuleSymbol = getSymbolOfNode(externalModule); + let externalModuleSymbol = getSymbolOfNode(externalModule); var exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); var resolvedExportSymbol: Symbol; - var symbolOfNode = getSymbolOfNode(node); + let symbolOfNode = getSymbolOfNode(node); if (isSymbolUsedInExportAssignment(symbolOfNode)) { return true; } @@ -1764,7 +1764,7 @@ module ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ImportEqualsDeclaration: - var parent = getDeclarationContainer(node); + let 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))) { @@ -1813,7 +1813,7 @@ module ts { } if (node) { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (links.isVisible === undefined) { links.isVisible = !!determineIfDeclarationIsVisible(); } @@ -1841,20 +1841,20 @@ module 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'. - var classType = getDeclaredTypeOfSymbol(prototype.parent); + let 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 { - var prop = getPropertyOfType(type, name); + let prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } // Return the inferred type for a binding element function getTypeForBindingElement(declaration: BindingElement): Type { - var pattern = declaration.parent; - var parentType = getTypeForVariableLikeDeclaration(pattern.parent); + let pattern = declaration.parent; + let parentType = getTypeForVariableLikeDeclaration(pattern.parent); // If parent has the unknown (error) type, then so does this binding element if (parentType === unknownType) { return unknownType; @@ -1870,7 +1870,7 @@ module ts { } if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name = declaration.propertyName || declaration.name; + let name = declaration.propertyName || declaration.name; // 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. var type = getTypeOfPropertyOfType(parentType, name.text) || @@ -1889,7 +1889,7 @@ module ts { } if (!declaration.dotDotDotToken) { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + indexOf(pattern.elements, declaration); + let propName = "" + indexOf(pattern.elements, declaration); var type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : getIndexTypeOfType(parentType, IndexKind.Number); if (!type) { if (isTupleType(parentType)) { @@ -1930,16 +1930,16 @@ module ts { return getTypeFromTypeNode(declaration.type); } if (declaration.kind === SyntaxKind.Parameter) { - var func = declaration.parent; + let 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)) { - var getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); + let getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } } // Use contextual parameter type if one is available - var type = getContextuallyTypedParameterType(declaration); + let type = getContextuallyTypedParameterType(declaration); if (type) { return type; } @@ -1971,11 +1971,11 @@ module ts { // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern: BindingPattern): Type { - var members: SymbolTable = {}; + let members: SymbolTable = {}; forEach(pattern.elements, e => { - var flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); - var name = e.propertyName || e.name; - var symbol = createSymbol(flags, name.text); + let flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); + let name = e.propertyName || e.name; + let symbol = createSymbol(flags, name.text); symbol.type = getTypeFromBindingElement(e); members[symbol.name] = symbol; }); @@ -1984,8 +1984,8 @@ module ts { // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern: BindingPattern): Type { - var hasSpreadElement: boolean = false; - var elementTypes: Type[] = []; + let hasSpreadElement: boolean = false; + let elementTypes: Type[] = []; forEach(pattern.elements, e => { elementTypes.push(e.kind === SyntaxKind.OmittedExpression || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); if (e.dotDotDotToken) { @@ -2018,7 +2018,7 @@ module ts { // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration, reportErrors?: boolean): Type { - var type = getTypeForVariableLikeDeclaration(declaration); + let type = getTypeForVariableLikeDeclaration(declaration); if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); @@ -2037,7 +2037,7 @@ module ts { type = declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { - var root = getRootDeclaration(declaration); + let root = getRootDeclaration(declaration); if (!isPrivateWithinAmbient(root) && !(root.kind === SyntaxKind.Parameter && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } @@ -2046,14 +2046,14 @@ module ts { } function getTypeOfVariableOrParameterOrProperty(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.type) { // Handle prototype property if (symbol.flags & SymbolFlags.Prototype) { return links.type = getTypeOfPrototypeProperty(symbol); } // Handle catch clause variables - var declaration = symbol.valueDeclaration; + let declaration = symbol.valueDeclaration; if (declaration.parent.kind === SyntaxKind.CatchClause) { return links.type = anyType; } @@ -2063,7 +2063,7 @@ module ts { } // Handle variable, parameter or property links.type = resolvingType; - var type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + let type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); if (links.type === resolvingType) { links.type = type; } @@ -2071,7 +2071,7 @@ module ts { else if (links.type === resolvingType) { links.type = anyType; if (compilerOptions.noImplicitAny) { - var diagnostic = (symbol.valueDeclaration).type ? + let diagnostic = (symbol.valueDeclaration).type ? Diagnostics._0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation : Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer; error(symbol.valueDeclaration, diagnostic, symbolToString(symbol)); @@ -2090,7 +2090,7 @@ module ts { return accessor.type && getTypeFromTypeNode(accessor.type); } else { - var setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); + let setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); } } @@ -2098,7 +2098,7 @@ module ts { } function getTypeOfAccessors(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); checkAndStoreTypeOfAccessors(symbol, links); return links.type; } @@ -2107,19 +2107,19 @@ module ts { links = links || getSymbolLinks(symbol); if (!links.type) { links.type = resolvingType; - var getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - var setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + let setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); - var type: Type; + let type: Type; // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); + let 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. - var setterParameterType = getAnnotatedAccessorType(setter); + let setterParameterType = getAnnotatedAccessorType(setter); if (setterParameterType) { type = setterParameterType; } @@ -2146,14 +2146,14 @@ module ts { else if (links.type === resolvingType) { links.type = anyType; if (compilerOptions.noImplicitAny) { - var getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + let 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)); } } } function getTypeOfFuncClassEnumModule(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.type) { links.type = createObjectType(TypeFlags.Anonymous, symbol); } @@ -2161,7 +2161,7 @@ module ts { } function getTypeOfEnumMember(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.type) { links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); } @@ -2169,7 +2169,7 @@ module ts { } function getTypeOfAlias(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.type) { links.type = getTypeOfSymbol(resolveAlias(symbol)); } @@ -2177,7 +2177,7 @@ module ts { } function getTypeOfInstantiatedSymbol(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.type) { links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); } @@ -2213,7 +2213,7 @@ module ts { function hasBaseType(type: InterfaceType, checkBase: InterfaceType) { return check(type); function check(type: InterfaceType): boolean { - var target = getTargetType(type); + let target = getTargetType(type); return target === checkBase || forEach(target.baseTypes, check); } } @@ -2222,13 +2222,13 @@ module ts { // the same, but even if they're not we still need the complete list to ensure instantiations supply type arguments // for all type parameters. function getTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] { - var result: TypeParameter[]; + let result: TypeParameter[]; forEach(symbol.declarations, node => { if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration) { - var declaration = node; + let declaration = node; if (declaration.typeParameters && declaration.typeParameters.length) { forEach(declaration.typeParameters, node => { - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + let tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); if (!result) { result = [tp]; } @@ -2243,10 +2243,10 @@ module ts { } function getDeclaredTypeOfClass(symbol: Symbol): InterfaceType { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = links.declaredType = createObjectType(TypeFlags.Class, symbol); - var typeParameters = getTypeParametersOfClassOrInterface(symbol); + let type = links.declaredType = createObjectType(TypeFlags.Class, symbol); + let typeParameters = getTypeParametersOfClassOrInterface(symbol); if (typeParameters) { type.flags |= TypeFlags.Reference; type.typeParameters = typeParameters; @@ -2256,10 +2256,10 @@ module ts { (type).typeArguments = type.typeParameters; } type.baseTypes = []; - var declaration = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); - var baseTypeNode = getClassBaseTypeNode(declaration); + let declaration = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); + let baseTypeNode = getClassBaseTypeNode(declaration); if (baseTypeNode) { - var baseType = getTypeFromTypeReferenceNode(baseTypeNode); + let baseType = getTypeFromTypeReferenceNode(baseTypeNode); if (baseType !== unknownType) { if (getTargetType(baseType).flags & TypeFlags.Class) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -2284,10 +2284,10 @@ module ts { } function getDeclaredTypeOfInterface(symbol: Symbol): InterfaceType { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = links.declaredType = createObjectType(TypeFlags.Interface, symbol); - var typeParameters = getTypeParametersOfClassOrInterface(symbol); + let type = links.declaredType = createObjectType(TypeFlags.Interface, symbol); + let typeParameters = getTypeParametersOfClassOrInterface(symbol); if (typeParameters) { type.flags |= TypeFlags.Reference; type.typeParameters = typeParameters; @@ -2300,7 +2300,7 @@ module ts { forEach(symbol.declarations, declaration => { if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { forEach(getInterfaceBaseTypeNodes(declaration), node => { - var baseType = getTypeFromTypeReferenceNode(node); + let baseType = getTypeFromTypeReferenceNode(node); if (baseType !== unknownType) { if (getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -2327,27 +2327,27 @@ module ts { } function getDeclaredTypeOfTypeAlias(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.declaredType) { links.declaredType = resolvingType; - var declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); - var type = getTypeFromTypeNode(declaration.type); + let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); + let type = getTypeFromTypeNode(declaration.type); if (links.declaredType === resolvingType) { links.declaredType = type; } } else if (links.declaredType === resolvingType) { links.declaredType = unknownType; - var declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); + let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); error(declaration.name, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } return links.declaredType; } function getDeclaredTypeOfEnum(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(TypeFlags.Enum); + let type = createType(TypeFlags.Enum); type.symbol = symbol; links.declaredType = type; } @@ -2355,9 +2355,9 @@ module ts { } function getDeclaredTypeOfTypeParameter(symbol: Symbol): TypeParameter { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(TypeFlags.TypeParameter); + let type = createType(TypeFlags.TypeParameter); type.symbol = symbol; if (!(getDeclarationOfKind(symbol, SyntaxKind.TypeParameter)).constraint) { type.constraint = noConstraintType; @@ -2368,7 +2368,7 @@ module ts { } function getDeclaredTypeOfAlias(symbol: Symbol): Type { - var links = getSymbolLinks(symbol); + let links = getSymbolLinks(symbol); if (!links.declaredType) { links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); } @@ -2399,7 +2399,7 @@ module ts { } function createSymbolTable(symbols: Symbol[]): SymbolTable { - var result: SymbolTable = {}; + let result: SymbolTable = {}; for (let symbol of symbols) { result[symbol.name] = symbol; } @@ -2407,7 +2407,7 @@ module ts { } function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper): SymbolTable { - var result: SymbolTable = {}; + let result: SymbolTable = {}; for (let symbol of symbols) { result[symbol.name] = instantiateSymbol(symbol, mapper); } @@ -2431,11 +2431,11 @@ module ts { } function resolveClassOrInterfaceMembers(type: InterfaceType): void { - var members = type.symbol.members; - var callSignatures = type.declaredCallSignatures; - var constructSignatures = type.declaredConstructSignatures; - var stringIndexType = type.declaredStringIndexType; - var numberIndexType = type.declaredNumberIndexType; + let members = type.symbol.members; + let callSignatures = type.declaredCallSignatures; + let constructSignatures = type.declaredConstructSignatures; + let stringIndexType = type.declaredStringIndexType; + let numberIndexType = type.declaredNumberIndexType; if (type.baseTypes.length) { members = createSymbolTable(type.declaredProperties); forEach(type.baseTypes, baseType => { @@ -2450,15 +2450,15 @@ module ts { } function resolveTypeReferenceMembers(type: TypeReference): void { - var target = type.target; - var mapper = createTypeMapper(target.typeParameters, type.typeArguments); - var members = createInstantiatedSymbolTable(target.declaredProperties, mapper); - var callSignatures = instantiateList(target.declaredCallSignatures, mapper, instantiateSignature); - var constructSignatures = instantiateList(target.declaredConstructSignatures, mapper, instantiateSignature); - var stringIndexType = target.declaredStringIndexType ? instantiateType(target.declaredStringIndexType, mapper) : undefined; - var numberIndexType = target.declaredNumberIndexType ? instantiateType(target.declaredNumberIndexType, mapper) : undefined; + let target = type.target; + let mapper = createTypeMapper(target.typeParameters, type.typeArguments); + let members = createInstantiatedSymbolTable(target.declaredProperties, mapper); + let callSignatures = instantiateList(target.declaredCallSignatures, mapper, instantiateSignature); + let constructSignatures = instantiateList(target.declaredConstructSignatures, mapper, instantiateSignature); + let stringIndexType = target.declaredStringIndexType ? instantiateType(target.declaredStringIndexType, mapper) : undefined; + let numberIndexType = target.declaredNumberIndexType ? instantiateType(target.declaredNumberIndexType, mapper) : undefined; forEach(target.baseTypes, baseType => { - var instantiatedBaseType = instantiateType(baseType, mapper); + let instantiatedBaseType = instantiateType(baseType, mapper); addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct)); @@ -2470,7 +2470,7 @@ module ts { function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], parameters: Symbol[], resolvedReturnType: Type, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { - var sig = new Signature(checker); + let sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -2488,10 +2488,10 @@ module ts { function getDefaultConstructSignatures(classType: InterfaceType): Signature[] { if (classType.baseTypes.length) { - var baseType = classType.baseTypes[0]; - var baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), SignatureKind.Construct); + let baseType = classType.baseTypes[0]; + let baseSignatures = getSignaturesOfType(getTypeOfSymbol(baseType.symbol), SignatureKind.Construct); return map(baseSignatures, baseSignature => { - var signature = baseType.flags & TypeFlags.Reference ? + let signature = baseType.flags & TypeFlags.Reference ? getSignatureInstantiation(baseSignature, (baseType).typeArguments) : cloneSignature(baseSignature); signature.typeParameters = classType.typeParameters; signature.resolvedReturnType = classType; @@ -2502,9 +2502,9 @@ module ts { } function createTupleTypeMemberSymbols(memberTypes: Type[]): SymbolTable { - var members: SymbolTable = {}; - for (var i = 0; i < memberTypes.length; i++) { - var symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); + let members: SymbolTable = {}; + for (let i = 0; i < memberTypes.length; i++) { + let symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); symbol.type = memberTypes[i]; members[i] = symbol; } @@ -2512,8 +2512,8 @@ module ts { } function resolveTupleTypeMembers(type: TupleType) { - var arrayType = resolveObjectOrUnionTypeMembers(createArrayType(getUnionType(type.elementTypes))); - var members = createTupleTypeMemberSymbols(type.elementTypes); + let arrayType = resolveObjectOrUnionTypeMembers(createArrayType(getUnionType(type.elementTypes))); + let members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } @@ -2522,7 +2522,7 @@ module ts { if (s.length !== t.length) { return false; } - for (var i = 0; i < s.length; i++) { + for (let i = 0; i < s.length; i++) { if (!compareSignatures(s[i], t[i], /*compareReturnTypes*/ false, compareTypes)) { return false; } @@ -2534,21 +2534,21 @@ module ts { // and if none of the signatures are generic, return a list of signatures that has substitutes a union of the // return types of the corresponding signatures in each resulting signature. function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] { - var signatureLists = map(types, t => getSignaturesOfType(t, kind)); - var signatures = signatureLists[0]; + let signatureLists = map(types, t => getSignaturesOfType(t, kind)); + let signatures = signatureLists[0]; for (let signature of signatures) { if (signature.typeParameters) { return emptyArray; } } - for (var i = 1; i < signatureLists.length; i++) { + for (let i = 1; i < signatureLists.length; i++) { if (!signatureListsIdentical(signatures, signatureLists[i])) { return emptyArray; } } - var result = map(signatures, cloneSignature); + let result = map(signatures, cloneSignature); for (var i = 0; i < result.length; i++) { - var s = result[i]; + let s = result[i]; // Clear resolved return type we possibly got from cloneSignature s.resolvedReturnType = undefined; s.unionSignatures = map(signatureLists, signatures => signatures[i]); @@ -2557,9 +2557,9 @@ module ts { } function getUnionIndexType(types: Type[], kind: IndexKind): Type { - var indexTypes: Type[] = []; + let indexTypes: Type[] = []; for (let type of types) { - var indexType = getIndexTypeOfType(type, kind); + let indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; } @@ -2571,15 +2571,15 @@ module 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). - var callSignatures = getUnionSignatures(type.types, SignatureKind.Call); - var constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); - var stringIndexType = getUnionIndexType(type.types, IndexKind.String); - var numberIndexType = getUnionIndexType(type.types, IndexKind.Number); + 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); setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveAnonymousTypeMembers(type: ObjectType) { - var symbol = type.symbol; + let symbol = type.symbol; if (symbol.flags & SymbolFlags.TypeLiteral) { var members = symbol.members; var callSignatures = getSignaturesOfSymbol(members["__call"]); @@ -2599,7 +2599,7 @@ module ts { callSignatures = getSignaturesOfSymbol(symbol); } if (symbol.flags & SymbolFlags.Class) { - var classType = getDeclaredTypeOfClass(symbol); + let classType = getDeclaredTypeOfClass(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); @@ -2648,9 +2648,9 @@ module ts { // the symbol for that property. Otherwise return undefined. function getPropertyOfObjectType(type: Type, name: string): Symbol { if (type.flags & TypeFlags.ObjectType) { - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); if (hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; + let symbol = resolved.members[name]; if (symbolIsValue(symbol)) { return symbol; } @@ -2659,9 +2659,9 @@ module ts { } function getPropertiesOfUnionType(type: UnionType): Symbol[] { - var result: Symbol[] = []; + let result: Symbol[] = []; forEach(getPropertiesOfType(type.types[0]), prop => { - var unionProp = getPropertyOfUnionType(type, prop.name); + let unionProp = getPropertyOfUnionType(type, prop.name); if (unionProp) { result.push(unionProp); } @@ -2704,12 +2704,12 @@ module ts { } function createUnionProperty(unionType: UnionType, name: string): Symbol { - var types = unionType.types; - var props: Symbol[]; + let types = unionType.types; + let props: Symbol[]; for (let current of types) { - var type = getApparentType(current); + let type = getApparentType(current); if (type !== unknownType) { - var prop = getPropertyOfType(type, name); + let prop = getPropertyOfType(type, name); if (!prop) { return undefined; } @@ -2721,15 +2721,15 @@ module ts { } } } - var propTypes: Type[] = []; - var declarations: Declaration[] = []; + let propTypes: Type[] = []; + let declarations: Declaration[] = []; for (let prop of props) { if (prop.declarations) { declarations.push.apply(declarations, prop.declarations); } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.UnionProperty, name); + let result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.UnionProperty, name); result.unionType = unionType; result.declarations = declarations; result.type = getUnionType(propTypes); @@ -2737,11 +2737,11 @@ module ts { } function getPropertyOfUnionType(type: UnionType, name: string): Symbol { - var properties = type.resolvedProperties || (type.resolvedProperties = {}); + let properties = type.resolvedProperties || (type.resolvedProperties = {}); if (hasProperty(properties, name)) { return properties[name]; } - var property = createUnionProperty(type, name); + let property = createUnionProperty(type, name); if (property) { properties[name] = property; } @@ -2761,15 +2761,15 @@ module ts { return undefined; } } - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); if (hasProperty(resolved.members, name)) { - var symbol = resolved.members[name]; + let symbol = resolved.members[name]; if (symbolIsValue(symbol)) { return symbol; } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol = getPropertyOfObjectType(globalFunctionType, name); + let symbol = getPropertyOfObjectType(globalFunctionType, name); if (symbol) return symbol; } return getPropertyOfObjectType(globalObjectType, name); @@ -2777,7 +2777,7 @@ module ts { function getSignaturesOfObjectOrUnionType(type: Type, kind: SignatureKind): Signature[] { if (type.flags & (TypeFlags.ObjectType | TypeFlags.Union)) { - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); return kind === SignatureKind.Call ? resolved.callSignatures : resolved.constructSignatures; } return emptyArray; @@ -2791,7 +2791,7 @@ module ts { function getIndexTypeOfObjectOrUnionType(type: Type, kind: IndexKind): Type { if (type.flags & (TypeFlags.ObjectType | TypeFlags.Union)) { - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); return kind === IndexKind.String ? resolved.stringIndexType : resolved.numberIndexType; } } @@ -2805,9 +2805,9 @@ module 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[] { - var result: TypeParameter[] = []; + let result: TypeParameter[] = []; forEach(typeParameterDeclarations, node => { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); + let tp = getDeclaredTypeOfTypeParameter(node.symbol); if (!contains(result, tp)) { result.push(tp); } @@ -2820,7 +2820,7 @@ module ts { return emptyArray; } - var module = resolveExternalModuleName(node, node.moduleSpecifier); + let module = resolveExternalModuleName(node, node.moduleSpecifier); if (!module || !module.exports) { return emptyArray; } @@ -2829,16 +2829,16 @@ module ts { } function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature { - var links = getNodeLinks(declaration); + let links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClass((declaration.parent).symbol) : undefined; - var typeParameters = classType ? classType.typeParameters : + let classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClass((declaration.parent).symbol) : undefined; + let typeParameters = classType ? classType.typeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; - var parameters: Symbol[] = []; - var hasStringLiterals = false; - var minArgumentCount = -1; - for (var i = 0, n = declaration.parameters.length; i < n; i++) { - var param = declaration.parameters[i]; + let parameters: Symbol[] = []; + let hasStringLiterals = false; + let minArgumentCount = -1; + for (let i = 0, n = declaration.parameters.length; i < n; i++) { + let param = declaration.parameters[i]; parameters.push(param.symbol); if (param.type && param.type.kind === SyntaxKind.StringLiteral) { hasStringLiterals = true; @@ -2854,7 +2854,7 @@ module ts { minArgumentCount = declaration.parameters.length; } - var returnType: Type; + let returnType: Type; if (classType) { returnType = classType; } @@ -2865,7 +2865,7 @@ module 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)) { - var setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); + let setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); returnType = getAnnotatedAccessorType(setter); } @@ -2882,9 +2882,9 @@ module ts { function getSignaturesOfSymbol(symbol: Symbol): Signature[] { if (!symbol) return emptyArray; - var result: Signature[] = []; - for (var i = 0, len = symbol.declarations.length; i < len; i++) { - var node = symbol.declarations[i]; + let result: Signature[] = []; + for (let i = 0, len = symbol.declarations.length; i < len; i++) { + let node = symbol.declarations[i]; switch (node.kind) { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: @@ -2903,7 +2903,7 @@ module 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) { - var previous = symbol.declarations[i - 1]; + let previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { break; } @@ -2933,7 +2933,7 @@ module ts { else if (signature.resolvedReturnType === resolvingType) { signature.resolvedReturnType = anyType; if (compilerOptions.noImplicitAny) { - var declaration = signature.declaration; + let 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)); } @@ -2947,7 +2947,7 @@ module ts { function getRestTypeOfSignature(signature: Signature): Type { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + let type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (type.flags & TypeFlags.Reference && (type).target === globalArrayType) { return (type).typeArguments[0]; } @@ -2978,8 +2978,8 @@ module 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) { - var isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; - var type = createObjectType(TypeFlags.Anonymous | TypeFlags.FromSignature); + let isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; + let type = createObjectType(TypeFlags.Anonymous | TypeFlags.FromSignature); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -2995,14 +2995,14 @@ module ts { } function getIndexDeclarationOfSymbol(symbol: Symbol, kind: IndexKind): SignatureDeclaration { - var syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; - var indexSymbol = getIndexSymbol(symbol); + let syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; + let indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { - var len = indexSymbol.declarations.length; + let len = indexSymbol.declarations.length; for (let decl of indexSymbol.declarations) { - var node = decl; + let node = decl; if (node.parameters.length === 1) { - var parameter = node.parameters[0]; + let parameter = node.parameters[0]; if (parameter && parameter.type && parameter.type.kind === syntaxKind) { return node; } @@ -3014,7 +3014,7 @@ module ts { } function getIndexTypeOfSymbol(symbol: Symbol, kind: IndexKind): Type { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); + let declaration = getIndexDeclarationOfSymbol(symbol, kind); return declaration ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; @@ -3023,7 +3023,7 @@ module ts { function getConstraintOfTypeParameter(type: TypeParameter): Type { if (!type.constraint) { if (type.target) { - var targetConstraint = getConstraintOfTypeParameter(type.target); + let targetConstraint = getConstraintOfTypeParameter(type.target); type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { @@ -3040,8 +3040,8 @@ module ts { case 2: return types[0].id + "," + types[1].id; default: - var result = ""; - for (var i = 0; i < types.length; i++) { + let result = ""; + for (let i = 0; i < types.length; i++) { if (i > 0) { result += ","; } @@ -3056,7 +3056,7 @@ module ts { // It is only necessary to do so if a constituent type might be the undefined type, the null type, or the type // of an object literal (since those types have widening related information we need to track). function getWideningFlagsOfTypes(types: Type[]): TypeFlags { - var result: TypeFlags = 0; + let result: TypeFlags = 0; for (let type of types) { result |= type.flags; } @@ -3064,10 +3064,10 @@ module ts { } function createTypeReference(target: GenericType, typeArguments: Type[]): TypeReference { - var id = getTypeListId(typeArguments); - var type = target.instantiations[id]; + let id = getTypeListId(typeArguments); + let type = target.instantiations[id]; if (!type) { - var flags = TypeFlags.Reference | getWideningFlagsOfTypes(typeArguments); + let flags = TypeFlags.Reference | getWideningFlagsOfTypes(typeArguments); type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -3076,13 +3076,13 @@ module ts { } function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: TypeReferenceNode, typeParameterSymbol: Symbol): boolean { - var links = getNodeLinks(typeReferenceNode); + let links = getNodeLinks(typeReferenceNode); if (links.isIllegalTypeReferenceInConstraint !== undefined) { return links.isIllegalTypeReferenceInConstraint; } // bubble up to the declaration - var currentNode: Node = typeReferenceNode; + let currentNode: Node = typeReferenceNode; // forEach === exists while (!forEach(typeParameterSymbol.declarations, d => d.parent === currentNode.parent)) { currentNode = currentNode.parent; @@ -3093,12 +3093,12 @@ module ts { } function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter: TypeParameterDeclaration): void { - var typeParameterSymbol: Symbol; + let typeParameterSymbol: Symbol; function check(n: Node): void { if (n.kind === SyntaxKind.TypeReference && (n).typeName.kind === SyntaxKind.Identifier) { - var links = getNodeLinks(n); + let links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { - var symbol = resolveName(typeParameter, ((n).typeName).text, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + let 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 @@ -3125,9 +3125,9 @@ module ts { } function getTypeFromTypeReferenceNode(node: TypeReferenceNode): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { - var symbol = resolveEntityName(node.typeName, SymbolFlags.Type); + let symbol = resolveEntityName(node.typeName, SymbolFlags.Type); if (symbol) { var type: Type; if ((symbol.flags & SymbolFlags.TypeParameter) && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { @@ -3140,7 +3140,7 @@ module ts { else { type = getDeclaredTypeOfSymbol(symbol); if (type.flags & (TypeFlags.Class | TypeFlags.Interface) && type.flags & TypeFlags.Reference) { - var typeParameters = (type).typeParameters; + let typeParameters = (type).typeParameters; if (node.typeArguments && node.typeArguments.length === typeParameters.length) { type = createTypeReference(type, map(node.typeArguments, getTypeFromTypeNode)); } @@ -3163,7 +3163,7 @@ module ts { } function getTypeFromTypeQueryNode(node: TypeQueryNode): Type { - var links = getNodeLinks(node); + let 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) @@ -3177,7 +3177,7 @@ module ts { function getTypeOfGlobalSymbol(symbol: Symbol, arity: number): ObjectType { function getTypeDeclaration(symbol: Symbol): Declaration { - var declarations = symbol.declarations; + let declarations = symbol.declarations; for (let declaration of declarations) { switch (declaration.kind) { case SyntaxKind.ClassDeclaration: @@ -3191,7 +3191,7 @@ module ts { if (!symbol) { return emptyObjectType; } - var type = getDeclaredTypeOfSymbol(symbol); + let 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 emptyObjectType; @@ -3227,12 +3227,12 @@ module ts { // globalArrayType will be undefined if we get here during creation of the Array type. This for example happens if // user code augments the Array type with call or construct signatures that have an array type as the return type. // We instead use globalArraySymbol to obtain the (not yet fully constructed) Array type. - var arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); + let arrayType = globalArrayType || getDeclaredTypeOfSymbol(globalArraySymbol); return arrayType !== emptyObjectType ? createTypeReference(arrayType, [elementType]) : emptyObjectType; } function getTypeFromArrayTypeNode(node: ArrayTypeNode): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); } @@ -3240,8 +3240,8 @@ module ts { } function createTupleType(elementTypes: Type[]) { - var id = getTypeListId(elementTypes); - var type = tupleTypes[id]; + let id = getTypeListId(elementTypes); + let type = tupleTypes[id]; if (!type) { type = tupleTypes[id] = createObjectType(TypeFlags.Tuple); type.elementTypes = elementTypes; @@ -3250,7 +3250,7 @@ module ts { } function getTypeFromTupleTypeNode(node: TupleTypeNode): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNode)); } @@ -3262,8 +3262,8 @@ module ts { addTypesToSortedSet(sortedSet, (type).types); } else { - var i = 0; - var id = type.id; + let i = 0; + let id = type.id; while (i < sortedSet.length && sortedSet[i].id < id) { i++; } @@ -3289,7 +3289,7 @@ module ts { } function removeSubtypes(types: Type[]) { - var i = types.length; + let i = types.length; while (i > 0) { i--; if (isSubtypeOfAny(types[i], types)) { @@ -3308,7 +3308,7 @@ module ts { } function removeAllButLast(types: Type[], typeToRemove: Type) { - var i = types.length; + let i = types.length; while (i > 0 && types.length > 1) { i--; if (types[i] === typeToRemove) { @@ -3321,7 +3321,7 @@ module ts { if (types.length === 0) { return emptyObjectType; } - var sortedTypes: Type[] = []; + let sortedTypes: Type[] = []; addTypesToSortedSet(sortedTypes, types); if (noSubtypeReduction) { if (containsAnyType(sortedTypes)) { @@ -3336,8 +3336,8 @@ module ts { if (sortedTypes.length === 1) { return sortedTypes[0]; } - var id = getTypeListId(sortedTypes); - var type = unionTypes[id]; + let id = getTypeListId(sortedTypes); + let type = unionTypes[id]; if (!type) { type = unionTypes[id] = createObjectType(TypeFlags.Union | getWideningFlagsOfTypes(sortedTypes)); type.types = sortedTypes; @@ -3346,7 +3346,7 @@ module ts { } function getTypeFromUnionTypeNode(node: UnionTypeNode): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); } @@ -3354,7 +3354,7 @@ module ts { } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node: Node): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers links.resolvedType = createObjectType(TypeFlags.Anonymous, node.symbol); @@ -3367,13 +3367,13 @@ module ts { return stringLiteralTypes[node.text]; } - var type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); + let type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); type.text = getTextOfNode(node); return type; } function getTypeFromStringLiteral(node: LiteralExpression): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getStringLiteralType(node); } @@ -3416,7 +3416,7 @@ module ts { // Callers should first ensure this by calling isTypeNode case SyntaxKind.Identifier: case SyntaxKind.QualifiedName: - var symbol = getSymbolInfo(node); + let symbol = getSymbolInfo(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: return unknownType; @@ -3425,7 +3425,7 @@ module ts { function instantiateList(items: T[], mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): T[] { if (items && items.length) { - var result: T[] = []; + let result: T[] = []; for (let v of items) { result.push(instantiator(v, mapper)); } @@ -3448,7 +3448,7 @@ module ts { case 2: return createBinaryTypeMapper(sources[0], targets[0], sources[1], targets[1]); } return t => { - for (var i = 0; i < sources.length; i++) { + for (let i = 0; i < sources.length; i++) { if (t === sources[i]) { return targets[i]; } @@ -3482,7 +3482,7 @@ module ts { function createInferenceMapper(context: InferenceContext): TypeMapper { return t => { - for (var i = 0; i < context.typeParameters.length; i++) { + for (let i = 0; i < context.typeParameters.length; i++) { if (t === context.typeParameters[i]) { return getInferredType(context, i); } @@ -3500,7 +3500,7 @@ module ts { } function instantiateTypeParameter(typeParameter: TypeParameter, mapper: TypeMapper): TypeParameter { - var result = createType(TypeFlags.TypeParameter); + let result = createType(TypeFlags.TypeParameter); result.symbol = typeParameter.symbol; if (typeParameter.constraint) { result.constraint = instantiateType(typeParameter.constraint, mapper); @@ -3517,7 +3517,7 @@ module ts { var freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); } - var result = createSignature(signature.declaration, freshTypeParameters, + let result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), signature.resolvedReturnType ? instantiateType(signature.resolvedReturnType, mapper) : undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); @@ -3528,7 +3528,7 @@ module ts { function instantiateSymbol(symbol: Symbol, mapper: TypeMapper): Symbol { if (symbol.flags & SymbolFlags.Instantiated) { - var links = getSymbolLinks(symbol); + let 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. @@ -3538,7 +3538,7 @@ module 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. - var result = createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name); + let result = createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -3551,13 +3551,13 @@ module ts { } function instantiateAnonymousType(type: ObjectType, mapper: TypeMapper): ObjectType { - var result = createObjectType(TypeFlags.Anonymous, type.symbol); + let result = createObjectType(TypeFlags.Anonymous, type.symbol); result.properties = instantiateList(getPropertiesOfObjectType(type), mapper, instantiateSymbol); result.members = createSymbolTable(result.properties); result.callSignatures = instantiateList(getSignaturesOfType(type, SignatureKind.Call), mapper, instantiateSignature); result.constructSignatures = instantiateList(getSignaturesOfType(type, SignatureKind.Construct), mapper, instantiateSignature); - var stringIndexType = getIndexTypeOfType(type, IndexKind.String); - var numberIndexType = getIndexTypeOfType(type, IndexKind.Number); + let stringIndexType = getIndexTypeOfType(type, IndexKind.String); + let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType) result.stringIndexType = instantiateType(stringIndexType, mapper); if (numberIndexType) result.numberIndexType = instantiateType(numberIndexType, mapper); return result; @@ -3621,9 +3621,9 @@ module ts { function getTypeWithoutConstructors(type: Type): Type { if (type.flags & TypeFlags.ObjectType) { - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.constructSignatures.length) { - var result = createObjectType(TypeFlags.Anonymous, type.symbol); + let result = createObjectType(TypeFlags.Anonymous, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = resolved.callSignatures; @@ -3636,9 +3636,9 @@ module ts { // TYPE CHECKING - var subtypeRelation: Map = {}; - var assignableRelation: Map = {}; - var identityRelation: Map = {}; + let subtypeRelation: Map = {}; + let assignableRelation: Map = {}; + let identityRelation: Map = {}; function isTypeIdenticalTo(source: Type, target: Type): boolean { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); @@ -3665,8 +3665,8 @@ module ts { } function isSignatureAssignableTo(source: Signature, target: Signature): boolean { - var sourceType = getOrCreateTypeFromSignature(source); - var targetType = getOrCreateTypeFromSignature(target); + let sourceType = getOrCreateTypeFromSignature(source); + let targetType = getOrCreateTypeFromSignature(target); return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); } @@ -3678,17 +3678,17 @@ module ts { headMessage?: DiagnosticMessage, containingMessageChain?: DiagnosticMessageChain): boolean { - var errorInfo: DiagnosticMessageChain; - var sourceStack: ObjectType[]; - var targetStack: ObjectType[]; - var maybeStack: Map[]; - var expandingFlags: number; - var depth = 0; - var overflow = false; + let errorInfo: DiagnosticMessageChain; + let sourceStack: ObjectType[]; + let targetStack: ObjectType[]; + let maybeStack: Map[]; + let expandingFlags: number; + let depth = 0; + let overflow = false; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + let result = isRelatedTo(source, target, errorNode !== undefined, headMessage); if (overflow) { error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } @@ -3718,7 +3718,7 @@ module ts { // Ternary.Maybe if they are related with assumptions of other relationships, or // Ternary.False if they are not related. function isRelatedTo(source: Type, target: Type, reportErrors?: boolean, headMessage?: DiagnosticMessage, elaborateErrors = false): Ternary { - var result: Ternary; + let result: Ternary; // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return Ternary.True; if (relation !== identityRelation) { @@ -3771,7 +3771,7 @@ module ts { } } else { - var saveErrorInfo = errorInfo; + let saveErrorInfo = errorInfo; if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typesRelatedTo((source).typeArguments, (target).typeArguments, reportErrors)) { @@ -3780,9 +3780,9 @@ module ts { } // Even if relationship doesn't hold for type arguments, it may hold in a structural comparison // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; + let reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; // identity relation does not use apparent type - var sourceOrApparentType = relation === identityRelation ? source : getApparentType(source); + let sourceOrApparentType = relation === identityRelation ? source : getApparentType(source); if (sourceOrApparentType.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType && (result = objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors, elaborateErrors))) { errorInfo = saveErrorInfo; @@ -3791,8 +3791,8 @@ module ts { } if (reportErrors) { headMessage = headMessage || Diagnostics.Type_0_is_not_assignable_to_type_1; - var sourceType = typeToString(source); - var targetType = typeToString(target); + let sourceType = typeToString(source); + let targetType = typeToString(target); if (sourceType === targetType) { sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); targetType = typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); @@ -3803,10 +3803,10 @@ module ts { } function unionTypeRelatedToUnionType(source: UnionType, target: UnionType): Ternary { - var result = Ternary.True; - var sourceTypes = source.types; + let result = Ternary.True; + let sourceTypes = source.types; for (let sourceType of sourceTypes) { - var related = typeRelatedToUnionType(sourceType, target, false); + let related = typeRelatedToUnionType(sourceType, target, false); if (!related) { return Ternary.False; } @@ -3816,9 +3816,9 @@ module ts { } function typeRelatedToUnionType(source: Type, target: UnionType, reportErrors: boolean): Ternary { - var targetTypes = target.types; - for (var i = 0, len = targetTypes.length; i < len; i++) { - var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + let targetTypes = target.types; + for (let i = 0, len = targetTypes.length; i < len; i++) { + let related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { return related; } @@ -3827,10 +3827,10 @@ module ts { } function unionTypeRelatedToType(source: UnionType, target: Type, reportErrors: boolean): Ternary { - var result = Ternary.True; - var sourceTypes = source.types; + let result = Ternary.True; + let sourceTypes = source.types; for (let sourceType of sourceTypes) { - var related = isRelatedTo(sourceType, target, reportErrors); + let related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return Ternary.False; } @@ -3840,9 +3840,9 @@ module ts { } function typesRelatedTo(sources: Type[], targets: Type[], reportErrors: boolean): Ternary { - var result = Ternary.True; - for (var i = 0, len = sources.length; i < len; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); + let result = Ternary.True; + for (let i = 0, len = sources.length; i < len; i++) { + let related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return Ternary.False; } @@ -3867,7 +3867,7 @@ module ts { } else { while (true) { - var constraint = getConstraintOfTypeParameter(source); + let constraint = getConstraintOfTypeParameter(source); if (constraint === target) return Ternary.True; if (!(constraint && constraint.flags & TypeFlags.TypeParameter)) break; source = constraint; @@ -3885,9 +3885,9 @@ module ts { if (overflow) { return Ternary.False; } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation[id]; - //var related: RelationComparisonResult = undefined; // relation[id]; + let id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + let related = relation[id]; + //let related: RelationComparisonResult = undefined; // 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 @@ -3896,7 +3896,7 @@ module ts { } } if (depth > 0) { - for (var i = 0; i < depth; i++) { + for (let i = 0; i < depth; i++) { // If source and target are already being compared, consider them related with assumptions if (maybeStack[i][id]) { return Ternary.Maybe; @@ -3918,14 +3918,15 @@ module ts { maybeStack[depth] = {}; maybeStack[depth][id] = RelationComparisonResult.Succeeded; depth++; - var saveExpandingFlags = expandingFlags; + let saveExpandingFlags = expandingFlags; if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack)) expandingFlags |= 2; + let result: Ternary; if (expandingFlags === 3) { - var result = Ternary.Maybe; + result = Ternary.Maybe; } else { - var result = propertiesRelatedTo(source, target, reportErrors); + result = propertiesRelatedTo(source, target, reportErrors); if (result) { result &= signaturesRelatedTo(source, target, SignatureKind.Call, reportErrors); if (result) { @@ -3942,9 +3943,9 @@ module ts { expandingFlags = saveExpandingFlags; depth--; if (result) { - var maybeCache = maybeStack[depth]; + let maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up - var destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1]; + let destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1]; copyMap(maybeCache, destinationCache); } else { @@ -3962,10 +3963,10 @@ module ts { // some level beyond that. function isDeeplyNestedGeneric(type: ObjectType, stack: ObjectType[]): boolean { if (type.flags & TypeFlags.Reference && depth >= 10) { - var target = (type).target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; + let target = (type).target; + let count = 0; + for (let i = 0; i < depth; i++) { + let t = stack[i]; if (t.flags & TypeFlags.Reference && (t).target === target) { count++; if (count >= 10) return true; @@ -3979,11 +3980,11 @@ module ts { if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var result = Ternary.True; - var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); + let result = Ternary.True; + let properties = getPropertiesOfObjectType(target); + let requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); for (let targetProp of properties) { - var sourceProp = getPropertyOfType(source, targetProp.name); + let sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { if (!(targetProp.flags & SymbolFlags.Optional) || requireOptionalProperties) { @@ -3994,8 +3995,8 @@ module ts { } } else if (!(targetProp.flags & SymbolFlags.Prototype)) { - var sourceFlags = getDeclarationFlagsFromSymbol(sourceProp); - var targetFlags = getDeclarationFlagsFromSymbol(targetProp); + let sourceFlags = getDeclarationFlagsFromSymbol(sourceProp); + let targetFlags = getDeclarationFlagsFromSymbol(targetProp); if (sourceFlags & NodeFlags.Private || targetFlags & NodeFlags.Private) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -4012,9 +4013,9 @@ module ts { } } else if (targetFlags & NodeFlags.Protected) { - var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + let sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; + let sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; + let 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, @@ -4030,7 +4031,7 @@ module ts { } return Ternary.False; } - var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + let related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); if (!related) { if (reportErrors) { reportError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); @@ -4059,18 +4060,18 @@ module ts { } function propertiesIdenticalTo(source: ObjectType, target: ObjectType): Ternary { - var sourceProperties = getPropertiesOfObjectType(source); - var targetProperties = getPropertiesOfObjectType(target); + let sourceProperties = getPropertiesOfObjectType(source); + let targetProperties = getPropertiesOfObjectType(target); if (sourceProperties.length !== targetProperties.length) { return Ternary.False; } - var result = Ternary.True; + let result = Ternary.True; for (let sourceProp of sourceProperties) { - var targetProp = getPropertyOfObjectType(target, sourceProp.name); + let targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return Ternary.False; } - var related = compareProperties(sourceProp, targetProp, isRelatedTo); + let related = compareProperties(sourceProp, targetProp, isRelatedTo); if (!related) { return Ternary.False; } @@ -4086,16 +4087,16 @@ module ts { if (target === anyFunctionType || source === anyFunctionType) { return Ternary.True; } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var result = Ternary.True; - var saveErrorInfo = errorInfo; + let sourceSignatures = getSignaturesOfType(source, kind); + let targetSignatures = getSignaturesOfType(target, kind); + let result = Ternary.True; + let saveErrorInfo = errorInfo; outer: for (let t of targetSignatures) { if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) { - var localErrors = reportErrors; + let localErrors = reportErrors; for (let s of sourceSignatures) { if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) { - var related = signatureRelatedTo(s, t, localErrors); + let related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; errorInfo = saveErrorInfo; @@ -4118,9 +4119,9 @@ module ts { if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { return Ternary.False; } - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var checkCount: number; + let sourceMax = source.parameters.length; + let targetMax = target.parameters.length; + let checkCount: number; if (source.hasRestParameter && target.hasRestParameter) { checkCount = sourceMax > targetMax ? sourceMax : targetMax; sourceMax--; @@ -4141,12 +4142,12 @@ module 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); - var result = Ternary.True; - for (var i = 0; i < checkCount; i++) { - var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - var saveErrorInfo = errorInfo; - var related = isRelatedTo(s, t, reportErrors); + 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; + let related = isRelatedTo(s, t, reportErrors); if (!related) { related = isRelatedTo(t, s, false); if (!related) { @@ -4161,21 +4162,21 @@ module ts { } result &= related; } - var t = getReturnTypeOfSignature(target); + let t = getReturnTypeOfSignature(target); if (t === voidType) return result; - var s = getReturnTypeOfSignature(source); + let s = getReturnTypeOfSignature(source); return result & isRelatedTo(s, t, reportErrors); } function signaturesIdenticalTo(source: ObjectType, target: ObjectType, kind: SignatureKind): Ternary { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); + let sourceSignatures = getSignaturesOfType(source, kind); + let targetSignatures = getSignaturesOfType(target, kind); if (sourceSignatures.length !== targetSignatures.length) { return Ternary.False; } - var result = Ternary.True; - for (var i = 0, len = sourceSignatures.length; i < len; ++i) { - var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*compareReturnTypes*/ true, isRelatedTo); + let result = Ternary.True; + for (let i = 0, len = sourceSignatures.length; i < len; ++i) { + let related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*compareReturnTypes*/ true, isRelatedTo); if (!related) { return Ternary.False; } @@ -4188,16 +4189,16 @@ module ts { if (relation === identityRelation) { return indexTypesIdenticalTo(IndexKind.String, source, target); } - var targetType = getIndexTypeOfType(target, IndexKind.String); + let targetType = getIndexTypeOfType(target, IndexKind.String); if (targetType) { - var sourceType = getIndexTypeOfType(source, IndexKind.String); + let sourceType = getIndexTypeOfType(source, IndexKind.String); if (!sourceType) { if (reportErrors) { reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return Ternary.False; } - var related = isRelatedTo(sourceType, targetType, reportErrors); + let related = isRelatedTo(sourceType, targetType, reportErrors); if (!related) { if (reportErrors) { reportError(Diagnostics.Index_signatures_are_incompatible); @@ -4213,10 +4214,10 @@ module ts { if (relation === identityRelation) { return indexTypesIdenticalTo(IndexKind.Number, source, target); } - var targetType = getIndexTypeOfType(target, IndexKind.Number); + let targetType = getIndexTypeOfType(target, IndexKind.Number); if (targetType) { - var sourceStringType = getIndexTypeOfType(source, IndexKind.String); - var sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); + let sourceStringType = getIndexTypeOfType(source, IndexKind.String); + let sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); if (!(sourceStringType || sourceNumberType)) { if (reportErrors) { reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); @@ -4242,8 +4243,8 @@ module ts { } function indexTypesIdenticalTo(indexKind: IndexKind, source: ObjectType, target: ObjectType): Ternary { - var targetType = getIndexTypeOfType(target, indexKind); - var sourceType = getIndexTypeOfType(source, indexKind); + let targetType = getIndexTypeOfType(target, indexKind); + let sourceType = getIndexTypeOfType(source, indexKind); if (!sourceType && !targetType) { return Ternary.True; } @@ -4265,8 +4266,8 @@ module ts { if (sourceProp === targetProp) { return Ternary.True; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); + let sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); + let targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); if (sourcePropAccessibility !== targetPropAccessibility) { return Ternary.False; } @@ -4292,13 +4293,13 @@ module ts { source.hasRestParameter !== target.hasRestParameter) { return Ternary.False; } - var result = Ternary.True; + let result = Ternary.True; if (source.typeParameters && target.typeParameters) { if (source.typeParameters.length !== target.typeParameters.length) { return Ternary.False; } - for (var i = 0, len = source.typeParameters.length; i < len; ++i) { - var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); + for (let i = 0, len = source.typeParameters.length; i < len; ++i) { + let related = compareTypes(source.typeParameters[i], target.typeParameters[i]); if (!related) { return Ternary.False; } @@ -4312,10 +4313,10 @@ module 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); - for (var i = 0, len = source.parameters.length; i < len; i++) { - var s = source.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); - var t = target.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); - var related = compareTypes(s, t); + for (let i = 0, len = source.parameters.length; i < len; i++) { + let s = source.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); + let t = target.hasRestParameter && i === len - 1 ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); + let related = compareTypes(s, t); if (!related) { return Ternary.False; } @@ -4339,14 +4340,14 @@ module ts { } function reportNoCommonSupertypeError(types: Type[], errorLocation: Node, errorMessageChainHead: DiagnosticMessageChain): void { - var bestSupertype: Type; - var bestSupertypeDownfallType: Type; // The type that caused bestSupertype not to be the common supertype - var bestSupertypeScore = 0; + let bestSupertype: Type; + let bestSupertypeDownfallType: Type; // The type that caused bestSupertype not to be the common supertype + let bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType: Type = undefined; - for (var j = 0; j < types.length; j++) { + for (let i = 0; i < types.length; i++) { + let score = 0; + let downfallType: Type = undefined; + for (let j = 0; j < types.length; j++) { if (isTypeSubtypeOf(types[j], types[i])) { score++; } @@ -4396,13 +4397,13 @@ module ts { } function getWidenedTypeOfObjectLiteral(type: Type): Type { - var properties = getPropertiesOfObjectType(type); - var members: SymbolTable = {}; + let properties = getPropertiesOfObjectType(type); + let members: SymbolTable = {}; forEach(properties, p => { - var propType = getTypeOfSymbol(p); - var widenedType = getWidenedType(propType); + let propType = getTypeOfSymbol(p); + let widenedType = getWidenedType(propType); if (propType !== widenedType) { - var symbol = createSymbol(p.flags | SymbolFlags.Transient, p.name); + let symbol = createSymbol(p.flags | SymbolFlags.Transient, p.name); symbol.declarations = p.declarations; symbol.parent = p.parent; symbol.type = widenedType; @@ -4412,8 +4413,8 @@ module ts { } members[p.name] = p; }); - var stringIndexType = getIndexTypeOfType(type, IndexKind.String); - var numberIndexType = getIndexTypeOfType(type, IndexKind.Number); + let stringIndexType = getIndexTypeOfType(type, IndexKind.String); + let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType) stringIndexType = getWidenedType(stringIndexType); if (numberIndexType) numberIndexType = getWidenedType(numberIndexType); return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); @@ -4439,7 +4440,7 @@ module ts { function reportWideningErrorsInType(type: Type): boolean { if (type.flags & TypeFlags.Union) { - var errorReported = false; + let errorReported = false; forEach((type).types, t => { if (reportWideningErrorsInType(t)) { errorReported = true; @@ -4451,9 +4452,9 @@ module ts { return reportWideningErrorsInType((type).typeArguments[0]); } if (type.flags & TypeFlags.ObjectLiteral) { - var errorReported = false; + let errorReported = false; forEach(getPropertiesOfObjectType(type), p => { - var t = getTypeOfSymbol(p); + let 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))); @@ -4467,7 +4468,7 @@ module ts { } function reportImplicitAnyError(declaration: Declaration, type: Type) { - var typeAsString = typeToString(getWidenedType(type)); + let typeAsString = typeToString(getWidenedType(type)); switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: @@ -4507,9 +4508,9 @@ module ts { } function forEachMatchingParameterType(source: Signature, target: Signature, callback: (s: Type, t: Type) => void) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count: number; + let sourceMax = source.parameters.length; + let targetMax = target.parameters.length; + let count: number; if (source.hasRestParameter && target.hasRestParameter) { count = sourceMax > targetMax ? sourceMax : targetMax; sourceMax--; @@ -4526,15 +4527,15 @@ module ts { else { count = sourceMax < targetMax ? sourceMax : targetMax; } - for (var i = 0; i < count; i++) { - var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + 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); callback(s, t); } } function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { - var inferences: TypeInferences[] = []; + let inferences: TypeInferences[] = []; for (let unused of typeParameters) { inferences.push({ primary: undefined, secondary: undefined }); } @@ -4548,14 +4549,14 @@ module ts { } function inferTypes(context: InferenceContext, source: Type, target: Type) { - var sourceStack: Type[]; - var targetStack: Type[]; - var depth = 0; - var inferiority = 0; + let sourceStack: Type[]; + let targetStack: Type[]; + let depth = 0; + let inferiority = 0; inferFromTypes(source, target); function isInProcess(source: Type, target: Type) { - for (var i = 0; i < depth; i++) { + for (let i = 0; i < depth; i++) { if (source === sourceStack[i] && target === targetStack[i]) { return true; } @@ -4565,10 +4566,10 @@ module ts { function isWithinDepthLimit(type: Type, stack: Type[]) { if (depth >= 5) { - var target = (type).target; - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; + let target = (type).target; + let count = 0; + for (let i = 0; i < depth; i++) { + let t = stack[i]; if (t.flags & TypeFlags.Reference && (t).target === target) { count++; } @@ -4584,11 +4585,11 @@ module ts { } if (target.flags & TypeFlags.TypeParameter) { // If target is a type parameter, make an inference - var typeParameters = context.typeParameters; - for (var i = 0; i < typeParameters.length; i++) { + let typeParameters = context.typeParameters; + for (let i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { - var inferences = context.inferences[i]; - var candidates = inferiority ? + let inferences = context.inferences[i]; + let candidates = inferiority ? inferences.secondary || (inferences.secondary = []) : inferences.primary || (inferences.primary = []); if (!contains(candidates, source)) candidates.push(source); @@ -4598,16 +4599,16 @@ module 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 - var sourceTypes = (source).typeArguments; - var targetTypes = (target).typeArguments; - for (var i = 0; i < sourceTypes.length; i++) { + let sourceTypes = (source).typeArguments; + let targetTypes = (target).typeArguments; + for (let i = 0; i < sourceTypes.length; i++) { inferFromTypes(sourceTypes[i], targetTypes[i]); } } else if (target.flags & TypeFlags.Union) { - var targetTypes = (target).types; - var typeParameterCount = 0; - var typeParameter: TypeParameter; + let targetTypes = (target).types; + let typeParameterCount = 0; + let typeParameter: TypeParameter; // First infer to each type in union that isn't a type parameter for (let t of targetTypes) { if (t.flags & TypeFlags.TypeParameter && contains(context.typeParameters, t)) { @@ -4627,7 +4628,7 @@ module ts { } else if (source.flags & TypeFlags.Union) { // Source is a union type, infer from each consituent type - var sourceTypes = (source).types; + let sourceTypes = (source).types; for (let sourceType of sourceTypes) { inferFromTypes(sourceType, target); } @@ -4655,9 +4656,9 @@ module ts { } function inferFromProperties(source: Type, target: Type) { - var properties = getPropertiesOfObjectType(target); + let properties = getPropertiesOfObjectType(target); for (let targetProp of properties) { - var sourceProp = getPropertyOfObjectType(source, targetProp.name); + let sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -4665,12 +4666,12 @@ module ts { } function inferFromSignatures(source: Type, target: Type, kind: SignatureKind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var sourceLen = sourceSignatures.length; - var targetLen = targetSignatures.length; - var len = sourceLen < targetLen ? sourceLen : targetLen; - for (var i = 0; i < len; i++) { + let sourceSignatures = getSignaturesOfType(source, kind); + let targetSignatures = getSignaturesOfType(target, kind); + let sourceLen = sourceSignatures.length; + let targetLen = targetSignatures.length; + let len = sourceLen < targetLen ? sourceLen : targetLen; + for (let i = 0; i < len; i++) { inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } } @@ -4681,9 +4682,9 @@ module ts { } function inferFromIndexTypes(source: Type, target: Type, sourceKind: IndexKind, targetKind: IndexKind) { - var targetIndexType = getIndexTypeOfType(target, targetKind); + let targetIndexType = getIndexTypeOfType(target, targetKind); if (targetIndexType) { - var sourceIndexType = getIndexTypeOfType(source, sourceKind); + let sourceIndexType = getIndexTypeOfType(source, sourceKind); if (sourceIndexType) { inferFromTypes(sourceIndexType, targetIndexType); } @@ -4692,17 +4693,17 @@ module ts { } function getInferenceCandidates(context: InferenceContext, index: number): Type[] { - var inferences = context.inferences[index]; + let inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } function getInferredType(context: InferenceContext, index: number): Type { - var inferredType = context.inferredTypes[index]; + let inferredType = context.inferredTypes[index]; if (!inferredType) { - var inferences = getInferenceCandidates(context, index); + let inferences = getInferenceCandidates(context, index); if (inferences.length) { // Infer widened union or supertype, or the undefined type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + let unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : inferenceFailureType; } else { @@ -4710,7 +4711,7 @@ module ts { inferredType = emptyObjectType; } if (inferredType !== inferenceFailureType) { - var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + let constraint = getConstraintOfTypeParameter(context.typeParameters[index]); inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; } context.inferredTypes[index] = inferredType; @@ -4719,7 +4720,7 @@ module ts { } function getInferredTypes(context: InferenceContext): Type[] { - for (var i = 0; i < context.inferredTypes.length; i++) { + for (let i = 0; i < context.inferredTypes.length; i++) { getInferredType(context, i); } @@ -4733,7 +4734,7 @@ module ts { // EXPRESSION TYPE CHECKING function getResolvedSymbol(node: Identifier): Symbol { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = (getFullWidth(node) > 0 && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node)) || unknownSymbol; } @@ -4763,10 +4764,10 @@ module 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) { - var types = (type).types; + let 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 - var narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); + let narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { return narrowedType; } @@ -4786,9 +4787,9 @@ module ts { // Check if a given variable is assigned within a given syntax node function isVariableAssignedWithin(symbol: Symbol, node: Node): boolean { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (links.assignmentChecks) { - var cachedResult = links.assignmentChecks[symbol.id]; + let cachedResult = links.assignmentChecks[symbol.id]; if (cachedResult !== undefined) { return cachedResult; } @@ -4800,7 +4801,7 @@ module ts { function isAssignedInBinaryExpression(node: BinaryExpression) { if (node.operatorToken.kind >= SyntaxKind.FirstAssignment && node.operatorToken.kind <= SyntaxKind.LastAssignment) { - var n = node.left; + let n = node.left; while (n.kind === SyntaxKind.ParenthesizedExpression) { n = (n).expression; } @@ -4869,8 +4870,8 @@ module ts { function resolveLocation(node: Node) { // Resolve location from top down towards node if it is a context sensitive expression // That helps in making sure not assigning types as any when resolved out of order - var containerNodes: Node[] = []; - for (var parent = node.parent; parent; parent = parent.parent) { + let containerNodes: Node[] = []; + for (let parent = node.parent; parent; parent = parent.parent) { if ((isExpression(parent) || isObjectLiteralMethod(node)) && isContextSensitive(parent)) { containerNodes.unshift(parent); @@ -4909,13 +4910,13 @@ module ts { // Get the narrowed type of a given symbol at a given location function getNarrowedTypeOfSymbol(symbol: Symbol, node: Node) { - var type = getTypeOfSymbol(symbol); + let type = getTypeOfSymbol(symbol); // Only narrow when symbol is variable of type any or an object, union, or type parameter type if (node && symbol.flags & SymbolFlags.Variable && type.flags & (TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) { loop: while (node.parent) { - var child = node; + let child = node; node = node.parent; - var narrowedType = type; + let narrowedType = type; switch (node.kind) { case SyntaxKind.IfStatement: // In a branch of an if statement, narrow based on controlling expression @@ -4967,12 +4968,12 @@ module ts { if (expr.left.kind !== SyntaxKind.TypeOfExpression || expr.right.kind !== SyntaxKind.StringLiteral) { return type; } - var left = expr.left; - var right = expr.right; + let left = expr.left; + let right = expr.right; if (left.expression.kind !== SyntaxKind.Identifier || getResolvedSymbol(left.expression) !== symbol) { return type; } - var typeInfo = primitiveTypeInfo[right.text]; + let typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === SyntaxKind.ExclamationEqualsEqualsToken) { assumeTrue = !assumeTrue; } @@ -5036,16 +5037,16 @@ module ts { return type; } // Check that right operand is a function type with a prototype property - var rightType = checkExpression(expr.right); + let rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } // Target type is type of prototype property - var prototypeProperty = getPropertyOfType(rightType, "prototype"); + let prototypeProperty = getPropertyOfType(rightType, "prototype"); if (!prototypeProperty) { return type; } - var targetType = getTypeOfSymbol(prototypeProperty); + let targetType = getTypeOfSymbol(prototypeProperty); // Narrow to target type if it is a subtype of current type if (isTypeSubtypeOf(targetType, type)) { return targetType; @@ -5064,7 +5065,7 @@ module ts { case SyntaxKind.ParenthesizedExpression: return narrowType(type, (expr).expression, assumeTrue); case SyntaxKind.BinaryExpression: - var operator = (expr).operatorToken.kind; + let operator = (expr).operatorToken.kind; if (operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { return narrowTypeByEquality(type, expr, assumeTrue); } @@ -5089,7 +5090,7 @@ module ts { } function checkIdentifier(node: Identifier): Type { - var symbol = getResolvedSymbol(node); + let 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 @@ -5113,7 +5114,7 @@ module ts { } function isInsideFunction(node: Node, threshold: Node): boolean { - var current = node; + let current = node; while (current && current !== threshold) { if (isFunctionLike(current)) { return true; @@ -5137,7 +5138,7 @@ module ts { // nesting structure: // (variable declaration or binding element) -> variable declaration list -> container - var container: Node = symbol.valueDeclaration; + let container: Node = symbol.valueDeclaration; while (container.kind !== SyntaxKind.VariableDeclarationList) { container = container.parent; } @@ -5148,9 +5149,9 @@ module ts { container = container.parent; } - var inFunction = isInsideFunction(node.parent, container); + let inFunction = isInsideFunction(node.parent, container); - var current = container; + let current = container; while (current && !nodeStartsNewLexicalEnvironment(current)) { if (isIterationStatement(current, /*lookInLabeledStatements*/ false)) { if (inFunction) { @@ -5165,7 +5166,7 @@ module ts { } function captureLexicalThis(node: Node, container: Node): void { - var classNode = container.parent && container.parent.kind === SyntaxKind.ClassDeclaration ? container.parent : undefined; + let classNode = container.parent && container.parent.kind === SyntaxKind.ClassDeclaration ? container.parent : undefined; getNodeLinks(node).flags |= NodeCheckFlags.LexicalThis; if (container.kind === SyntaxKind.PropertyDeclaration || container.kind === SyntaxKind.Constructor) { getNodeLinks(classNode).flags |= NodeCheckFlags.CaptureThis; @@ -5178,8 +5179,8 @@ module ts { function checkThisExpression(node: Node): Type { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. - var container = getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; + let container = getThisContainer(node, /* includeArrowFunctions */ true); + let needToCaptureLexicalThis = false; // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === SyntaxKind.ArrowFunction) { @@ -5220,16 +5221,16 @@ module ts { captureLexicalThis(node, container); } - var classNode = container.parent && container.parent.kind === SyntaxKind.ClassDeclaration ? container.parent : undefined; + let classNode = container.parent && container.parent.kind === SyntaxKind.ClassDeclaration ? container.parent : undefined; if (classNode) { - var symbol = getSymbolOfNode(classNode); + let symbol = getSymbolOfNode(classNode); return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol); } return anyType; } function isInConstructorArgumentInitializer(node: Node, constructorDecl: Node): boolean { - for (var n = node; n && n !== constructorDecl; n = n.parent) { + for (let n = node; n && n !== constructorDecl; n = n.parent) { if (n.kind === SyntaxKind.Parameter) { return true; } @@ -5238,11 +5239,11 @@ module ts { } function checkSuperExpression(node: Node): Type { - var isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; - var enclosingClass = getAncestor(node, SyntaxKind.ClassDeclaration); - var baseClass: Type; + let isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; + let enclosingClass = getAncestor(node, SyntaxKind.ClassDeclaration); + let baseClass: Type; if (enclosingClass && getClassBaseTypeNode(enclosingClass)) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); + let classType = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClass)); baseClass = classType.baseTypes.length && classType.baseTypes[0]; } @@ -5251,10 +5252,10 @@ module ts { return unknownType; } - var container = getSuperContainer(node, /*includeFunctions*/ true); + let container = getSuperContainer(node, /*includeFunctions*/ true); if (container) { - var canUseSuperExpression = false; + let canUseSuperExpression = false; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes @@ -5296,7 +5297,7 @@ module ts { } if (canUseSuperExpression) { - var returnType: Type; + let returnType: Type; if ((container.flags & NodeFlags.Static) || isCallExpression) { getNodeLinks(node).flags |= NodeCheckFlags.SuperStatic; @@ -5340,14 +5341,14 @@ module ts { // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type { if (isFunctionExpressionOrArrowFunction(parameter.parent)) { - var func = parameter.parent; + let func = parameter.parent; if (isContextSensitive(func)) { - var contextualSignature = getContextualSignature(func); + let contextualSignature = getContextualSignature(func); if (contextualSignature) { - var funcHasRestParameters = hasRestParameters(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = indexOf(func.parameters, parameter); + let funcHasRestParameters = hasRestParameters(func); + let len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + let indexOfParameter = indexOf(func.parameters, parameter); if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -5369,13 +5370,13 @@ module 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 { - var declaration = node.parent; + let declaration = node.parent; if (node === declaration.initializer) { if (declaration.type) { return getTypeFromTypeNode(declaration.type); } if (declaration.kind === SyntaxKind.Parameter) { - var type = getContextuallyTypedParameterType(declaration); + let type = getContextuallyTypedParameterType(declaration); if (type) { return type; } @@ -5388,7 +5389,7 @@ module ts { } function getContextualTypeForReturnExpression(node: Expression): Type { - var func = getContainingFunction(node); + let func = getContainingFunction(node); if (func) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed @@ -5397,7 +5398,7 @@ module 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 - var signature = getContextualSignatureForFunctionLikeDeclaration(func); + let signature = getContextualSignatureForFunctionLikeDeclaration(func); if (signature) { return getReturnTypeOfSignature(signature); } @@ -5407,10 +5408,10 @@ module 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 { - var args = getEffectiveCallArguments(callTarget); - var argIndex = indexOf(args, arg); + let args = getEffectiveCallArguments(callTarget); + let argIndex = indexOf(args, arg); if (argIndex >= 0) { - var signature = getResolvedSignature(callTarget); + let signature = getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); } return undefined; @@ -5425,8 +5426,8 @@ module ts { } function getContextualTypeForBinaryOperand(node: Expression): Type { - var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; + let binaryExpression = node.parent; + let 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) { @@ -5436,7 +5437,7 @@ module ts { else if (operator === SyntaxKind.BarBarToken) { // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand. - var type = getContextualType(binaryExpression); + let type = getContextualType(binaryExpression); if (!type && node === binaryExpression.right) { type = checkExpression(binaryExpression.left); } @@ -5452,11 +5453,11 @@ module ts { if (!(type.flags & TypeFlags.Union)) { return mapper(type); } - var types = (type).types; - var mappedType: Type; - var mappedTypes: Type[]; + let types = (type).types; + let mappedType: Type; + let mappedTypes: Type[]; for (let current of types) { - var t = mapper(current); + let t = mapper(current); if (t) { if (!mappedType) { mappedType = t; @@ -5474,7 +5475,7 @@ module ts { function getTypeOfPropertyOfContextualType(type: Type, name: string) { return applyToContextualType(type, t => { - var prop = getPropertyOfObjectType(t, name); + let prop = getPropertyOfObjectType(t, name); return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -5507,15 +5508,15 @@ module ts { } function getContextualTypeForObjectLiteralElement(element: ObjectLiteralElement) { - var objectLiteral = element.parent; - var type = getContextualType(objectLiteral); + let objectLiteral = element.parent; + let 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. - var symbolName = getSymbolOfNode(element).name; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + let symbolName = getSymbolOfNode(element).name; + let propertyType = getTypeOfPropertyOfContextualType(type, symbolName); if (propertyType) { return propertyType; } @@ -5533,10 +5534,10 @@ module 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 { - var arrayLiteral = node.parent; - var type = getContextualType(arrayLiteral); + let arrayLiteral = node.parent; + let type = getContextualType(arrayLiteral); if (type) { - var index = indexOf(arrayLiteral.elements, node); + let index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, IndexKind.Number) || (languageVersion >= ScriptTarget.ES6 ? checkIteratedType(type, /*expressionForError*/ undefined) : undefined); @@ -5546,7 +5547,7 @@ module ts { // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node: Expression): Type { - var conditional = node.parent; + let conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } @@ -5560,7 +5561,7 @@ module ts { if (node.contextualType) { return node.contextualType; } - var parent = node.parent; + let parent = node.parent; switch (parent.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: @@ -5596,9 +5597,9 @@ module 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 { - var signatures = getSignaturesOfObjectOrUnionType(type, SignatureKind.Call); + let signatures = getSignaturesOfObjectOrUnionType(type, SignatureKind.Call); if (signatures.length === 1) { - var signature = signatures[0]; + let signature = signatures[0]; if (!signature.typeParameters) { return signature; } @@ -5621,7 +5622,7 @@ module ts { // union type of return types from these signatures function getContextualSignature(node: FunctionExpression | MethodDeclaration): Signature { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); - var type = isObjectLiteralMethod(node) + let type = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); if (!type) { @@ -5630,8 +5631,8 @@ module ts { if (!(type.flags & TypeFlags.Union)) { return getNonGenericSignature(type); } - var signatureList: Signature[]; - var types = (type).types; + let signatureList: Signature[]; + let types = (type).types; for (let current of types) { // The signature set of all constituent type with call signatures should match // So number of signatures allowed is either 0 or 1 @@ -5640,7 +5641,7 @@ module ts { return undefined; } - var signature = getNonGenericSignature(current); + let signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -5658,7 +5659,7 @@ module ts { } // Result is union of signatures collected (return type is union of return types of this signature set) - var result: Signature; + let result: Signature; if (signatureList) { result = cloneSignature(signatureList[0]); // Clear resolved return type we possibly got from cloneSignature @@ -5678,7 +5679,7 @@ module 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 { - var parent = node.parent; + let parent = node.parent; if (parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node) { return true; } @@ -5692,7 +5693,7 @@ module ts { } function checkSpreadElementExpression(node: SpreadElementExpression, contextualMapper?: TypeMapper): Type { - var type = checkExpressionCached(node.expression, contextualMapper); + let type = checkExpressionCached(node.expression, contextualMapper); if (!isArrayLikeType(type)) { error(node.expression, Diagnostics.Type_0_is_not_an_array_type, typeToString(type)); return unknownType; @@ -5701,14 +5702,14 @@ module ts { } function checkArrayLiteral(node: ArrayLiteralExpression, contextualMapper?: TypeMapper): Type { - var elements = node.elements; + let elements = node.elements; if (!elements.length) { return createArrayType(undefinedType); } - var hasSpreadElement: boolean = false; - var elementTypes: Type[] = []; + let hasSpreadElement: boolean = false; + let elementTypes: Type[] = []; forEach(elements, e => { - var type = checkExpression(e, contextualMapper); + let type = checkExpression(e, contextualMapper); if (e.kind === SyntaxKind.SpreadElementExpression) { elementTypes.push(getIndexTypeOfType(type, IndexKind.Number) || anyType); hasSpreadElement = true; @@ -5718,7 +5719,7 @@ module ts { } }); if (!hasSpreadElement) { - var contextualType = getContextualType(node); + let contextualType = getContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType) || isAssignmentTarget(node)) { return createTupleType(elementTypes); } @@ -5762,7 +5763,7 @@ module ts { } function checkComputedPropertyName(node: ComputedPropertyName): Type { - var links = getNodeLinks(node.expression); + let links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); @@ -5783,13 +5784,13 @@ module ts { // Grammar checking checkGrammarObjectLiteralExpression(node); - var propertiesTable: SymbolTable = {}; - var propertiesArray: Symbol[] = []; - var contextualType = getContextualType(node); - var typeFlags: TypeFlags; + let propertiesTable: SymbolTable = {}; + let propertiesArray: Symbol[] = []; + let contextualType = getContextualType(node); + let typeFlags: TypeFlags; for (let memberDecl of node.properties) { - var member = memberDecl.symbol; + let member = memberDecl.symbol; if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || isObjectLiteralMethod(memberDecl)) { @@ -5806,7 +5807,7 @@ module ts { : checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; - var prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); + let prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); prop.declarations = member.declarations; prop.parent = member.parent; if (member.valueDeclaration) { @@ -5833,29 +5834,29 @@ module ts { propertiesArray.push(member); } - var stringIndexType = getIndexType(IndexKind.String); - var numberIndexType = getIndexType(IndexKind.Number); - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + let stringIndexType = getIndexType(IndexKind.String); + let numberIndexType = getIndexType(IndexKind.Number); + let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.ContainsUndefinedOrNull); return result; function getIndexType(kind: IndexKind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - var propTypes: Type[] = []; - for (var i = 0; i < propertiesArray.length; i++) { - var propertyDecl = node.properties[i]; + let propTypes: Type[] = []; + for (let i = 0; i < propertiesArray.length; i++) { + let 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. - var type = getTypeOfSymbol(propertiesArray[i]); + let type = getTypeOfSymbol(propertiesArray[i]); if (!contains(propTypes, type)) { propTypes.push(type); } } } - var result = propTypes.length ? getUnionType(propTypes) : undefinedType; + let result = propTypes.length ? getUnionType(propTypes) : undefinedType; typeFlags |= result.flags; return result; } @@ -5874,16 +5875,16 @@ module ts { } function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol) { - var flags = getDeclarationFlagsFromSymbol(prop); + let flags = getDeclarationFlagsFromSymbol(prop); // Public properties are always accessible if (!(flags & (NodeFlags.Private | NodeFlags.Protected))) { return; } // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - var enclosingClassDeclaration = getAncestor(node, SyntaxKind.ClassDeclaration); - var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; - var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + let enclosingClassDeclaration = getAncestor(node, SyntaxKind.ClassDeclaration); + let enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; + let declaringClass = getDeclaredTypeOfSymbol(prop.parent); // Private property is accessible if declaring and enclosing class are the same if (flags & NodeFlags.Private) { if (declaringClass !== enclosingClass) { @@ -5920,15 +5921,15 @@ module ts { } function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { - var type = checkExpressionOrQualifiedName(left); + let type = checkExpressionOrQualifiedName(left); if (type === unknownType) return type; if (type !== anyType) { - var apparentType = getApparentType(getWidenedType(type)); + let apparentType = getApparentType(getWidenedType(type)); if (apparentType === unknownType) { // handle cases when type is Type parameter with invalid constraint return unknownType; } - var prop = getPropertyOfType(apparentType, right.text); + let 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)); @@ -5957,19 +5958,19 @@ module ts { } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { - var left = node.kind === SyntaxKind.PropertyAccessExpression + let left = node.kind === SyntaxKind.PropertyAccessExpression ? (node).expression : (node).left; - var type = checkExpressionOrQualifiedName(left); + let type = checkExpressionOrQualifiedName(left); if (type !== unknownType && type !== anyType) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); + let prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & SymbolFlags.Class) { if (left.kind === SyntaxKind.SuperKeyword && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { return false; } else { - var modificationCount = diagnostics.getModificationCount(); + let modificationCount = diagnostics.getModificationCount(); checkClassPropertyAccess(node, left, type, prop); return diagnostics.getModificationCount() === modificationCount; } @@ -5981,28 +5982,28 @@ module ts { function checkIndexedAccess(node: ElementAccessExpression): Type { // Grammar checking if (!node.argumentExpression) { - var sourceFile = getSourceFile(node); + let sourceFile = getSourceFile(node); if (node.parent.kind === SyntaxKind.NewExpression && (node.parent).expression === node) { - var start = skipTrivia(sourceFile.text, node.expression.end); - var end = node.end; + let start = skipTrivia(sourceFile.text, node.expression.end); + let end = node.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); } else { - var start = node.end - "]".length; - var end = node.end; + let start = node.end - "]".length; + let 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 - var objectType = getApparentType(checkExpression(node.expression)); - var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + let objectType = getApparentType(checkExpression(node.expression)); + let indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; if (objectType === unknownType) { return unknownType; } - var isConstEnum = isConstEnumObjectType(objectType); + let 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); @@ -6020,9 +6021,9 @@ module ts { // See if we can index as a property. if (node.argumentExpression) { - var name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + let name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); if (name !== undefined) { - var prop = getPropertyOfType(objectType, name); + let prop = getPropertyOfType(objectType, name); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); @@ -6039,14 +6040,14 @@ module ts { // Try to use a number indexer. if (allConstituentTypesHaveKind(indexType, TypeFlags.Any | TypeFlags.NumberLike)) { - var numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); + let numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); if (numberIndexType) { return numberIndexType; } } // Try to use string indexing. - var stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); + let stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); if (stringIndexType) { return stringIndexType; } @@ -6076,7 +6077,7 @@ module ts { return (indexArgumentExpression).text; } if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { - var rightHandSideName = ((indexArgumentExpression).name).text; + let rightHandSideName = ((indexArgumentExpression).name).text; return getPropertyNameForKnownSymbolName(rightHandSideName); } @@ -6110,13 +6111,13 @@ module ts { // The name is Symbol., so make sure Symbol actually resolves to the // global Symbol object - var leftHandSide = (expression).expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + let leftHandSide = (expression).expression; + let leftHandSideSymbol = getResolvedSymbol(leftHandSide); if (!leftHandSideSymbol) { return false; } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(); + let globalESSymbol = getGlobalESSymbolConstructorSymbol(); if (!globalESSymbol) { // Already errored when we tried to look up the symbol return false; @@ -6155,19 +6156,19 @@ module ts { // so order how inherited signatures are processed is still preserved. // interface A { (x: string): void } // interface B extends A { (x: 'foo'): string } - // var b: B; + // let b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures: Signature[], result: Signature[]): void { - var lastParent: Node; - var lastSymbol: Symbol; - var cutoffIndex: number = 0; - var index: number; - var specializedIndex: number = -1; - var spliceIndex: number; + let lastParent: Node; + let lastSymbol: Symbol; + let cutoffIndex: number = 0; + let index: number; + let specializedIndex: number = -1; + let spliceIndex: number; Debug.assert(!result.length); for (let signature of signatures) { - var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent = signature.declaration && signature.declaration.parent; + let symbol = signature.declaration && getSymbolOfNode(signature.declaration); + let parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { index++; @@ -6204,7 +6205,7 @@ module ts { } function getSpreadArgumentIndex(args: Expression[]): number { - for (var i = 0; i < args.length; i++) { + for (let i = 0; i < args.length; i++) { if (args[i].kind === SyntaxKind.SpreadElementExpression) { return i; } @@ -6213,12 +6214,12 @@ module ts { } function hasCorrectArity(node: CallLikeExpression, args: Expression[], signature: Signature) { - var adjustedArgCount: number; // Apparent number of arguments we will have in this call - var typeArguments: NodeArray; // Type arguments (undefined if none) - var callIsIncomplete: boolean; // In incomplete call we want to be lenient when we have too few arguments + let adjustedArgCount: number; // Apparent number of arguments we will have in this call + let typeArguments: NodeArray; // Type arguments (undefined if none) + let callIsIncomplete: boolean; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === SyntaxKind.TaggedTemplateExpression) { - var tagExpression = node; + let 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 @@ -6228,8 +6229,8 @@ module 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. - var templateExpression = tagExpression.template; - var lastSpan = lastOrUndefined(templateExpression.templateSpans); + let templateExpression = tagExpression.template; + let lastSpan = lastOrUndefined(templateExpression.templateSpans); Debug.assert(lastSpan !== undefined); // we should always have at least one span. callIsIncomplete = getFullWidth(lastSpan.literal) === 0 || !!lastSpan.literal.isUnterminated; } @@ -6237,13 +6238,13 @@ module 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. - var templateLiteral = tagExpression.template; + let templateLiteral = tagExpression.template; Debug.assert(templateLiteral.kind === SyntaxKind.NoSubstitutionTemplateLiteral); callIsIncomplete = !!templateLiteral.isUnterminated; } } else { - var callExpression = node; + let callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' Debug.assert(callExpression.kind === SyntaxKind.NewExpression); @@ -6262,7 +6263,7 @@ module 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. - var hasRightNumberOfTypeArgs = !typeArguments || + let hasRightNumberOfTypeArgs = !typeArguments || (signature.typeParameters && typeArguments.length === signature.typeParameters.length); if (!hasRightNumberOfTypeArgs) { return false; @@ -6270,7 +6271,7 @@ module ts { // If spread arguments are present, check that they correspond to a rest parameter. If so, no // further checking is necessary. - var spreadArgIndex = getSpreadArgumentIndex(args); + let spreadArgIndex = getSpreadArgumentIndex(args); if (spreadArgIndex >= 0) { return signature.hasRestParameter && spreadArgIndex >= signature.parameters.length - 1; } @@ -6281,14 +6282,14 @@ module ts { } // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = adjustedArgCount >= signature.minArgumentCount; + let 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) { - var resolved = resolveObjectOrUnionTypeMembers(type); + let resolved = resolveObjectOrUnionTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { return resolved.callSignatures[0]; @@ -6299,7 +6300,7 @@ module 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 { - var context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + let 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); @@ -6308,23 +6309,23 @@ module ts { } function inferTypeArguments(signature: Signature, args: Expression[], excludeArgument: boolean[]): InferenceContext { - var typeParameters = signature.typeParameters; - var context = createInferenceContext(typeParameters, /*inferUnionTypes*/ false); - var inferenceMapper = createInferenceMapper(context); + let typeParameters = signature.typeParameters; + let context = createInferenceContext(typeParameters, /*inferUnionTypes*/ false); + let inferenceMapper = createInferenceMapper(context); // 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. - for (var i = 0; i < args.length; i++) { - var arg = args[i]; + for (let i = 0; i < args.length; i++) { + let arg = args[i]; if (arg.kind !== SyntaxKind.OmittedExpression) { - var paramType = getTypeAtPosition(signature, arg.kind === SyntaxKind.SpreadElementExpression ? -1 : i); + let paramType = getTypeAtPosition(signature, arg.kind === SyntaxKind.SpreadElementExpression ? -1 : i); if (i === 0 && args[i].parent.kind === SyntaxKind.TaggedTemplateExpression) { var argType = globalTemplateStringsArrayType; } else { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; + let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; var argType = checkExpressionWithContextualType(arg, paramType, mapper); } inferTypes(context, argType, paramType); @@ -6335,22 +6336,22 @@ module ts { // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) if (excludeArgument) { - for (var i = 0; i < args.length; i++) { + for (let i = 0; i < args.length; i++) { // No need to check for omitted args and template expressions, their exlusion value is always undefined if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, arg.kind === SyntaxKind.SpreadElementExpression ? -1 : i); + let arg = args[i]; + let paramType = getTypeAtPosition(signature, arg.kind === SyntaxKind.SpreadElementExpression ? -1 : i); inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } } - var inferredTypes = getInferredTypes(context); + let inferredTypes = getInferredTypes(context); // Inference has failed if the inferenceFailureType type is in list of inferences context.failedTypeParameterIndex = indexOf(inferredTypes, inferenceFailureType); // Wipe out the inferenceFailureType from the array so that error recovery can work properly - for (var i = 0; i < inferredTypes.length; i++) { + for (let i = 0; i < inferredTypes.length; i++) { if (inferredTypes[i] === inferenceFailureType) { inferredTypes[i] = unknownType; } @@ -6360,15 +6361,15 @@ module ts { } function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean): boolean { - var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; - for (var i = 0; i < typeParameters.length; i++) { - var typeArgNode = typeArguments[i]; - var typeArgument = getTypeFromTypeNode(typeArgNode); + let typeParameters = signature.typeParameters; + let typeArgumentsAreAssignable = true; + for (let i = 0; i < typeParameters.length; i++) { + let typeArgNode = typeArguments[i]; + let typeArgument = getTypeFromTypeNode(typeArgNode); // Do not push on this array! It has a preallocated length typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); + let constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); @@ -6379,14 +6380,14 @@ module ts { } function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; + for (let i = 0; i < args.length; i++) { + let arg = args[i]; if (arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, arg.kind === SyntaxKind.SpreadElementExpression ? -1 : i); + let paramType = getTypeAtPosition(signature, arg.kind === SyntaxKind.SpreadElementExpression ? -1 : i); // A tagged template expression provides a special first argument, and string literals get string literal types // unless we're reporting errors - var argType = i === 0 && node.kind === SyntaxKind.TaggedTemplateExpression ? globalTemplateStringsArrayType : + let argType = i === 0 && node.kind === SyntaxKind.TaggedTemplateExpression ? globalTemplateStringsArrayType : arg.kind === SyntaxKind.StringLiteral && !reportErrors ? getStringLiteralType(arg) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); // Use argument expression as error location when reporting errors @@ -6407,9 +6408,9 @@ module ts { * expressions, where the first element of the list is the template for error reporting purposes. */ function getEffectiveCallArguments(node: CallLikeExpression): Expression[] { - var args: Expression[]; + let args: Expression[]; if (node.kind === SyntaxKind.TaggedTemplateExpression) { - var template = (node).template; + let template = (node).template; args = [template]; if (template.kind === SyntaxKind.TemplateExpression) { @@ -6437,8 +6438,8 @@ module ts { */ function getEffectiveTypeArguments(callExpression: CallExpression): TypeNode[] { if (callExpression.expression.kind === SyntaxKind.SuperKeyword) { - var containingClass = getAncestor(callExpression, SyntaxKind.ClassDeclaration); - var baseClassTypeNode = containingClass && getClassBaseTypeNode(containingClass); + let containingClass = getAncestor(callExpression, SyntaxKind.ClassDeclaration); + let baseClassTypeNode = containingClass && getClassBaseTypeNode(containingClass); return baseClassTypeNode && baseClassTypeNode.typeArguments; } else { @@ -6448,9 +6449,9 @@ module ts { } function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[]): Signature { - var isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; + let isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; - var typeArguments: TypeNode[]; + let typeArguments: TypeNode[]; if (!isTaggedTemplate) { typeArguments = getEffectiveTypeArguments(node); @@ -6461,7 +6462,7 @@ module ts { } } - var candidates = candidatesOutArray || []; + let candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { @@ -6469,7 +6470,7 @@ module ts { return resolveErrorCall(node); } - var args = getEffectiveCallArguments(node); + let 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. @@ -6482,8 +6483,8 @@ module ts { // // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. - var excludeArgument: boolean[]; - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + let excludeArgument: boolean[]; + for (let i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { if (isContextSensitive(args[i])) { if (!excludeArgument) { excludeArgument = new Array(args.length); @@ -6513,10 +6514,10 @@ module ts { // function foo() {} // foo(0, true); // - var candidateForArgumentError: Signature; - var candidateForTypeArgumentError: Signature; - var resultOfFailedInference: InferenceContext; - var result: Signature; + let candidateForArgumentError: Signature; + let candidateForTypeArgumentError: Signature; + let resultOfFailedInference: InferenceContext; + let result: Signature; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument @@ -6560,10 +6561,10 @@ module ts { } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); + let failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; + let inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); - var diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError + 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, typeToString(failedTypeParameter)); @@ -6595,13 +6596,13 @@ module ts { continue; } - var originalCandidate = current; - var inferenceResult: InferenceContext; + let originalCandidate = current; + let inferenceResult: InferenceContext; while (true) { var candidate = originalCandidate; if (candidate.typeParameters) { - var typeArgumentTypes: Type[]; + let typeArgumentTypes: Type[]; var typeArgumentsAreValid: boolean; if (typeArguments) { typeArgumentTypes = new Array(candidate.typeParameters.length); @@ -6620,7 +6621,7 @@ module ts { if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { break; } - var index = excludeArgument ? indexOf(excludeArgument, true) : -1; + let index = excludeArgument ? indexOf(excludeArgument, true) : -1; if (index < 0) { return candidate; } @@ -6633,7 +6634,7 @@ module 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) { - var instantiatedCandidate = candidate; + let instantiatedCandidate = candidate; if (typeArgumentsAreValid) { candidateForArgumentError = instantiatedCandidate; } @@ -6657,15 +6658,15 @@ module ts { function resolveCallExpression(node: CallExpression, candidatesOutArray: Signature[]): Signature { if (node.expression.kind === SyntaxKind.SuperKeyword) { - var superType = checkSuperExpression(node.expression); + let superType = checkSuperExpression(node.expression); if (superType !== unknownType) { return resolveCall(node, getSignaturesOfType(superType, SignatureKind.Construct), candidatesOutArray); } return resolveUntypedCall(node); } - var funcType = checkExpression(node.expression); - var apparentType = getApparentType(funcType); + let funcType = checkExpression(node.expression); + let apparentType = getApparentType(funcType); if (apparentType === unknownType) { // Another error has already been reported @@ -6676,9 +6677,9 @@ module 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. - var callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - var constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + let 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 @@ -6709,13 +6710,13 @@ module ts { function resolveNewExpression(node: NewExpression, candidatesOutArray: Signature[]): Signature { if (node.arguments && languageVersion < ScriptTarget.ES6) { - var spreadIndex = getSpreadArgumentIndex(node.arguments); + let spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { error(node.arguments[spreadIndex], Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_6_and_higher); } } - var expressionType = checkExpression(node.expression); + let expressionType = checkExpression(node.expression); // TS 1.0 spec: 4.11 // If ConstructExpr is of type Any, Args can be any argument // list and the result of the operation is of type Any. @@ -6741,7 +6742,7 @@ module 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. - var constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); + let constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); if (constructSignatures.length) { return resolveCall(node, constructSignatures, candidatesOutArray); } @@ -6750,9 +6751,9 @@ module 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. - var callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); + let callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); + let signature = resolveCall(node, callSignatures, candidatesOutArray); if (getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } @@ -6764,15 +6765,15 @@ module ts { } function resolveTaggedTemplateExpression(node: TaggedTemplateExpression, candidatesOutArray: Signature[]): Signature { - var tagType = checkExpression(node.tag); - var apparentType = getApparentType(tagType); + let tagType = checkExpression(node.tag); + let apparentType = getApparentType(tagType); if (apparentType === unknownType) { // Another error has already been reported return resolveErrorCall(node); } - var callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); if (tagType === anyType || (!callSignatures.length && !(tagType.flags & TypeFlags.Union) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); @@ -6789,7 +6790,7 @@ module 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 { - var links = getNodeLinks(node); + let 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 @@ -6817,12 +6818,12 @@ module ts { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - var signature = getResolvedSignature(node); + let signature = getResolvedSignature(node); if (node.expression.kind === SyntaxKind.SuperKeyword) { return voidType; } if (node.kind === SyntaxKind.NewExpression) { - var declaration = signature.declaration; + let declaration = signature.declaration; if (declaration && declaration.kind !== SyntaxKind.Constructor && declaration.kind !== SyntaxKind.ConstructSignature && @@ -6843,10 +6844,10 @@ module ts { } function checkTypeAssertion(node: TypeAssertion): Type { - var exprType = checkExpression(node.expression); - var targetType = getTypeFromTypeNode(node.type); + let exprType = checkExpression(node.expression); + let targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { - var widenedType = getWidenedType(exprType); + let widenedType = getWidenedType(exprType); if (!(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } @@ -6866,30 +6867,31 @@ module ts { } function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - for (var i = 0; i < len; i++) { - var parameter = signature.parameters[i]; - var links = getSymbolLinks(parameter); + let len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (let i = 0; i < len; i++) { + let parameter = signature.parameters[i]; + let links = getSymbolLinks(parameter); links.type = instantiateType(getTypeAtPosition(context, i), mapper); } if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { - var parameter = signature.parameters[signature.parameters.length - 1]; - var links = getSymbolLinks(parameter); + let parameter = signature.parameters[signature.parameters.length - 1]; + let links = getSymbolLinks(parameter); links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper); } } function getReturnTypeFromBody(func: FunctionLikeDeclaration, contextualMapper?: TypeMapper): Type { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + let contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } + if (func.body.kind !== SyntaxKind.Block) { var type = checkExpressionCached(func.body, contextualMapper); } else { // Aggregate the types of expressions within all the return statements. - var types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); + let types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper); if (types.length === 0) { return voidType; } @@ -6909,12 +6911,12 @@ module ts { /// Returns a set of types relating to every return expression relating to a function block. function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper?: TypeMapper): Type[] { - var aggregatedTypes: Type[] = []; + let aggregatedTypes: Type[] = []; forEachReturnStatement(body, returnStatement => { - var expr = returnStatement.expression; + let expr = returnStatement.expression; if (expr) { - var type = checkExpressionCached(expr, contextualMapper); + let type = checkExpressionCached(expr, contextualMapper); if (!contains(aggregatedTypes, type)) { aggregatedTypes.push(type); } @@ -6953,7 +6955,7 @@ module ts { return; } - var bodyBlock = func.body; + let bodyBlock = func.body; // Ensure the body has at least one return expression. if (bodyContainsAReturnStatement(bodyBlock)) { @@ -6975,7 +6977,7 @@ module ts { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); // Grammar checking - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + let hasGrammarError = checkGrammarFunctionLikeDeclaration(node); if (!hasGrammarError && node.kind === SyntaxKind.FunctionExpression) { checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); } @@ -6984,24 +6986,24 @@ module ts { if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } - var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + let links = getNodeLinks(node); + let type = getTypeOfSymbol(node.symbol); // Check if function expression is contextually typed and assign parameter types if so if (!(links.flags & NodeCheckFlags.ContextChecked)) { - var contextualSignature = getContextualSignature(node); + let 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. if (!(links.flags & NodeCheckFlags.ContextChecked)) { links.flags |= NodeCheckFlags.ContextChecked; if (contextualSignature) { - var signature = getSignaturesOfType(type, SignatureKind.Call)[0]; + let signature = getSignaturesOfType(type, SignatureKind.Call)[0]; if (isContextSensitive(node)) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } if (!node.type) { signature.resolvedReturnType = resolvingType; - var returnType = getReturnTypeFromBody(node, contextualMapper); + let returnType = getReturnTypeFromBody(node, contextualMapper); if (signature.resolvedReturnType === resolvingType) { signature.resolvedReturnType = returnType; } @@ -7030,7 +7032,7 @@ module ts { checkSourceElement(node.body); } else { - var exprType = checkExpression(node.body); + let exprType = checkExpression(node.body); if (node.type) { checkTypeAssignableTo(exprType, getTypeFromTypeNode(node.type), node.body, /*headMessage*/ undefined); } @@ -7049,7 +7051,7 @@ module ts { function checkReferenceExpression(n: Node, invalidReferenceMessage: DiagnosticMessage, constantVariableMessage: DiagnosticMessage): boolean { function findSymbol(n: Node): Symbol { - var symbol = getNodeLinks(n).resolvedSymbol; + let 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. @@ -7093,12 +7095,12 @@ module ts { var symbol = findSymbol(n); return symbol && (symbol.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0; case SyntaxKind.ElementAccessExpression: - var index = (n).argumentExpression; + let index = (n).argumentExpression; var symbol = findSymbol((n).expression); if (symbol && index && index.kind === SyntaxKind.StringLiteral) { - var name = (index).text; - var prop = getPropertyOfType(getTypeOfSymbol(symbol), name); + let name = (index).text; + let prop = getPropertyOfType(getTypeOfSymbol(symbol), name); return prop && (prop.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(prop) & NodeFlags.Const) !== 0; } return false; @@ -7128,17 +7130,17 @@ module ts { grammarErrorOnNode(node.expression, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode); } - var operandType = checkExpression(node.expression); + let operandType = checkExpression(node.expression); return booleanType; } function checkTypeOfExpression(node: TypeOfExpression): Type { - var operandType = checkExpression(node.expression); + let operandType = checkExpression(node.expression); return stringType; } function checkVoidExpression(node: VoidExpression): Type { - var operandType = checkExpression(node.expression); + let operandType = checkExpression(node.expression); return undefinedType; } @@ -7151,7 +7153,7 @@ module ts { checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); } - var operandType = checkExpression(node.operand); + let operandType = checkExpression(node.operand); switch (node.operator) { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: @@ -7164,7 +7166,7 @@ module ts { return booleanType; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: - var ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + let 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, @@ -7183,8 +7185,8 @@ module ts { // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. checkGrammarEvalOrArgumentsInStrictMode(node, node.operand); - var operandType = checkExpression(node.operand); - var ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_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); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, @@ -7201,7 +7203,7 @@ module ts { return true; } if (type.flags & TypeFlags.Union) { - var types = (type).types; + let types = (type).types; for (let current of types) { if (current.flags & kind) { return true; @@ -7218,7 +7220,7 @@ module ts { return true; } if (type.flags & TypeFlags.Union) { - var types = (type).types; + let types = (type).types; for (let current of types) { if (!(current.flags & kind)) { return false; @@ -7268,12 +7270,12 @@ module ts { } function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type, contextualMapper?: TypeMapper): Type { - var properties = node.properties; + let properties = node.properties; for (let p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { // TODO(andersh): Computed property support - var name = (p).name; - var type = sourceType.flags & TypeFlags.Any ? sourceType : + let name = (p).name; + let type = sourceType.flags & TypeFlags.Any ? sourceType : getTypeOfPropertyOfType(sourceType, name.text) || isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, IndexKind.Number) || getIndexTypeOfType(sourceType, IndexKind.String); @@ -7297,13 +7299,13 @@ module ts { error(node, Diagnostics.Type_0_is_not_an_array_type, typeToString(sourceType)); return sourceType; } - var elements = node.elements; - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; + let elements = node.elements; + for (let i = 0; i < elements.length; i++) { + let e = elements[i]; if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { - var propName = "" + i; - var type = sourceType.flags & TypeFlags.Any ? sourceType : + let propName = "" + i; + let type = sourceType.flags & TypeFlags.Any ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : getIndexTypeOfType(sourceType, IndexKind.Number); if (type) { @@ -7346,7 +7348,7 @@ module ts { } function checkReferenceAssignment(target: Expression, sourceType: Type, contextualMapper?: TypeMapper): Type { - var targetType = checkExpression(target, contextualMapper); + let 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); } @@ -7361,12 +7363,12 @@ module ts { checkGrammarEvalOrArgumentsInStrictMode(node, node.left); } - var operator = node.operatorToken.kind; + let operator = node.operatorToken.kind; if (operator === SyntaxKind.EqualsToken && (node.left.kind === SyntaxKind.ObjectLiteralExpression || node.left.kind === SyntaxKind.ArrayLiteralExpression)) { return checkDestructuringAssignment(node.left, checkExpression(node.right, contextualMapper), contextualMapper); } - var leftType = checkExpression(node.left, contextualMapper); - var rightType = checkExpression(node.right, contextualMapper); + let leftType = checkExpression(node.left, contextualMapper); + let rightType = checkExpression(node.right, contextualMapper); switch (operator) { case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: @@ -7397,7 +7399,7 @@ module ts { if (leftType.flags & (TypeFlags.Undefined | TypeFlags.Null)) leftType = rightType; if (rightType.flags & (TypeFlags.Undefined | TypeFlags.Null)) rightType = leftType; - var suggestedOperator: SyntaxKind; + let suggestedOperator: SyntaxKind; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion if ((leftType.flags & TypeFlags.Boolean) && @@ -7407,8 +7409,8 @@ module ts { } else { // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(node.left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(node.right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + let leftOk = checkArithmeticOperandType(node.left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + let rightOk = checkArithmeticOperandType(node.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); } @@ -7425,7 +7427,7 @@ module ts { if (leftType.flags & (TypeFlags.Undefined | TypeFlags.Null)) leftType = rightType; if (rightType.flags & (TypeFlags.Undefined | TypeFlags.Null)) rightType = leftType; - var resultType: Type; + let resultType: Type; if (allConstituentTypesHaveKind(leftType, TypeFlags.NumberLike) && allConstituentTypesHaveKind(rightType, TypeFlags.NumberLike)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. @@ -7490,7 +7492,7 @@ module ts { // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { - var offendingSymbolOperand = + let offendingSymbolOperand = someConstituentTypeHasKind(leftType, TypeFlags.ESSymbol) ? node.left : someConstituentTypeHasKind(rightType, TypeFlags.ESSymbol) ? node.right : undefined; @@ -7526,7 +7528,7 @@ module 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. - var ok = checkReferenceExpression(node.left, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + let ok = checkReferenceExpression(node.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 @@ -7552,8 +7554,8 @@ module ts { function checkConditionalExpression(node: ConditionalExpression, contextualMapper?: TypeMapper): Type { checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, contextualMapper); - var type2 = checkExpression(node.whenFalse, contextualMapper); + let type1 = checkExpression(node.whenTrue, contextualMapper); + let type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } @@ -7571,15 +7573,15 @@ module ts { } function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper?: TypeMapper): Type { - var saveContextualType = node.contextualType; + let saveContextualType = node.contextualType; node.contextualType = contextualType; - var result = checkExpression(node, contextualMapper); + let result = checkExpression(node, contextualMapper); node.contextualType = saveContextualType; return result; } function checkExpressionCached(node: Expression, contextualMapper?: TypeMapper): Type { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = checkExpression(node, contextualMapper); } @@ -7608,17 +7610,17 @@ module ts { checkComputedPropertyName(node.name); } - var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); + let uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } function instantiateTypeWithSingleGenericCallSignature(node: Expression | MethodDeclaration, type: Type, contextualMapper?: TypeMapper) { if (contextualMapper && contextualMapper !== identityMapper) { - var signature = getSingleCallSignature(type); + let signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - var contextualType = getContextualType(node); + let contextualType = getContextualType(node); if (contextualType) { - var contextualSignature = getSingleCallSignature(contextualType); + let contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper)); } @@ -7641,12 +7643,12 @@ module ts { // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. function checkExpressionOrQualifiedName(node: Expression | QualifiedName, contextualMapper?: TypeMapper): Type { - var type: Type; + let type: Type; if (node.kind == SyntaxKind.QualifiedName) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, contextualMapper); + let uninstantiatedType = checkExpressionWorker(node, contextualMapper); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } @@ -7655,7 +7657,7 @@ module ts { // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = + let 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)); @@ -7768,7 +7770,7 @@ module ts { checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); checkVariableLikeDeclaration(node); - var func = getContainingFunction(node); + let func = getContainingFunction(node); if (node.flags & NodeFlags.AccessibilityModifier) { func = getContainingFunction(node); if (!(func.kind === SyntaxKind.Constructor && nodeIsPresent(func.body))) { @@ -7824,7 +7826,7 @@ module ts { function checkTypeForDuplicateIndexSignatures(node: Node) { if (node.kind === SyntaxKind.InterfaceDeclaration) { - var nodeSymbol = getSymbolOfNode(node); + let 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) { @@ -7835,12 +7837,12 @@ module 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 - var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + let indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol) { - var seenNumericIndexer = false; - var seenStringIndexer = false; + let seenNumericIndexer = false; + let seenStringIndexer = false; for (let decl of indexSymbol.declarations) { - var declaration = decl; + let declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: @@ -7888,8 +7890,8 @@ module ts { checkSourceElement(node.body); - var symbol = getSymbolOfNode(node); - var firstDeclaration = getDeclarationOfKind(symbol, node.kind); + let symbol = getSymbolOfNode(node); + let firstDeclaration = getDeclarationOfKind(symbol, node.kind); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(symbol); @@ -7946,12 +7948,12 @@ module ts { // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = + let superCallShouldBeFirst = forEach((node.parent).members, isInstancePropertyWithInitializer) || forEach(node.parameters, p => p.flags & (NodeFlags.Public | NodeFlags.Private | NodeFlags.Protected)); if (superCallShouldBeFirst) { - var statements = (node.body).statements; + let statements = (node.body).statements; if (!statements.length || statements[0].kind !== SyntaxKind.ExpressionStatement || !isSuperCallExpression((statements[0]).expression)) { error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } @@ -7981,15 +7983,15 @@ module ts { if (!hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - var otherAccessor = getDeclarationOfKind(node.symbol, otherKind); + let otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; + let 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); } - var currentAccessorType = getAnnotatedAccessorType(node); - var otherAccessorType = getAnnotatedAccessorType(otherAccessor); + let currentAccessorType = getAnnotatedAccessorType(node); + let 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) { @@ -8010,15 +8012,15 @@ module ts { // Grammar checking checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReferenceNode(node); + let type = getTypeFromTypeReferenceNode(node); if (type !== unknownType && node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved - var len = node.typeArguments.length; - for (var i = 0; i < len; i++) { + let len = node.typeArguments.length; + for (let i = 0; i < len; i++) { checkSourceElement(node.typeArguments[i]); - var constraint = getConstraintOfTypeParameter((type).target.typeParameters[i]); + let constraint = getConstraintOfTypeParameter((type).target.typeParameters[i]); if (produceDiagnostics && constraint) { - var typeArgument = (type).typeArguments[i]; + let typeArgument = (type).typeArguments[i]; checkTypeAssignableTo(typeArgument, constraint, node, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } @@ -8032,7 +8034,7 @@ module ts { function checkTypeLiteral(node: TypeLiteralNode) { forEach(node.members, checkSourceElement); if (produceDiagnostics) { - var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + let type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); } @@ -8044,7 +8046,7 @@ module ts { function checkTupleType(node: TupleTypeNode) { // Grammar checking - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + let hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { grammarErrorOnNode(node, Diagnostics.A_tuple_type_element_list_cannot_be_empty); } @@ -8064,7 +8066,7 @@ module ts { if (!produceDiagnostics) { return; } - var signature = getSignatureFromDeclaration(signatureDeclarationNode); + let signature = getSignatureFromDeclaration(signatureDeclarationNode); if (!signature.hasStringLiterals) { return; } @@ -8079,14 +8081,14 @@ module ts { // TypeScript 1.0 spec (April 2014): 3.7.2.4 // Every specialized call or construct signature in an object type must be assignable // to at least one non-specialized call or construct signature in the same object type - var signaturesToCheck: Signature[]; + let signaturesToCheck: Signature[]; // Unnamed (call\construct) signatures in interfaces are inherited and not shadowed so examining just node symbol won't give complete answer. // 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); - var signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; - var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - var containingType = getDeclaredTypeOfSymbol(containingSymbol); + let signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; + let containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); + let containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); } else { @@ -8103,7 +8105,7 @@ module ts { } function getEffectiveDeclarationFlags(n: Node, flagsToCheck: NodeFlags) { - var flags = getCombinedNodeFlags(n); + let flags = getCombinedNodeFlags(n); if (n.parent.kind !== SyntaxKind.InterfaceDeclaration && isInAmbientContext(n)) { if (!(flags & NodeFlags.Ambient)) { // It is nested in an ambient context, which means it is automatically exported @@ -8126,19 +8128,19 @@ module 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 - var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + let 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 - var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + let someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + let canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); forEach(overloads, o => { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; + let deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; if (deviation & NodeFlags.Export) { error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } @@ -8154,9 +8156,9 @@ module ts { function checkQuestionTokenAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, someHaveQuestionToken: boolean, allHaveQuestionToken: boolean): void { if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); + let canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); forEach(overloads, o => { - var deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; + let deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { error(o.name, Diagnostics.Overload_signatures_must_all_be_optional_or_required); } @@ -8164,26 +8166,26 @@ module ts { } } - var flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected; - var someNodeFlags: NodeFlags = 0; - var allNodeFlags = flagsToCheck; - var someHaveQuestionToken = false; - var allHaveQuestionToken = true; - var hasOverloads = false; - var bodyDeclaration: FunctionLikeDeclaration; - var lastSeenNonAmbientDeclaration: FunctionLikeDeclaration; - var previousDeclaration: FunctionLikeDeclaration; + let flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected; + let someNodeFlags: NodeFlags = 0; + let allNodeFlags = flagsToCheck; + let someHaveQuestionToken = false; + let allHaveQuestionToken = true; + let hasOverloads = false; + let bodyDeclaration: FunctionLikeDeclaration; + let lastSeenNonAmbientDeclaration: FunctionLikeDeclaration; + let previousDeclaration: FunctionLikeDeclaration; - var declarations = symbol.declarations; - var isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0; + let declarations = symbol.declarations; + let isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0; function reportImplementationExpectedError(node: FunctionLikeDeclaration): void { if (node.name && getFullWidth(node.name) === 0) { return; } - var seen = false; - var subsequentNode = forEachChild(node.parent, c => { + let seen = false; + let subsequentNode = forEachChild(node.parent, c => { if (seen) { return c; } @@ -8193,13 +8195,13 @@ module ts { }); if (subsequentNode) { if (subsequentNode.kind === node.kind) { - var errorNode: Node = (subsequentNode).name || subsequentNode; + let 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)); - var diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; + let diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; error(errorNode, diagnostic); return; } @@ -8209,7 +8211,7 @@ module ts { } } } - var errorNode: Node = node.name || node; + let errorNode: Node = node.name || node; if (isConstructor) { error(errorNode, Diagnostics.Constructor_implementation_is_missing); } @@ -8220,13 +8222,13 @@ module ts { // when checking exported function declarations across modules check only duplicate implementations // names and consistency of modifiers are verified when we check local symbol - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; - var duplicateFunctionDeclaration = false; - var multipleConstructorImplementation = false; + let isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; + let duplicateFunctionDeclaration = false; + let multipleConstructorImplementation = false; for (let current of declarations) { - var node = current; - var inAmbientContext = isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext; + let node = current; + let inAmbientContext = isInAmbientContext(node); + let 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 @@ -8239,7 +8241,7 @@ module ts { } if (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.Constructor) { - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + let currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); @@ -8295,8 +8297,8 @@ module ts { checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); if (bodyDeclaration) { - var signatures = getSignaturesOfSymbol(symbol); - var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + let signatures = getSignaturesOfSymbol(symbol); + let bodySignature = getSignatureFromDeclaration(bodyDeclaration); // If the implementation signature has string literals, we will have reported an error in // checkSpecializedSignatureDeclaration if (!bodySignature.hasStringLiterals) { @@ -8354,10 +8356,10 @@ module ts { // we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace // to denote disjoint declarationSpaces (without making new enum type). - var exportedDeclarationSpaces: SymbolFlags = 0; - var nonExportedDeclarationSpaces: SymbolFlags = 0; + let exportedDeclarationSpaces: SymbolFlags = 0; + let nonExportedDeclarationSpaces: SymbolFlags = 0; forEach(symbol.declarations, d => { - var declarationSpaces = getDeclarationSpaces(d); + let declarationSpaces = getDeclarationSpaces(d); if (getEffectiveDeclarationFlags(d, NodeFlags.Export)) { exportedDeclarationSpaces |= declarationSpaces; } @@ -8366,7 +8368,7 @@ module ts { } }); - var commonDeclarationSpace = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + let commonDeclarationSpace = exportedDeclarationSpaces & nonExportedDeclarationSpaces; if (commonDeclarationSpace) { // declaration spaces for exported and non-exported declarations intersect @@ -8389,8 +8391,8 @@ module ts { case SyntaxKind.EnumDeclaration: return SymbolFlags.ExportType | SymbolFlags.ExportValue; case SyntaxKind.ImportEqualsDeclaration: - var result: SymbolFlags = 0; - var target = resolveAlias(getSymbolOfNode(d)); + let result: SymbolFlags = 0; + let target = resolveAlias(getSymbolOfNode(d)); forEach(target.declarations, d => { result |= getDeclarationSpaces(d); }); return result; default: @@ -8428,10 +8430,10 @@ module 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 - var symbol = getSymbolOfNode(node); - var localSymbol = node.localSymbol || symbol; + let symbol = getSymbolOfNode(node); + let localSymbol = node.localSymbol || symbol; - var firstDeclaration = getDeclarationOfKind(localSymbol, node.kind); + let firstDeclaration = getDeclarationOfKind(localSymbol, node.kind); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -8503,7 +8505,7 @@ module ts { return false; } - var root = getRootDeclaration(node); + let root = getRootDeclaration(node); if (root.kind === SyntaxKind.Parameter && nodeIsMissing((root.parent).body)) { // just an overload - no codegen impact return false; @@ -8520,10 +8522,10 @@ module ts { // this function will run after checking the source file so 'CaptureThis' is correct for all nodes function checkIfThisIsCapturedInEnclosingScope(node: Node): void { - var current = node; + let current = node; while (current) { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { - var isDeclaration = node.kind !== SyntaxKind.Identifier; + let isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { error((node).name, Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -8542,14 +8544,14 @@ module ts { } // bubble up and find containing type - var enclosingClass = getAncestor(node, SyntaxKind.ClassDeclaration); + let enclosingClass = getAncestor(node, SyntaxKind.ClassDeclaration); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || isInAmbientContext(enclosingClass)) { return; } if (getClassBaseTypeNode(enclosingClass)) { - var isDeclaration = node.kind !== SyntaxKind.Identifier; + let isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { error(node, Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -8570,7 +8572,7 @@ module ts { } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - var parent = getDeclarationContainer(node); + let 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_an_external_module, @@ -8593,33 +8595,33 @@ module 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 var declarations will not + // Only consider declarations with initializers, uninitialized let declarations will not // step on a let/const variable. // Do not consider let and const declarations, as duplicate block-scoped declarations // are handled by the binder. - // We are only looking for var declarations that step on let\const declarations from a + // We are only looking for let 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 - // var x = 0; // symbol for this declaration will be 'symbol' + // let x = 0; // symbol for this declaration will be 'symbol' // } if (node.initializer && (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0) { - var symbol = getSymbolOfNode(node); + let symbol = getSymbolOfNode(node); if (symbol.flags & SymbolFlags.FunctionScopedVariable) { - var localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + let 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) { - var varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); - var container = + let varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); + let container = varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent; // 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) - var namesShareScope = + let namesShareScope = container && (container.kind === SyntaxKind.Block && isFunctionLike(container.parent) || (container.kind === SyntaxKind.ModuleBlock && container.kind === SyntaxKind.ModuleDeclaration) || @@ -8630,7 +8632,7 @@ module 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) { - var name = symbolToString(localDeclarationSymbol); + let name = symbolToString(localDeclarationSymbol); error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); } } @@ -8654,7 +8656,7 @@ module ts { } function visit(n: Node) { if (n.kind === SyntaxKind.Identifier) { - var referencedSymbol = getNodeLinks(n).resolvedSymbol; + let 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) { @@ -8708,8 +8710,8 @@ module ts { } return; } - var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + let symbol = getSymbolOfNode(node); + let type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer if (node.initializer) { @@ -8720,7 +8722,7 @@ module ts { else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + let 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)); } @@ -8841,8 +8843,8 @@ module ts { checkForInOrForOfVariableDeclaration(node); } else { - var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression); + let varExpr = node.initializer; + let iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { @@ -8852,7 +8854,7 @@ module ts { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { - var leftType = checkExpression(varExpr); + let 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); @@ -8875,11 +8877,11 @@ module ts { // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form - // for (var VarDecl in Expr) Statement + // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - var variable = (node.initializer).declarations[0]; + let 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); } @@ -8891,8 +8893,8 @@ module 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. - var varExpr = node.initializer; - var leftType = checkExpression(varExpr); + let varExpr = node.initializer; + let 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); } @@ -8905,7 +8907,7 @@ module ts { } } - var rightType = checkExpression(node.expression); + let 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 (!allConstituentTypesHaveKind(rightType, TypeFlags.Any | TypeFlags.ObjectType | TypeFlags.TypeParameter)) { @@ -8916,16 +8918,16 @@ module ts { } function checkForInOrForOfVariableDeclaration(iterationStatement: ForInStatement | ForOfStatement): void { - var variableDeclarationList = iterationStatement.initializer; + let variableDeclarationList = iterationStatement.initializer; // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; + let decl = variableDeclarationList.declarations[0]; checkVariableDeclaration(decl); } } function checkRightHandSideOfForOf(rhsExpression: Expression): Type { - var expressionType = getTypeOfExpression(rhsExpression); + let expressionType = getTypeOfExpression(rhsExpression); return languageVersion >= ScriptTarget.ES6 ? checkIteratedType(expressionType, rhsExpression) : checkElementTypeOfArrayOrString(expressionType, rhsExpression); @@ -8936,11 +8938,11 @@ module ts { */ function checkIteratedType(iterable: Type, expressionForError: Expression): Type { Debug.assert(languageVersion >= ScriptTarget.ES6); - var iteratedType = getIteratedType(iterable, expressionForError); + let iteratedType = getIteratedType(iterable, expressionForError); // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. if (expressionForError && iteratedType) { - var completeIterableType = globalIterableType !== emptyObjectType + let completeIterableType = globalIterableType !== emptyObjectType ? createTypeReference(globalIterableType, [iteratedType]) : emptyObjectType; checkTypeAssignableTo(iterable, completeIterableType, expressionForError); @@ -8979,12 +8981,12 @@ module ts { return undefined; } - var iteratorFunction = getTypeOfPropertyOfType(iterable, getPropertyNameForKnownSymbolName("iterator")); + let iteratorFunction = getTypeOfPropertyOfType(iterable, getPropertyNameForKnownSymbolName("iterator")); if (iteratorFunction && allConstituentTypesHaveKind(iteratorFunction, TypeFlags.Any)) { return undefined; } - var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; + let iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; if (iteratorFunctionSignatures.length === 0) { if (expressionForError) { error(expressionForError, Diagnostics.The_right_hand_side_of_a_for_of_statement_must_have_a_Symbol_iterator_method_that_returns_an_iterator); @@ -8992,17 +8994,17 @@ module ts { return undefined; } - var iterator = getUnionType(map(iteratorFunctionSignatures, getReturnTypeOfSignature)); + let iterator = getUnionType(map(iteratorFunctionSignatures, getReturnTypeOfSignature)); if (allConstituentTypesHaveKind(iterator, TypeFlags.Any)) { return undefined; } - var iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); + let iteratorNextFunction = getTypeOfPropertyOfType(iterator, "next"); if (iteratorNextFunction && allConstituentTypesHaveKind(iteratorNextFunction, TypeFlags.Any)) { return undefined; } - var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; + let iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; if (iteratorNextFunctionSignatures.length === 0) { if (expressionForError) { error(expressionForError, Diagnostics.The_iterator_returned_by_the_right_hand_side_of_a_for_of_statement_must_have_a_next_method); @@ -9010,12 +9012,12 @@ module ts { return undefined; } - var iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + let iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (allConstituentTypesHaveKind(iteratorNextResult, TypeFlags.Any)) { return undefined; } - var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + let iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); if (!iteratorNextValue) { if (expressionForError) { error(expressionForError, Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); @@ -9049,10 +9051,10 @@ module 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. - var arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); - var hasStringConstituent = arrayOrStringType !== arrayType; + let arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + let hasStringConstituent = arrayOrStringType !== arrayType; - var reportedError = false; + let reportedError = false; if (hasStringConstituent) { if (languageVersion < ScriptTarget.ES5) { error(expressionForError, Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); @@ -9072,7 +9074,7 @@ module 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. - var diagnostic = hasStringConstituent + let diagnostic = hasStringConstituent ? Diagnostics.Type_0_is_not_an_array_type : Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(expressionForError, diagnostic, typeToString(arrayType)); @@ -9080,7 +9082,7 @@ module ts { return hasStringConstituent ? stringType : unknownType; } - var arrayElementType = getIndexTypeOfType(arrayType, IndexKind.Number) || unknownType; + let 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) { @@ -9107,17 +9109,17 @@ module ts { function checkReturnStatement(node: ReturnStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = getContainingFunction(node); + let functionBlock = getContainingFunction(node); if (!functionBlock) { grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); } } if (node.expression) { - var func = getContainingFunction(node); + let func = getContainingFunction(node); if (func) { - var returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - var exprType = checkExpressionCached(node.expression); + let returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + let exprType = checkExpressionCached(node.expression); if (func.kind === SyntaxKind.SetAccessor) { error(node.expression, Diagnostics.Setters_cannot_return_a_value); } @@ -9151,10 +9153,10 @@ module ts { // Grammar checking checkGrammarStatementInAmbientContext(node); - var firstDefaultClause: CaseOrDefaultClause; - var hasDuplicateDefaultClause = false; + let firstDefaultClause: CaseOrDefaultClause; + let hasDuplicateDefaultClause = false; - var expressionType = checkExpression(node.expression); + let 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) { @@ -9162,19 +9164,19 @@ module ts { firstDefaultClause = clause; } else { - var sourceFile = getSourceFileOfNode(node); - var start = skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + let sourceFile = getSourceFileOfNode(node); + let start = skipTrivia(sourceFile.text, clause.pos); + let 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) { - var caseClause = clause; + let 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. - var caseType = checkExpression(caseClause.expression); + let 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); @@ -9187,13 +9189,13 @@ module ts { function checkLabeledStatement(node: LabeledStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - var current = node.parent; + let current = node.parent; while (current) { if (isFunctionLike(current)) { break; } if (current.kind === SyntaxKind.LabeledStatement && (current).label.text === node.label.text) { - var sourceFile = getSourceFileOfNode(node); + let sourceFile = getSourceFileOfNode(node); grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; } @@ -9223,7 +9225,7 @@ module ts { checkGrammarStatementInAmbientContext(node); checkBlock(node.tryBlock); - var catchClause = node.catchClause; + let catchClause = node.catchClause; if (catchClause) { // Grammar checking if (catchClause.variableDeclaration) { @@ -9237,10 +9239,10 @@ module ts { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - var identifierName = (catchClause.variableDeclaration.name).text; - var locals = catchClause.block.locals; + let identifierName = (catchClause.variableDeclaration.name).text; + let locals = catchClause.block.locals; if (locals && hasProperty(locals, identifierName)) { - var localSymbol = locals[identifierName] + let localSymbol = locals[identifierName] if (localSymbol && (localSymbol.flags & SymbolFlags.BlockScopedVariable) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } @@ -9261,27 +9263,27 @@ module ts { } function checkIndexConstraints(type: Type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); + let declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); + let declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); - var stringIndexType = getIndexTypeOfType(type, IndexKind.String); - var numberIndexType = getIndexTypeOfType(type, IndexKind.Number); + let stringIndexType = getIndexTypeOfType(type, IndexKind.String); + let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType || numberIndexType) { forEach(getPropertiesOfObjectType(type), prop => { - var propType = getTypeOfSymbol(prop); + let propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); }); if (type.flags & TypeFlags.Class && type.symbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration) { - var classDeclaration = type.symbol.valueDeclaration; + let classDeclaration = type.symbol.valueDeclaration; for (let 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)) { - var propType = getTypeOfSymbol(member.symbol); + let propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); } @@ -9289,12 +9291,12 @@ module ts { } } - var errorNode: Node; + let errorNode: Node; if (stringIndexType && numberIndexType) { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (type.flags & TypeFlags.Interface)) { - var someBaseTypeHasBothIndexers = forEach((type).baseTypes, base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); + let someBaseTypeHasBothIndexers = forEach((type).baseTypes, base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } @@ -9323,7 +9325,7 @@ module ts { // perform property check if property or indexer is declared in 'type' // this allows to rule out cases when both property and indexer are inherited from the base class - var errorNode: Node; + let errorNode: Node; if (prop.valueDeclaration.name.kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } @@ -9334,12 +9336,12 @@ module 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 - var someBaseClassHasBothPropertyAndIndexer = forEach((containingType).baseTypes, base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); + let someBaseClassHasBothPropertyAndIndexer = forEach((containingType).baseTypes, base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = + let 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; @@ -9366,7 +9368,7 @@ module ts { function checkTypeParameters(typeParameterDeclarations: TypeParameterDeclaration[]) { if (typeParameterDeclarations) { for (let i = 0, n = typeParameterDeclarations.length; i < n; i++) { - var node = typeParameterDeclarations[i]; + let node = typeParameterDeclarations[i]; checkTypeParameter(node); if (produceDiagnostics) { @@ -9391,19 +9393,19 @@ module ts { } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var type = getDeclaredTypeOfSymbol(symbol); - var staticType = getTypeOfSymbol(symbol); - var baseTypeNode = getClassBaseTypeNode(node); + let symbol = getSymbolOfNode(node); + let type = getDeclaredTypeOfSymbol(symbol); + let staticType = getTypeOfSymbol(symbol); + let baseTypeNode = getClassBaseTypeNode(node); if (baseTypeNode) { emitExtends = emitExtends || !isInAmbientContext(node); checkTypeReference(baseTypeNode); } if (type.baseTypes.length) { if (produceDiagnostics) { - var baseType = type.baseTypes[0]; + let baseType = type.baseTypes[0]; checkTypeAssignableTo(type, baseType, node.name || node, Diagnostics.Class_0_incorrectly_extends_base_class_1); - var staticBaseType = getTypeOfSymbol(baseType.symbol); + let staticBaseType = getTypeOfSymbol(baseType.symbol); checkTypeAssignableTo(staticType, getTypeWithoutConstructors(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseType.symbol !== resolveEntityName(baseTypeNode.typeName, SymbolFlags.Value)) { @@ -9417,14 +9419,14 @@ module ts { checkExpressionOrQualifiedName(baseTypeNode.typeName); } - var implementedTypeNodes = getClassImplementedTypeNodes(node); + let implementedTypeNodes = getClassImplementedTypeNodes(node); if (implementedTypeNodes) { forEach(implementedTypeNodes, typeRefNode => { checkTypeReference(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeReferenceNode(typeRefNode); + let t = getTypeFromTypeReferenceNode(typeRefNode); if (t !== unknownType) { - var declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; + let declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; if (declaredType.flags & (TypeFlags.Class | TypeFlags.Interface)) { checkTypeAssignableTo(type, t, node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1); } @@ -9466,18 +9468,18 @@ module ts { // derived class instance member variables and accessors, but not by other kinds of members. // NOTE: assignability is checked in checkClassDeclaration - var baseProperties = getPropertiesOfObjectType(baseType); + let baseProperties = getPropertiesOfObjectType(baseType); for (let baseProperty of baseProperties) { - var base = getTargetSymbol(baseProperty); + let base = getTargetSymbol(baseProperty); if (base.flags & SymbolFlags.Prototype) { continue; } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); + let derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); if (derived) { - var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); - var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + let baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + let derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); if ((baseDeclarationFlags & NodeFlags.Private) || (derivedDeclarationFlags & NodeFlags.Private)) { // either base or derived property is private - not override, skip it continue; @@ -9493,7 +9495,7 @@ module ts { continue; } - var errorMessage: DiagnosticMessage; + let errorMessage: DiagnosticMessage; if (base.flags & SymbolFlags.Method) { if (derived.flags & SymbolFlags.Accessor) { errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; @@ -9532,9 +9534,9 @@ module ts { // TypeScript 1.0 spec (April 2014): // 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 (var i = 0, len = list1.length; i < len; i++) { - var tp1 = list1[i]; - var tp2 = list2[i]; + for (let i = 0, len = list1.length; i < len; i++) { + let tp1 = list1[i]; + let tp2 = list2[i]; if (tp1.name.text !== tp2.name.text) { return false; } @@ -9556,26 +9558,26 @@ module ts { return true; } - var seen: Map<{ prop: Symbol; containingType: Type }> = {}; + let seen: Map<{ prop: Symbol; containingType: Type }> = {}; forEach(type.declaredProperties, p => { seen[p.name] = { prop: p, containingType: type }; }); - var ok = true; + let ok = true; for (let base of type.baseTypes) { - var properties = getPropertiesOfObjectType(base); + let properties = getPropertiesOfObjectType(base); for (let prop of properties) { if (!hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { - var existing = seen[prop.name]; - var isInheritedProperty = existing.containingType !== type; + let existing = seen[prop.name]; + let isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; - var typeName1 = typeToString(existing.containingType); - var typeName2 = typeToString(base); + let typeName1 = typeToString(existing.containingType); + let typeName2 = typeToString(base); - var errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + 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); diagnostics.add(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); } @@ -9595,8 +9597,8 @@ module ts { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + let symbol = getSymbolOfNode(node); + let 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); @@ -9605,7 +9607,7 @@ module ts { // Only check this symbol once if (node === firstInterfaceDecl) { - var type = getDeclaredTypeOfSymbol(symbol); + let type = getDeclaredTypeOfSymbol(symbol); // run subsequent checks only if first set succeeded if (checkInheritedPropertiesAreIdentical(type, node.name)) { forEach(type.baseTypes, baseType => { @@ -9632,20 +9634,20 @@ module ts { } function computeEnumMemberValues(node: EnumDeclaration) { - var nodeLinks = getNodeLinks(node); + let nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & NodeCheckFlags.EnumValuesComputed)) { - var enumSymbol = getSymbolOfNode(node); - var enumType = getDeclaredTypeOfSymbol(enumSymbol); - var autoValue = 0; - var ambient = isInAmbientContext(node); - var enumIsConst = isConst(node); + let enumSymbol = getSymbolOfNode(node); + let enumType = getDeclaredTypeOfSymbol(enumSymbol); + let autoValue = 0; + let ambient = isInAmbientContext(node); + let enumIsConst = isConst(node); forEach(node.members, member => { if (member.name.kind !== SyntaxKind.ComputedPropertyName && isNumericLiteralName((member.name).text)) { error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); } - var initializer = member.initializer; + let initializer = member.initializer; if (initializer) { autoValue = getConstantValueForEnumMemberInitializer(initializer, enumIsConst); if (autoValue === undefined) { @@ -9657,7 +9659,7 @@ module ts { // If it is a constant value (not undefined), it is syntactically constrained to be a number. // Also, we do not need to check this for ambients because there is already // a syntax error if it is not a constant. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); + checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); } } else if (enumIsConst) { @@ -9688,7 +9690,7 @@ module ts { function evalConstant(e: Node): number { switch (e.kind) { case SyntaxKind.PrefixUnaryExpression: - var value = evalConstant((e).operand); + let value = evalConstant((e).operand); if (value === undefined) { return undefined; } @@ -9703,11 +9705,11 @@ module ts { return undefined; } - var left = evalConstant((e).left); + let left = evalConstant((e).left); if (left === undefined) { return undefined; } - var right = evalConstant((e).right); + let right = evalConstant((e).right); if (right === undefined) { return undefined; } @@ -9736,10 +9738,10 @@ module ts { return undefined; } - var member = initializer.parent; - var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); - var enumType: Type; - var propertyName: string; + let member = initializer.parent; + let currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); + let enumType: Type; + let propertyName: string; if (e.kind === SyntaxKind.Identifier) { // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. @@ -9753,11 +9755,11 @@ module ts { (e).argumentExpression.kind !== SyntaxKind.StringLiteral) { return undefined; } - var enumType = getTypeOfNode((e).expression); + enumType = getTypeOfNode((e).expression); propertyName = ((e).argumentExpression).text; } else { - var enumType = getTypeOfNode((e).expression); + enumType = getTypeOfNode((e).expression); propertyName = (e).name.text; } if (enumType !== currentType) { @@ -9768,11 +9770,11 @@ module ts { if (propertyName === undefined) { return undefined; } - var property = getPropertyOfObjectType(enumType, propertyName); + let property = getPropertyOfObjectType(enumType, propertyName); if (!property || !(property.flags & SymbolFlags.EnumMember)) { return undefined; } - var propertyDecl = property.valueDeclaration; + let propertyDecl = property.valueDeclaration; // self references are illegal if (member === propertyDecl) { return undefined; @@ -9809,11 +9811,11 @@ module ts { // for the first member. // // Only perform this check once per symbol - var enumSymbol = getSymbolOfNode(node); - var firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); + let enumSymbol = getSymbolOfNode(node); + let firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { if (enumSymbol.declarations.length > 1) { - var enumIsConst = isConst(node); + let enumIsConst = isConst(node); // check that const is placed\omitted on all enum declarations forEach(enumSymbol.declarations, decl => { if (isConstEnumDeclaration(decl) !== enumIsConst) { @@ -9822,19 +9824,19 @@ module ts { }); } - var seenEnumMissingInitialInitializer = false; + let seenEnumMissingInitialInitializer = false; forEach(enumSymbol.declarations, declaration => { // return true if we hit a violation of the rule, false otherwise if (declaration.kind !== SyntaxKind.EnumDeclaration) { return false; } - var enumDeclaration = declaration; + let enumDeclaration = declaration; if (!enumDeclaration.members.length) { return false; } - var firstEnumMember = enumDeclaration.members[0]; + let 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); @@ -9848,7 +9850,7 @@ module ts { } function getFirstNonAmbientClassOrFunctionDeclaration(symbol: Symbol): Declaration { - var declarations = symbol.declarations; + let declarations = symbol.declarations; for (let declaration of declarations) { if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && !isInAmbientContext(declaration)) { return declaration; @@ -9869,14 +9871,14 @@ module ts { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); + let 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)) { - var classOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + let classOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (classOrFunc) { if (getSourceFileOfNode(node) !== getSourceFileOfNode(classOrFunc)) { error(node.name, Diagnostics.A_module_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); @@ -9908,12 +9910,12 @@ module ts { } function checkExternalImportOrExportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean { - var moduleName = getExternalModuleName(node); + let moduleName = getExternalModuleName(node); if (getFullWidth(moduleName) !== 0 && moduleName.kind !== SyntaxKind.StringLiteral) { error(moduleName, Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + let 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_an_internal_module : @@ -9932,15 +9934,15 @@ module ts { } function checkAliasSymbol(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportSpecifier | ExportSpecifier) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); + let symbol = getSymbolOfNode(node); + let target = resolveAlias(symbol); if (target !== unknownSymbol) { - var excludedMeanings = + let 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) { - var message = node.kind === SyntaxKind.ExportSpecifier ? + let 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)); @@ -9959,7 +9961,7 @@ module ts { grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { - var importClause = node.importClause; + let importClause = node.importClause; if (importClause) { if (importClause.name) { checkImportBinding(importClause); @@ -9984,11 +9986,11 @@ module ts { markExportAsReferenced(node); } if (isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveAlias(getSymbolOfNode(node)); + let 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 - var moduleName = getFirstIdentifier(node.moduleReference); + let 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)); } @@ -10020,7 +10022,7 @@ module ts { } function checkExportAssignment(node: ExportAssignment) { - var container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; + let 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_an_internal_module); return; @@ -10049,16 +10051,16 @@ module ts { } function hasExportedMembers(moduleSymbol: Symbol) { - var declarations = moduleSymbol.declarations; + let declarations = moduleSymbol.declarations; for (let current of declarations) { - var statements = getModuleStatements(current); + let statements = getModuleStatements(current); for (let node of statements) { if (node.kind === SyntaxKind.ExportDeclaration) { - var exportClause = (node).exportClause; + let exportClause = (node).exportClause; if (!exportClause) { return true; } - var specifiers = exportClause.elements; + let specifiers = exportClause.elements; for (let specifier of specifiers) { if (!(specifier.propertyName && specifier.name && specifier.name.text === "default")) { return true; @@ -10073,13 +10075,13 @@ module ts { } function checkExternalModuleExports(node: SourceFile | ModuleDeclaration) { - var moduleSymbol = getSymbolOfNode(node); - var links = getSymbolLinks(moduleSymbol); + let moduleSymbol = getSymbolOfNode(node); + let links = getSymbolLinks(moduleSymbol); if (!links.exportsChecked) { - var defaultSymbol = getExportAssignmentSymbol(moduleSymbol); + let defaultSymbol = getExportAssignmentSymbol(moduleSymbol); if (defaultSymbol) { if (hasExportedMembers(moduleSymbol)) { - var declaration = getDeclarationOfAliasSymbol(defaultSymbol) || defaultSymbol.valueDeclaration; + let declaration = getDeclarationOfAliasSymbol(defaultSymbol) || defaultSymbol.valueDeclaration; error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -10195,8 +10197,8 @@ module ts { // Function expression bodies are checked after all statements in the enclosing body. This is to ensure // constructs like the following are permitted: - // var foo = function () { - // var s = foo(); + // let foo = function () { + // let s = foo(); // return "hello"; // } // Here, performing a full type check of the body of the function expression whilst in the process of @@ -10285,14 +10287,14 @@ module ts { } function checkSourceFile(node: SourceFile) { - var start = new Date().getTime(); + let start = new Date().getTime(); checkSourceFileWorker(node); checkTime += new Date().getTime() - start; } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node: SourceFile) { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!(links.flags & NodeCheckFlags.TypeChecked)) { // Grammar checking checkGrammarSourceFile(node); @@ -10357,11 +10359,11 @@ module ts { } function getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[] { - var symbols: SymbolTable = {}; - var memberFlags: NodeFlags = 0; + let symbols: SymbolTable = {}; + let memberFlags: NodeFlags = 0; function copySymbol(symbol: Symbol, meaning: SymbolFlags) { if (symbol.flags & meaning) { - var id = symbol.name; + let id = symbol.name; if (!isReservedMemberName(id) && !hasProperty(symbols, id)) { symbols[id] = symbol; } @@ -10369,7 +10371,7 @@ module ts { } function copySymbols(source: SymbolTable, meaning: SymbolFlags) { if (meaning) { - for (var id in source) { + for (let id in source) { if (hasProperty(source, id)) { copySymbol(source[id], meaning); } @@ -10433,7 +10435,7 @@ module ts { // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(entityName: EntityName): boolean { - var node: Node = entityName; + let node: Node = entityName; while (node.parent && node.parent.kind === SyntaxKind.QualifiedName) node = node.parent; return node.parent && node.parent.kind === SyntaxKind.TypeReference; } @@ -10468,13 +10470,13 @@ module ts { // At this point, node is either a qualified name or an identifier Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName, "'node' was expected to be a qualified name or identifier in 'isTypeNode'."); - var parent = node.parent; + let parent = node.parent; if (parent.kind === SyntaxKind.TypeQuery) { return false; } // Do not recursively call isTypeNode on the parent. In the example: // - // var a: A.B.C; + // let a: A.B.C; // // Calling isTypeNode would consider the qualified name A.B a type node. Only C or // A.B.C is a type node. @@ -10571,18 +10573,18 @@ module 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. - var meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; + let meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; return resolveEntityName(entityName, meaning); } else if (entityName.kind === SyntaxKind.PropertyAccessExpression) { - var symbol = getNodeLinks(entityName).resolvedSymbol; + let symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } else if (entityName.kind === SyntaxKind.QualifiedName) { - var symbol = getNodeLinks(entityName).resolvedSymbol; + let symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); } @@ -10590,7 +10592,7 @@ module ts { } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; + let meaning = entityName.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead // return the alias symbol. meaning |= SymbolFlags.Alias; @@ -10626,12 +10628,12 @@ module ts { case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: - var type = checkExpression(node); + let type = checkExpression(node); return type.symbol; case SyntaxKind.ConstructorKeyword: // constructor keyword for an overload, should take us to the definition if it exist - var constructorDeclaration = node.parent; + let constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === SyntaxKind.Constructor) { return (constructorDeclaration.parent).symbol; } @@ -10639,7 +10641,7 @@ module ts { case SyntaxKind.StringLiteral: // External module name in an import declaration - var moduleName: Expression; + let moduleName: Expression; if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && @@ -10651,9 +10653,9 @@ module ts { case SyntaxKind.NumericLiteral: // index access if (node.parent.kind == SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { - var objectType = checkExpression((node.parent).expression); + let objectType = checkExpression((node.parent).expression); if (objectType === unknownType) return undefined; - var apparentType = getApparentType(objectType); + let apparentType = getApparentType(objectType); if (apparentType === unknownType) return undefined; return getPropertyOfType(apparentType, (node).text); } @@ -10688,29 +10690,29 @@ module ts { if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration - var symbol = getSymbolOfNode(node); + let symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); } if (isTypeDeclarationName(node)) { - var symbol = getSymbolInfo(node); + let symbol = getSymbolInfo(node); return symbol && getDeclaredTypeOfSymbol(symbol); } if (isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration - var symbol = getSymbolOfNode(node); + let symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } if (isDeclarationName(node)) { - var symbol = getSymbolInfo(node); + let symbol = getSymbolInfo(node); return symbol && getTypeOfSymbol(symbol); } if (isInRightSideOfImportOrExportAssignment(node)) { - var symbol = getSymbolInfo(node); - var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + let symbol = getSymbolInfo(node); + let declaredType = symbol && getDeclaredTypeOfSymbol(symbol); return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); } @@ -10728,7 +10730,7 @@ module ts { // if the type has call or construct signatures function getAugmentedPropertiesOfType(type: Type): Symbol[] { var type = getApparentType(type); - var propsByName = createSymbolTable(getPropertiesOfType(type)); + let propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, SignatureKind.Call).length || getSignaturesOfType(type, SignatureKind.Construct).length) { forEach(getPropertiesOfType(globalFunctionType), p => { if (!hasProperty(propsByName, p.name)) { @@ -10741,15 +10743,15 @@ module ts { function getRootSymbols(symbol: Symbol): Symbol[] { if (symbol.flags & SymbolFlags.UnionProperty) { - var symbols: Symbol[] = []; - var name = symbol.name; + let symbols: Symbol[] = []; + let name = symbol.name; forEach(getSymbolLinks(symbol).unionType.types, t => { symbols.push(getPropertyOfType(t, name)); }); return symbols; } else if (symbol.flags & SymbolFlags.Transient) { - var target = getSymbolLinks(symbol).target; + let target = getSymbolLinks(symbol).target; if (target) { return [target]; } @@ -10772,7 +10774,7 @@ module ts { } function isUniqueLocalName(name: string, container: Node): boolean { - for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { + for (let node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { if (node.locals && hasProperty(node.locals, name)) { // We conservatively include alias symbols to cover cases where they're emitted as locals if (node.locals[name].flags & (SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias)) { @@ -10784,8 +10786,8 @@ module ts { } function getGeneratedNamesForSourceFile(sourceFile: SourceFile): Map { - var links = getNodeLinks(sourceFile); - var generatedNames = links.generatedNames; + let links = getNodeLinks(sourceFile); + let generatedNames = links.generatedNames; if (!generatedNames) { generatedNames = links.generatedNames = {}; generateNames(sourceFile); @@ -10826,7 +10828,7 @@ module ts { } function makeUniqueName(baseName: string): string { - var name = generateUniqueName(baseName, isExistingName); + let name = generateUniqueName(baseName, isExistingName); return generatedNames[name] = name; } @@ -10842,15 +10844,15 @@ module ts { function generateNameForModuleOrEnum(node: ModuleDeclaration | EnumDeclaration) { if (node.name.kind === SyntaxKind.Identifier) { - var name = node.name.text; + let name = node.name.text; // Use module/enum name itself if it is unique, otherwise make a unique variation assignGeneratedName(node, isUniqueLocalName(name, node) ? name : makeUniqueName(name)); } } function generateNameForImportOrExportDeclaration(node: ImportDeclaration | ExportDeclaration) { - var expr = getExternalModuleName(node); - var baseName = expr.kind === SyntaxKind.StringLiteral ? + let expr = getExternalModuleName(node); + let baseName = expr.kind === SyntaxKind.StringLiteral ? escapeIdentifier(makeIdentifierFromModuleName((expr).text)) : "module"; assignGeneratedName(node, makeUniqueName(baseName)); } @@ -10875,7 +10877,7 @@ module ts { } function getGeneratedNameForNode(node: Node) { - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.generatedName) { getGeneratedNamesForSourceFile(getSourceFile(node)); } @@ -10891,10 +10893,10 @@ module ts { } function getAliasNameSubstitution(symbol: Symbol): string { - var declaration = getDeclarationOfAliasSymbol(symbol); + let declaration = getDeclarationOfAliasSymbol(symbol); if (declaration && declaration.kind === SyntaxKind.ImportSpecifier) { - var moduleName = getGeneratedNameForNode(declaration.parent.parent.parent); - var propertyName = (declaration).propertyName || (declaration).name; + let moduleName = getGeneratedNameForNode(declaration.parent.parent.parent); + let propertyName = (declaration).propertyName || (declaration).name; return moduleName + "." + unescapeIdentifier(propertyName.text); } } @@ -10903,8 +10905,8 @@ module ts { if (isExternalModuleSymbol(symbol.parent)) { return "exports." + unescapeIdentifier(symbol.name); } - var node = location; - var containerSymbol = getParentOfSymbol(symbol); + let node = location; + let containerSymbol = getParentOfSymbol(symbol); while (node) { if ((node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.EnumDeclaration) && getSymbolOfNode(node) === containerSymbol) { return getGeneratedNameForNode(node) + "." + unescapeIdentifier(symbol.name); @@ -10914,7 +10916,7 @@ module ts { } function getExpressionNameSubstitution(node: Identifier): string { - var symbol = getNodeLinks(node).resolvedSymbol; + let symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { // Whan an identifier resolves to a parented symbol, it references an exported entity from // another declaration of the same internal module. @@ -10924,7 +10926,7 @@ module 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. - var exportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + let exportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); if (symbol !== exportSymbol && !(exportSymbol.flags & SymbolFlags.ExportHasLocal)) { return getExportNameSubstitution(exportSymbol, node.parent); } @@ -10936,7 +10938,7 @@ module ts { } function hasExportDefaultValue(node: SourceFile): boolean { - var symbol = getResolvedExportAssignmentSymbol(getSymbolOfNode(node)); + let symbol = getResolvedExportAssignmentSymbol(getSymbolOfNode(node)); return symbol && symbol !== unknownSymbol && symbolIsValue(symbol) && !isConstEnumSymbol(symbol); } @@ -10949,7 +10951,7 @@ module ts { } function isAliasResolvedToValue(symbol: Symbol): boolean { - var target = resolveAlias(symbol); + let target = resolveAlias(symbol); // const enums and modules that contain only const enums are not considered values from the emit perespective return target !== unknownSymbol && target.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(target); } @@ -10960,7 +10962,7 @@ module ts { function isReferencedAliasDeclaration(node: Node): boolean { if (isAliasSymbolDeclaration(node)) { - var symbol = getSymbolOfNode(node); + let symbol = getSymbolOfNode(node); if (getSymbolLinks(symbol).referenced) { return true; } @@ -10970,8 +10972,8 @@ module ts { function isImplementationOfOverload(node: FunctionLikeDeclaration) { if (nodeIsPresent(node.body)) { - var symbol = getSymbolOfNode(node); - var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + let symbol = getSymbolOfNode(node); + let 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; @@ -11003,10 +11005,10 @@ module ts { return getEnumMemberValue(node); } - var symbol = getNodeLinks(node).resolvedSymbol; + let symbol = getNodeLinks(node).resolvedSymbol; if (symbol && (symbol.flags & SymbolFlags.EnumMember)) { - var declaration = symbol.valueDeclaration; - var constantValue: number; + let declaration = symbol.valueDeclaration; + let constantValue: number; if (declaration.kind === SyntaxKind.EnumMember) { return getEnumMemberValue(declaration); } @@ -11017,8 +11019,8 @@ module 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 - var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) + let symbol = getSymbolOfNode(declaration); + let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) ? getTypeOfSymbol(symbol) : unknownType; @@ -11026,7 +11028,7 @@ module ts { } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - var signature = getSignatureFromDeclaration(signatureDeclaration); + let signature = getSignatureFromDeclaration(signatureDeclaration); getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } @@ -11052,17 +11054,17 @@ module ts { } // for names in variable declarations and binding elements try to short circuit and fetch symbol from the node - var declarationSymbol: Symbol = + let declarationSymbol: Symbol = (n.parent.kind === SyntaxKind.VariableDeclaration && (n.parent).name === n) || n.parent.kind === SyntaxKind.BindingElement ? getSymbolOfNode(n.parent) : undefined; - var symbol = declarationSymbol || + let symbol = declarationSymbol || getNodeLinks(n).resolvedSymbol || resolveName(n, n.text, SymbolFlags.BlockScopedVariable | SymbolFlags.Alias, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); - var isLetOrConst = + let isLetOrConst = symbol && (symbol.flags & SymbolFlags.BlockScopedVariable) && symbol.valueDeclaration.parent.kind !== SyntaxKind.CatchClause; @@ -11178,14 +11180,14 @@ module ts { return; } - var lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node; - var flags = 0; + let lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node; + let flags = 0; for (let modifier of node.modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: - var text: string; + let text: string; if (modifier.kind === SyntaxKind.PublicKeyword) { text = "public"; } @@ -11283,9 +11285,9 @@ module ts { function checkGrammarForDisallowedTrailingComma(list: NodeArray): boolean { if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - var sourceFile = getSourceFileOfNode(list[0]); + let start = list.end - ",".length; + let end = list.end; + let sourceFile = getSourceFileOfNode(list[0]); return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Trailing_comma_not_allowed); } } @@ -11296,9 +11298,9 @@ module ts { } if (typeParameters && typeParameters.length === 0) { - var start = typeParameters.pos - "<".length; - var sourceFile = getSourceFileOfNode(node); - var end = skipTrivia(sourceFile.text, typeParameters.end) + ">".length; + let start = typeParameters.pos - "<".length; + let sourceFile = getSourceFileOfNode(node); + let end = skipTrivia(sourceFile.text, typeParameters.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Type_parameter_list_cannot_be_empty); } } @@ -11308,11 +11310,11 @@ module ts { return true; } - var seenOptionalParameter = false; - var parameterCount = parameters.length; + let seenOptionalParameter = false; + let parameterCount = parameters.length; - for (var i = 0; i < parameterCount; i++) { - var parameter = parameters[i]; + for (let i = 0; i < parameterCount; i++) { + let 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); @@ -11347,7 +11349,7 @@ module ts { } function checkGrammarIndexSignatureParameters(node: SignatureDeclaration): boolean { - var parameter = node.parameters[0]; + let parameter = node.parameters[0]; if (node.parameters.length !== 1) { if (parameter) { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_must_have_exactly_one_parameter); @@ -11392,9 +11394,9 @@ module ts { function checkGrammarForAtLeastOneTypeArgument(node: Node, typeArguments: NodeArray): boolean { if (typeArguments && typeArguments.length === 0) { - var sourceFile = getSourceFileOfNode(node); - var start = typeArguments.pos - "<".length; - var end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + let sourceFile = getSourceFileOfNode(node); + let start = typeArguments.pos - "<".length; + let end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Type_argument_list_cannot_be_empty); } } @@ -11406,7 +11408,7 @@ module ts { function checkGrammarForOmittedArgument(node: CallExpression, arguments: NodeArray): boolean { if (arguments) { - var sourceFile = getSourceFileOfNode(node); + let sourceFile = getSourceFileOfNode(node); for (let arg of arguments) { if (arg.kind === SyntaxKind.OmittedExpression) { return grammarErrorAtPos(sourceFile, arg.pos, 0, Diagnostics.Argument_expression_expected); @@ -11421,20 +11423,20 @@ module ts { } function checkGrammarHeritageClause(node: HeritageClause): boolean { - var types = node.types; + let types = node.types; if (checkGrammarForDisallowedTrailingComma(types)) { return true; } if (types && types.length === 0) { - var listType = tokenToString(node.token); - var sourceFile = getSourceFileOfNode(node); + let listType = tokenToString(node.token); + let sourceFile = getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType) } } function checkGrammarClassDeclarationHeritageClauses(node: ClassDeclaration) { - var seenExtendsClause = false; - var seenImplementsClause = false; + let seenExtendsClause = false; + let seenImplementsClause = false; if (!checkGrammarModifiers(node) && node.heritageClauses) { for (let heritageClause of node.heritageClauses) { @@ -11469,7 +11471,7 @@ module ts { } function checkGrammarInterfaceDeclaration(node: InterfaceDeclaration) { - var seenExtendsClause = false; + let seenExtendsClause = false; if (node.heritageClauses) { for (let heritageClause of node.heritageClauses) { @@ -11499,7 +11501,7 @@ module ts { return false; } - var computedPropertyName = node; + let 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); } @@ -11523,15 +11525,15 @@ module ts { } function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression) { - var seen: Map = {}; - var Property = 1; - var GetAccessor = 2; - var SetAccesor = 4; - var GetOrSetAccessor = GetAccessor | SetAccesor; - var inStrictMode = (node.parserContextFlags & ParserContextFlags.StrictMode) !== 0; + let seen: Map = {}; + let Property = 1; + let GetAccessor = 2; + let SetAccesor = 4; + let GetOrSetAccessor = GetAccessor | SetAccesor; + let inStrictMode = (node.parserContextFlags & ParserContextFlags.StrictMode) !== 0; for (let prop of node.properties) { - var name = prop.name; + let 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 @@ -11547,7 +11549,7 @@ module 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 - var currentKind: number; + let currentKind: number; if (prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment) { // Grammar checking for computedPropertName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop,(prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); @@ -11573,7 +11575,7 @@ module ts { seen[(name).text] = currentKind; } else { - var existingKind = seen[(name).text]; + let existingKind = seen[(name).text]; if (currentKind === Property && existingKind === Property) { if (inStrictMode) { grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode); @@ -11600,23 +11602,23 @@ module ts { } if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { - var variableList = forInOrOfStatement.initializer; + let variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + let 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); } - var firstDeclaration = variableList.declarations[0]; + let firstDeclaration = variableList.declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + let 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) { - var diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + let 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); @@ -11628,7 +11630,7 @@ module ts { } function checkGrammarAccessor(accessor: MethodDeclaration): boolean { - var kind = accessor.kind; + let kind = accessor.kind; if (languageVersion < ScriptTarget.ES5) { return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } @@ -11652,7 +11654,7 @@ module ts { return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } else { - var parameter = accessor.parameters[0]; + let parameter = accessor.parameters[0]; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter); } @@ -11731,7 +11733,7 @@ module ts { } function checkGrammarBreakOrContinueStatement(node: BreakOrContinueStatement): boolean { - var current: Node = node; + let current: Node = node; while (current) { if (isFunctionLike(current)) { return grammarErrorOnNode(node, Diagnostics.Jump_target_cannot_cross_function_boundary); @@ -11742,7 +11744,7 @@ module 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 - var isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement + let isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement && !isIterationStatement((current).statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { @@ -11770,14 +11772,14 @@ module ts { } if (node.label) { - var message = node.kind === SyntaxKind.BreakStatement + let 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 { - var message = node.kind === SyntaxKind.BreakStatement + let 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) @@ -11786,7 +11788,7 @@ module ts { function checkGrammarBindingElement(node: BindingElement) { if (node.dotDotDotToken) { - var elements = (node.parent).elements; + let elements = (node.parent).elements; if (node !== elements[elements.length - 1]) { return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } @@ -11808,7 +11810,7 @@ module ts { } if (node.initializer) { // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; + let equalsTokenLength = "=".length; return grammarErrorAtPos(getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -11823,7 +11825,7 @@ module ts { } } - var checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); + let checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". @@ -11843,7 +11845,7 @@ module ts { } } else { - var elements = (name).elements; + let elements = (name).elements; for (let element of elements) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -11851,7 +11853,7 @@ module ts { } function checkGrammarVariableDeclarationList(declarationList: VariableDeclarationList): boolean { - var declarations = declarationList.declarations; + let declarations = declarationList.declarations; if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { return true; } @@ -11891,7 +11893,7 @@ module ts { function isIntegerLiteral(expression: Expression): boolean { if (expression.kind === SyntaxKind.PrefixUnaryExpression) { - var unaryExpression = expression; + let unaryExpression = expression; if (unaryExpression.operator === SyntaxKind.PlusToken || unaryExpression.operator === SyntaxKind.MinusToken) { expression = unaryExpression.operand; } @@ -11909,15 +11911,15 @@ module ts { } function checkGrammarEnumDeclaration(enumDecl: EnumDeclaration): boolean { - var enumIsConst = (enumDecl.flags & NodeFlags.Const) !== 0; + let enumIsConst = (enumDecl.flags & NodeFlags.Const) !== 0; - var hasError = false; + let hasError = false; // skip checks below for const enums - they allow arbitrary initializers as long as they can be evaluated to constant expressions. // since all values are known in compile time - it is not necessary to check that constant enum section precedes computed enum members. if (!enumIsConst) { - var inConstantEnumMemberSection = true; - var inAmbientContext = isInAmbientContext(enumDecl); + let inConstantEnumMemberSection = true; + let inAmbientContext = isInAmbientContext(enumDecl); for (let node of enumDecl.members) { // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including @@ -11947,9 +11949,9 @@ module ts { } function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - var sourceFile = getSourceFileOfNode(node); + let sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = getSpanOfTokenAtPosition(sourceFile, node.pos); + let span = getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } @@ -11963,7 +11965,7 @@ module ts { } function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - var sourceFile = getSourceFileOfNode(node); + let sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; @@ -11972,9 +11974,9 @@ module ts { function checkGrammarEvalOrArgumentsInStrictMode(contextNode: Node, name: Node): boolean { if (name && name.kind === SyntaxKind.Identifier) { - var identifier = name; + let identifier = name; if (contextNode && (contextNode.parserContextFlags & ParserContextFlags.StrictMode) && isEvalOrArgumentsIdentifier(identifier)) { - var nameText = declarationNameToString(identifier); + let nameText = declarationNameToString(identifier); return grammarErrorOnNode(identifier, Diagnostics.Invalid_use_of_0_in_strict_mode, nameText); } } @@ -12061,7 +12063,7 @@ module ts { } // Find containing block which is either Block, ModuleBlock, SourceFile - var links = getNodeLinks(node); + let links = getNodeLinks(node); if (!links.hasReportedStatementInAmbientContext && isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts) } @@ -12072,7 +12074,7 @@ module 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) { - var links = getNodeLinks(node.parent); + let 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); @@ -12099,9 +12101,9 @@ module ts { } function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - var sourceFile = getSourceFileOfNode(node); + let sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span = getSpanOfTokenAtPosition(sourceFile, node.pos); + let span = getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add(createFileDiagnostic(sourceFile, textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } From a6348c1e3187d61c3f69a47ab951f13348b434d8 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 12:34:12 -0700 Subject: [PATCH 17/19] Use 'let' in the emitter. --- src/compiler/emitter.ts | 739 ++++++++++++++++++++-------------------- 1 file changed, 371 insertions(+), 368 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index da789b6ffef..661544749e6 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -54,7 +54,7 @@ module ts { referencePathsOutput: string; } - var indentStrings: string[] = ["", " "]; + let indentStrings: string[] = ["", " "]; export function getIndentString(level: number) { if (indentStrings[level] === undefined) { indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; @@ -81,11 +81,11 @@ module ts { } function createTextWriter(newLine: String): EmitTextWriter { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; + let output = ""; + let indent = 0; + let lineStart = true; + let lineCount = 0; + let linePos = 0; function write(s: string) { if (s && s.length) { @@ -109,7 +109,7 @@ module ts { function writeLiteral(s: string) { if (s && s.length) { write(s); - var lineStartsOfS = computeLineStarts(s); + let lineStartsOfS = computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; @@ -160,7 +160,7 @@ module ts { function emitComments(currentSourceFile: SourceFile, writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string, writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void) { - var emitLeadingSpace = !trailingSeparator; + let emitLeadingSpace = !trailingSeparator; forEach(comments, comment => { if (emitLeadingSpace) { writer.write(" "); @@ -182,11 +182,11 @@ module ts { function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string){ if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) { - var firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - var lineCount = getLineStarts(currentSourceFile).length; - var firstCommentLineIndent: number; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - var nextLineStart = (currentLine + 1) === lineCount + let firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos); + let lineCount = getLineStarts(currentSourceFile).length; + let firstCommentLineIndent: number; + for (let pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + let nextLineStart = (currentLine + 1) === lineCount ? currentSourceFile.text.length + 1 : getStartPositionOfLine(currentLine + 1, currentSourceFile); @@ -197,7 +197,7 @@ module ts { } // These are number of spaces writer is going to write at current indent - var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + let currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); // Number of spaces we want to be writing // eg: Assume writer indent @@ -213,10 +213,10 @@ module ts { // More right indented comment */ --4 = 8 - 4 + 11 // class c { } // } - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + let spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); if (spacesToEmit > 0) { - var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); - var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + let 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); @@ -245,8 +245,8 @@ module ts { } function writeTrimmedCurrentLine(pos: number, nextLineStart: number) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ''); + let end = Math.min(comment.end, nextLineStart - 1); + let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ''); if (currentLineText) { // trimmed forward and ending spaces text writer.write(currentLineText); @@ -261,7 +261,7 @@ module ts { } function calculateIndent(pos: number, end: number) { - var currentLineIndent = 0; + let currentLineIndent = 0; for (; pos < end && isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { if (currentSourceFile.text.charCodeAt(pos) === CharacterCodes.tab) { // Tabs = TabSize = indent size and go to next tabStop @@ -286,9 +286,9 @@ module ts { } function getAllAccessorDeclarations(declarations: NodeArray, accessor: AccessorDeclaration) { - var firstAccessor: AccessorDeclaration; - var getAccessor: AccessorDeclaration; - var setAccessor: AccessorDeclaration; + let firstAccessor: AccessorDeclaration; + let getAccessor: AccessorDeclaration; + let setAccessor: AccessorDeclaration; if (hasDynamicName(accessor)) { firstAccessor = accessor; if (accessor.kind === SyntaxKind.GetAccessor) { @@ -305,8 +305,8 @@ module ts { forEach(declarations, (member: Declaration) => { if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) && (member.flags & NodeFlags.Static) === (accessor.flags & NodeFlags.Static)) { - var memberName = getPropertyNameForPropertyNameNode(member.name); - var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + let memberName = getPropertyNameForPropertyNameNode(member.name); + let accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { if (!firstAccessor) { firstAccessor = member; @@ -331,18 +331,19 @@ module ts { } function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string) { - var sourceFilePath = getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); + let sourceFilePath = getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); return combinePaths(newDirPath, sourceFilePath); } function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string){ - var compilerOptions = host.getCompilerOptions(); + let compilerOptions = host.getCompilerOptions(); + let emitOutputFilePathWithoutExtension: string; if (compilerOptions.outDir) { - var emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); } else { - var emitOutputFilePathWithoutExtension = removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = removeFileExtension(sourceFile.fileName); } return emitOutputFilePathWithoutExtension + extension; @@ -355,37 +356,37 @@ module ts { } function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit { - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || ScriptTarget.ES3; + let newLine = host.getNewLine(); + let compilerOptions = host.getCompilerOptions(); + let languageVersion = compilerOptions.target || ScriptTarget.ES3; - var write: (s: string) => void; - var writeLine: () => void; - var increaseIndent: () => void; - var decreaseIndent: () => void; - var writeTextOfNode: (sourceFile: SourceFile, node: Node) => void; + let write: (s: string) => void; + let writeLine: () => void; + let increaseIndent: () => void; + let decreaseIndent: () => void; + let writeTextOfNode: (sourceFile: SourceFile, node: Node) => void; - var writer = createAndSetNewTextWriterWithSymbolWriter(); + let writer = createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration: Node; - var currentSourceFile: SourceFile; - var reportedDeclarationError = false; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + let enclosingDeclaration: Node; + let currentSourceFile: SourceFile; + let reportedDeclarationError = false; + let emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; + let emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var aliasDeclarationEmitInfo: AliasDeclarationEmitInfo[] = []; + let aliasDeclarationEmitInfo: AliasDeclarationEmitInfo[] = []; // Contains the reference paths that needs to go in the declaration file. // Collecting this separately because reference paths need to be first thing in the declaration file // and we could be collecting these paths from multiple files into single one with --out option - var referencePathsOutput = ""; + let referencePathsOutput = ""; if (root) { // Emitting just a single file, so emit references in this file only if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; + let addedGlobalFileReference = false; forEach(root.referencedFiles, fileReference => { - var referencedFile = tryResolveScriptReference(host, root, fileReference); + let 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 @@ -404,13 +405,13 @@ module ts { } else { // Emit references corresponding to this file - var emittedReferencedFiles: SourceFile[] = []; + let emittedReferencedFiles: SourceFile[] = []; forEach(host.getSourceFiles(), sourceFile => { if (!isExternalModuleOrDeclarationFile(sourceFile)) { // Check what references need to be added if (!compilerOptions.noResolve) { forEach(sourceFile.referencedFiles, fileReference => { - var referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); + let referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); // If the reference file is a declaration file or an external module, emit that reference if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && @@ -435,14 +436,14 @@ module ts { } function hasInternalAnnotation(range: CommentRange) { - var text = currentSourceFile.text; - var comment = text.substring(range.pos, range.end); + let text = currentSourceFile.text; + let comment = text.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node: Node) { if (node) { - var leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); + let leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); if (forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -452,7 +453,7 @@ module ts { } function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter { - var writer = createTextWriter(newLine); + let writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.writeKeyword = writer.write; writer.writeOperator = writer.write; @@ -475,9 +476,9 @@ module ts { } function writeAsychronousImportEqualsDeclarations(importEqualsDeclarations: ImportEqualsDeclaration[]) { - var oldWriter = writer; + let oldWriter = writer; forEach(importEqualsDeclarations, aliasToWrite => { - var aliasEmitInfo = forEach(aliasDeclarationEmitInfo, declEmitInfo => declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined); + let aliasEmitInfo = forEach(aliasDeclarationEmitInfo, declEmitInfo => declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined); // If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration // then we don't need to write it at this point. We will write it when we actually see its declaration // Eg. @@ -487,7 +488,7 @@ module ts { // we would write alias foo declaration when we visit it since it would now be marked as visible if (aliasEmitInfo) { createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) { + for (let declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } writeImportEqualsDeclaration(aliasToWrite); @@ -507,7 +508,7 @@ module ts { else { // Report error reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + let errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, @@ -561,7 +562,7 @@ module ts { } function emitSeparatedList(nodes: Node[], separator: string, eachNodeEmitFn: (node: Node) => void) { - var currentWriterPos = writer.getTextPos(); + let currentWriterPos = writer.getTextPos(); for (let node of nodes) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -577,7 +578,7 @@ module ts { function writeJsDocComments(declaration: Node) { if (declaration) { - var jsDocComments = getJsDocComments(declaration, currentSourceFile); + let 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); @@ -625,7 +626,7 @@ module ts { } function emitEntityName(entityName: EntityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, + let visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration); @@ -637,7 +638,7 @@ module ts { writeTextOfNode(currentSourceFile, entityName); } else { - var qualifiedName = entityName; + let qualifiedName = entityName; writeEntityName(qualifiedName.left); write("."); writeTextOfNode(currentSourceFile, qualifiedName.right); @@ -734,7 +735,7 @@ module ts { } function emitImportEqualsDeclaration(node: ImportEqualsDeclaration) { - var nodeEmitInfo = { + let nodeEmitInfo = { declaration: node, outputPos: writer.getTextPos(), indent: writer.getIndent(), @@ -787,7 +788,7 @@ module ts { write("."); writeTextOfNode(currentSourceFile, node.name); } - var prevEnclosingDeclaration = enclosingDeclaration; + let prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; write(" {"); writeLine(); @@ -842,7 +843,7 @@ module ts { function emitEnumMemberDeclaration(node: EnumMember) { emitJsDocComments(node); writeTextOfNode(currentSourceFile, node.name); - var enumMemberValue = resolver.getConstantValue(node); + let enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); write(enumMemberValue.toString()); @@ -882,7 +883,7 @@ module ts { function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { // Type parameter constraints are named by user so we should always be able to name it - var diagnosticMessage: DiagnosticMessage; + let diagnosticMessage: DiagnosticMessage; switch (node.parent.kind) { case SyntaxKind.ClassDeclaration: diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; @@ -946,7 +947,7 @@ module ts { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - var diagnosticMessage: DiagnosticMessage; + let diagnosticMessage: DiagnosticMessage; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { // Class or Interface implemented/extended is inaccessible @@ -984,10 +985,10 @@ module ts { emitModuleElementDeclarationFlags(node); write("class "); writeTextOfNode(currentSourceFile, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; + let prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = getClassBaseTypeNode(node); + let baseTypeNode = getClassBaseTypeNode(node); if (baseTypeNode) { emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); } @@ -1010,7 +1011,7 @@ module ts { emitModuleElementDeclarationFlags(node); write("interface "); writeTextOfNode(currentSourceFile, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; + let prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); emitHeritageClause(getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); @@ -1058,7 +1059,7 @@ module ts { } function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - var diagnosticMessage: DiagnosticMessage; + let diagnosticMessage: DiagnosticMessage; if (node.kind === SyntaxKind.VariableDeclaration) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? @@ -1110,7 +1111,7 @@ module ts { } function emitVariableStatement(node: VariableStatement) { - var hasDeclarationWithEmit = forEach(node.declarationList.declarations, varDeclaration => resolver.isDeclarationVisible(varDeclaration)); + let hasDeclarationWithEmit = forEach(node.declarationList.declarations, varDeclaration => resolver.isDeclarationVisible(varDeclaration)); if (hasDeclarationWithEmit) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -1134,18 +1135,20 @@ module ts { return; } - var accessors = getAllAccessorDeclarations((node.parent).members, node); + let accessors = getAllAccessorDeclarations((node.parent).members, node); + let accessorWithTypeAnnotation: AccessorDeclaration; + if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(node); writeTextOfNode(currentSourceFile, node.name); if (!(node.flags & NodeFlags.Private)) { - var accessorWithTypeAnnotation: AccessorDeclaration = node; - var type = getTypeAnnotationFromAccessor(node); + accessorWithTypeAnnotation = node; + let type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; + let anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -1168,7 +1171,7 @@ module ts { } function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - var diagnosticMessage: DiagnosticMessage; + let diagnosticMessage: DiagnosticMessage; if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) { // Setters have to have type named and cannot infer it so, the type should always be named if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) { @@ -1263,7 +1266,7 @@ module ts { write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; + let prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; // Parameters @@ -1277,7 +1280,7 @@ module ts { } // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType; + let 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) { @@ -1297,7 +1300,7 @@ module ts { } function getReturnTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - var diagnosticMessage: DiagnosticMessage; + let diagnosticMessage: DiagnosticMessage; switch (node.kind) { case SyntaxKind.ConstructSignature: // Interfaces cannot have return types that cannot be named @@ -1390,7 +1393,7 @@ module ts { } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - var diagnosticMessage: DiagnosticMessage; + let diagnosticMessage: DiagnosticMessage; switch (node.parent.kind) { case SyntaxKind.Constructor: diagnosticMessage = symbolAccesibilityResult.errorModuleName ? @@ -1499,7 +1502,7 @@ module ts { } function writeReferencePath(referencedFile: SourceFile) { - var declFileName = referencedFile.flags & NodeFlags.DeclarationFile + let declFileName = referencedFile.flags & NodeFlags.DeclarationFile ? referencedFile.fileName // Declaration file, use declaration file name : shouldEmitToOwnFile(referencedFile, compilerOptions) ? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file @@ -1517,8 +1520,8 @@ module ts { } export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { - var diagnostics: Diagnostic[] = []; - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + let diagnostics: Diagnostic[] = []; + let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); return diagnostics; } @@ -1526,16 +1529,16 @@ module ts { // @internal // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult { - var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || ScriptTarget.ES3; - var sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap ? [] : undefined; - var diagnostics: Diagnostic[] = []; - var newLine = host.getNewLine(); + let compilerOptions = host.getCompilerOptions(); + let languageVersion = compilerOptions.target || ScriptTarget.ES3; + let sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap ? [] : undefined; + let diagnostics: Diagnostic[] = []; + let newLine = host.getNewLine(); if (targetSourceFile === undefined) { forEach(host.getSourceFiles(), sourceFile => { if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js"); + let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js"); emitFile(jsFilePath, sourceFile); } }); @@ -1547,7 +1550,7 @@ module ts { else { // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); emitFile(jsFilePath, targetSourceFile); } else if (!isDeclarationFile(targetSourceFile) && compilerOptions.out) { @@ -1565,57 +1568,57 @@ module ts { }; function emitJavaScript(jsFilePath: string, root?: SourceFile) { - var writer = createTextWriter(newLine); - var write = writer.write; - var writeTextOfNode = writer.writeTextOfNode; - var writeLine = writer.writeLine; - var increaseIndent = writer.increaseIndent; - var decreaseIndent = writer.decreaseIndent; - var preserveNewLines = compilerOptions.preserveNewLines || false; + let writer = createTextWriter(newLine); + let write = writer.write; + let writeTextOfNode = writer.writeTextOfNode; + let writeLine = writer.writeLine; + let increaseIndent = writer.increaseIndent; + let decreaseIndent = writer.decreaseIndent; + let preserveNewLines = compilerOptions.preserveNewLines || false; - var currentSourceFile: SourceFile; + let currentSourceFile: SourceFile; - var lastFrame: ScopeFrame; - var currentScopeNames: Map; + let lastFrame: ScopeFrame; + let currentScopeNames: Map; - var generatedBlockScopeNames: string[]; + let generatedBlockScopeNames: string[]; - var extendsEmitted = false; - var tempCount = 0; - var tempVariables: Identifier[]; - var tempParameters: Identifier[]; - var externalImports: ExternalImportInfo[]; - var exportSpecifiers: Map; - var exportDefault: FunctionDeclaration | ClassDeclaration | ExportAssignment | ExportSpecifier; + let extendsEmitted = false; + let tempCount = 0; + let tempVariables: Identifier[]; + let tempParameters: Identifier[]; + let externalImports: ExternalImportInfo[]; + let exportSpecifiers: Map; + let exportDefault: FunctionDeclaration | ClassDeclaration | ExportAssignment | ExportSpecifier; /** write emitted output to disk*/ - var writeEmittedFiles = writeJavaScriptFile; + let writeEmittedFiles = writeJavaScriptFile; /** Emit leading comments of the node */ - var emitLeadingComments = compilerOptions.removeComments ? (node: Node) => { } : emitLeadingDeclarationComments; + let emitLeadingComments = compilerOptions.removeComments ? (node: Node) => { } : emitLeadingDeclarationComments; /** Emit Trailing comments of the node */ - var emitTrailingComments = compilerOptions.removeComments ? (node: Node) => { } : emitTrailingDeclarationComments; + let emitTrailingComments = compilerOptions.removeComments ? (node: Node) => { } : emitTrailingDeclarationComments; - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? (pos: number) => { } : emitLeadingCommentsOfLocalPosition; + let emitLeadingCommentsOfPosition = compilerOptions.removeComments ? (pos: number) => { } : emitLeadingCommentsOfLocalPosition; - var detachedCommentsInfo: { nodePos: number; detachedCommentEndPos: number }[]; + let detachedCommentsInfo: { nodePos: number; detachedCommentEndPos: number }[]; /** Emit detached comments of the node */ - var emitDetachedComments = compilerOptions.removeComments ? (node: TextRange) => { } : emitDetachedCommentsAtPosition; + let emitDetachedComments = compilerOptions.removeComments ? (node: TextRange) => { } : emitDetachedCommentsAtPosition; - var writeComment = writeCommentRange; + let writeComment = writeCommentRange; /** Emit a node */ - var emitNodeWithoutSourceMap = compilerOptions.removeComments ? emitNodeWithoutSourceMapWithoutComments : emitNodeWithoutSourceMapWithComments; - var emit = emitNodeWithoutSourceMap; - var emitWithoutComments = emitNodeWithoutSourceMapWithoutComments; + let emitNodeWithoutSourceMap = compilerOptions.removeComments ? emitNodeWithoutSourceMapWithoutComments : emitNodeWithoutSourceMapWithComments; + let emit = emitNodeWithoutSourceMap; + let emitWithoutComments = emitNodeWithoutSourceMapWithoutComments; /** Called just before starting emit of a node */ - var emitStart = function (node: Node) { }; + let emitStart = function (node: Node) { }; /** Called once the emit of the node is done */ - var emitEnd = function (node: Node) { }; + let emitEnd = function (node: Node) { }; /** Emit the text for the given token that comes after startPos * This by default writes the text provided with the given tokenKind @@ -1623,18 +1626,18 @@ module ts { * @param tokenKind the kind of the token to search and emit * @param startPos the position in the source to start searching for the token * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - var emitToken = emitTokenText; + let emitToken = emitTokenText; /** Called to before starting the lexical scopes as in function/class in the emitted code because of node * @param scopeDeclaration node that starts the lexical scope * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ - var scopeEmitStart = function (scopeDeclaration: Node, scopeName?: string) { } + let scopeEmitStart = function (scopeDeclaration: Node, scopeName?: string) { } /** Called after coming out of the scope */ - var scopeEmitEnd = function () { } + let scopeEmitEnd = function () { } /** Sourcemap data that will get encoded */ - var sourceMapData: SourceMapData; + let sourceMapData: SourceMapData; if (compilerOptions.sourceMap) { initializeEmitterWithSourceMaps(); @@ -1664,7 +1667,7 @@ module ts { // enters the new lexical environment // return value should be passed to matching call to exitNameScope. function enterNameScope(): boolean { - var names = currentScopeNames; + let names = currentScopeNames; currentScopeNames = undefined; if (names) { lastFrame = { names, previous: lastFrame }; @@ -1684,7 +1687,7 @@ module ts { } function generateUniqueNameForLocation(location: Node, baseName: string): string { - var name: string + let name: string // first try to check if base name can be used as is if (!isExistingName(location, baseName)) { name = baseName; @@ -1716,7 +1719,7 @@ module ts { } // check generated names in outer scopes - // var x; + // let x; // function foo() { // let x; // 1 // function bar() { @@ -1728,7 +1731,7 @@ module ts { //} // here both x(1) and x(2) should be renamed and their names should be different // so x in (3) will refer to x(1) - var frame = lastFrame; + let frame = lastFrame; while (frame) { if (hasProperty(frame.names, name)) { return true; @@ -1739,28 +1742,28 @@ module ts { } function initializeEmitterWithSourceMaps() { - var sourceMapDir: string; // The directory in which sourcemap will be + let sourceMapDir: string; // The directory in which sourcemap will be // Current source map file and its index in the sources list - var sourceMapSourceIndex = -1; + let sourceMapSourceIndex = -1; // Names and its index map - var sourceMapNameIndexMap: Map = {}; - var sourceMapNameIndices: number[] = []; + let sourceMapNameIndexMap: Map = {}; + let sourceMapNameIndices: number[] = []; function getSourceMapNameIndex() { return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; } // Last recorded and encoded spans - var lastRecordedSourceMapSpan: SourceMapSpan; - var lastEncodedSourceMapSpan: SourceMapSpan = { + let lastRecordedSourceMapSpan: SourceMapSpan; + let lastEncodedSourceMapSpan: SourceMapSpan = { emittedLine: 1, emittedColumn: 1, sourceLine: 1, sourceColumn: 1, sourceIndex: 0 }; - var lastEncodedNameIndex = 0; + let lastEncodedNameIndex = 0; // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -1768,7 +1771,7 @@ module ts { return; } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { // Emit comma to separate the entry @@ -1778,7 +1781,7 @@ module ts { } else { // Emit line delimiters - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + for (let encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { sourceMapData.sourceMapMappings += ";"; } prevEncodedEmittedColumn = 1; @@ -1826,9 +1829,9 @@ module ts { } // Encode 5 bits at a time starting from least significant bits - var encodedStr = ""; + let encodedStr = ""; do { - var currentDigit = inValue & 31; // 11111 + let currentDigit = inValue & 31; // 11111 inValue = inValue >> 5; if (inValue > 0) { // There are still more digits to decode, set the msb (6th bit) @@ -1842,14 +1845,14 @@ module ts { } function recordSourceMapSpan(pos: number) { - var sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos); + let sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); + let emittedLine = writer.getLine(); + let emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || @@ -1889,9 +1892,9 @@ module ts { } function writeTextWithSpanRecord(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + let tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + let tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); recordSourceMapSpan(tokenEndPos); return tokenEndPos; } @@ -1900,7 +1903,7 @@ module ts { // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + let sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, @@ -1919,14 +1922,14 @@ module ts { } function recordScopeNameStart(scopeName: string) { - var scopeNameIndex = -1; + let scopeNameIndex = -1; if (scopeName) { - var parentIndex = getSourceMapNameIndex(); + let 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. - var name = (node).name; + let name = (node).name; if (!name || name.kind !== SyntaxKind.ComputedPropertyName) { scopeName = "." + scopeName; } @@ -1958,7 +1961,7 @@ module ts { node.kind === SyntaxKind.EnumDeclaration) { // Declaration and has associated name use it if ((node).name) { - var name = (node).name; + let name = (node).name; // For computed property names, the text will include the brackets scopeName = name.kind === SyntaxKind.ComputedPropertyName ? getTextOfNode(name) @@ -1997,8 +2000,8 @@ module ts { return "{\"version\":" + version + ",\"file\":\"" + escapeString(file) + "\",\"sourceRoot\":\"" + escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + escapeString(mappings) + "\"}"; function serializeStringArray(list: string[]): string { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { + let output = ""; + for (let i = 0, n = list.length; i < n; i++) { if (i) { output += ","; } @@ -2025,7 +2028,7 @@ module ts { } // Initialize source map data - var sourceMapJsFile = getBaseFileName(normalizeSlashes(jsFilePath)); + let sourceMapJsFile = getBaseFileName(normalizeSlashes(jsFilePath)); sourceMapData = { sourceMapFilePath: jsFilePath + ".map", jsSourceMappingURL: sourceMapJsFile + ".map", @@ -2114,7 +2117,7 @@ module ts { // Create a temporary variable with a unique unused name. The forLoopVariable parameter signals that the // name should be one that is appropriate for a for loop variable. function createTempVariable(location: Node, forLoopVariable?: boolean): Identifier { - var name = forLoopVariable ? "_i" : undefined; + let name = forLoopVariable ? "_i" : undefined; while (true) { if (name && !isExistingName(location, name)) { break; @@ -2129,7 +2132,7 @@ module ts { // we just generated. recordNameInCurrentScope(name); - var result = createSynthesizedNode(SyntaxKind.Identifier); + let result = createSynthesizedNode(SyntaxKind.Identifier); result.text = name; return result; } @@ -2142,7 +2145,7 @@ module ts { } function createAndRecordTempVariable(location: Node): Identifier { - var temp = createTempVariable(location, /*forLoopVariable*/ false); + let temp = createTempVariable(location, /*forLoopVariable*/ false); recordTempDeclaration(temp); return temp; @@ -2163,7 +2166,7 @@ module ts { } function emitTokenText(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) { - var tokenString = tokenToString(tokenKind); + let tokenString = tokenToString(tokenKind); if (emitFn) { emitFn(); } @@ -2210,7 +2213,7 @@ module ts { writeLine(); } - for (var i = 0, n = nodes.length; i < n; i++) { + for (let i = 0, n = nodes.length; i < n; i++) { if (i) { if (preserveNewLines && nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { write(", "); @@ -2241,7 +2244,7 @@ module ts { } function emitList(nodes: Node[], start: number, count: number, multiLine: boolean, trailingComma: boolean) { - for (var i = 0; i < count; i++) { + for (let i = 0; i < count; i++) { if (multiLine) { if (i) { write(","); @@ -2274,7 +2277,7 @@ module ts { } function emitLinesStartingAt(nodes: Node[], startIndex: number): void { - for (var i = startIndex; i < nodes.length; i++) { + for (let i = startIndex; i < nodes.length; i++) { writeLine(); emit(nodes[i]); } @@ -2295,7 +2298,7 @@ module ts { } function emitLiteral(node: LiteralExpression) { - var text = getLiteralText(node); + let text = getLiteralText(node); if (compilerOptions.sourceMap && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { writer.writeLiteral(text); @@ -2350,13 +2353,13 @@ module ts { // Find original source text, since we need to emit the raw strings of the tagged template. // The raw strings contain the (escaped) strings of what the user wrote. // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node); // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - var isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; + let isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: @@ -2384,7 +2387,7 @@ module ts { } function emitDownlevelTaggedTemplate(node: TaggedTemplateExpression) { - var tempVariable = createAndRecordTempVariable(node); + let tempVariable = createAndRecordTempVariable(node); write("("); emit(tempVariable); write(" = "); @@ -2404,7 +2407,7 @@ module ts { if (node.template.kind === SyntaxKind.TemplateExpression) { forEach((node.template).templateSpans, templateSpan => { write(", "); - var needsParens = templateSpan.expression.kind === SyntaxKind.BinaryExpression + let needsParens = templateSpan.expression.kind === SyntaxKind.BinaryExpression && (templateSpan.expression).operatorToken.kind === SyntaxKind.CommaToken; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -2420,21 +2423,21 @@ module ts { return; } - var emitOuterParens = isExpression(node.parent) + let emitOuterParens = isExpression(node.parent) && templateNeedsParens(node, node.parent); if (emitOuterParens) { write("("); } - var headEmitted = false; + let headEmitted = false; if (shouldEmitTemplateHead()) { emitLiteral(node.head); headEmitted = true; } for (let i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; + let 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 @@ -2445,7 +2448,7 @@ module ts { // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression + let needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression && comparePrecedenceToBinaryPlus(templateSpan.expression) !== Comparison.GreaterThan; if (i > 0 || headEmitted) { @@ -2573,7 +2576,7 @@ module ts { } function isNotExpressionIdentifier(node: Identifier) { - var parent = node.parent; + let parent = node.parent; switch (parent.kind) { case SyntaxKind.Parameter: case SyntaxKind.VariableDeclaration: @@ -2605,7 +2608,7 @@ module ts { } function emitExpressionIdentifier(node: Identifier) { - var substitution = resolver.getExpressionNameSubstitution(node); + let substitution = resolver.getExpressionNameSubstitution(node); if (substitution) { write(substitution); } @@ -2620,9 +2623,9 @@ module ts { } function emitIdentifier(node: Identifier) { - var variableId = getBlockScopedVariableId(node); + let variableId = getBlockScopedVariableId(node); if (variableId !== undefined && generatedBlockScopeNames) { - var text = generatedBlockScopeNames[variableId]; + let text = generatedBlockScopeNames[variableId]; if (text) { write(text); return; @@ -2649,7 +2652,7 @@ module ts { } function emitSuper(node: Node) { - var flags = resolver.getNodeCheckFlags(node); + let flags = resolver.getNodeCheckFlags(node); if (flags & NodeCheckFlags.SuperInstance) { write("_super.prototype"); } @@ -2663,14 +2666,14 @@ module ts { function emitObjectBindingPattern(node: BindingPattern) { write("{ "); - var elements = node.elements; + let elements = node.elements; emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); write(" }"); } function emitArrayBindingPattern(node: BindingPattern) { write("["); - var elements = node.elements; + let elements = node.elements; emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); write("]"); } @@ -2713,9 +2716,9 @@ module ts { } function emitListWithSpread(elements: Expression[], multiLine: boolean, trailingComma: boolean) { - var pos = 0; - var group = 0; - var length = elements.length; + let pos = 0; + let group = 0; + let length = elements.length; while (pos < length) { // Emit using the pattern .concat(, , ...) if (group === 1) { @@ -2724,14 +2727,14 @@ module ts { else if (group > 1) { write(", "); } - var e = elements[pos]; + let e = elements[pos]; if (e.kind === SyntaxKind.SpreadElementExpression) { e = (e).expression; emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; } else { - var i = pos; + let i = pos; while (i < length && elements[i].kind !== SyntaxKind.SpreadElementExpression) { i++; } @@ -2758,7 +2761,7 @@ module ts { } function emitArrayLiteral(node: ArrayLiteralExpression) { - var elements = node.elements; + let elements = node.elements; if (elements.length === 0) { write("[]"); } @@ -2774,31 +2777,31 @@ module ts { } function emitDownlevelObjectLiteralWithComputedProperties(node: ObjectLiteralExpression, firstComputedPropertyIndex: number): void { - var parenthesizedObjectLiteral = createDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex); + let parenthesizedObjectLiteral = createDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex); return emit(parenthesizedObjectLiteral); } function createDownlevelObjectLiteralWithComputedProperties(originalObjectLiteral: ObjectLiteralExpression, firstComputedPropertyIndex: number): ParenthesizedExpression { // 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. - var tempVar = createAndRecordTempVariable(originalObjectLiteral); + let tempVar = createAndRecordTempVariable(originalObjectLiteral); // Hold onto the initial non-computed properties in a new object literal, // then create the rest through property accesses on the temp variable. - var initialObjectLiteral = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); + let initialObjectLiteral = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); initialObjectLiteral.properties = >originalObjectLiteral.properties.slice(0, firstComputedPropertyIndex); initialObjectLiteral.flags |= NodeFlags.MultiLine; // The comma expressions that will patch the object literal. // This will end up being something like '_a = { ... }, _a.x = 10, _a.y = 20, _a'. - var propertyPatches = createBinaryExpression(tempVar, SyntaxKind.EqualsToken, initialObjectLiteral); + let propertyPatches = createBinaryExpression(tempVar, SyntaxKind.EqualsToken, initialObjectLiteral); ts.forEach(originalObjectLiteral.properties, property => { - var patchedProperty = tryCreatePatchingPropertyAssignment(originalObjectLiteral, tempVar, property); + let patchedProperty = tryCreatePatchingPropertyAssignment(originalObjectLiteral, tempVar, property); if (patchedProperty) { // TODO(drosen): Preserve comments - //var leadingComments = getLeadingCommentRanges(currentSourceFile.text, property.pos); - //var trailingComments = getTrailingCommentRanges(currentSourceFile.text, property.end); + //let leadingComments = getLeadingCommentRanges(currentSourceFile.text, property.pos); + //let trailingComments = getTrailingCommentRanges(currentSourceFile.text, property.end); //addCommentsToSynthesizedNode(patchedProperty, leadingComments, trailingComments); propertyPatches = createBinaryExpression(propertyPatches, SyntaxKind.CommaToken, patchedProperty); @@ -2808,11 +2811,11 @@ module ts { // Finally, return the temp variable. propertyPatches = createBinaryExpression(propertyPatches, SyntaxKind.CommaToken, createIdentifier(tempVar.text, /*startsOnNewLine:*/ true)); - var result = createParenthesizedExpression(propertyPatches); + let result = createParenthesizedExpression(propertyPatches); // TODO(drosen): Preserve comments - // var leadingComments = getLeadingCommentRanges(currentSourceFile.text, originalObjectLiteral.pos); - // var trailingComments = getTrailingCommentRanges(currentSourceFile.text, originalObjectLiteral.end); + // let leadingComments = getLeadingCommentRanges(currentSourceFile.text, originalObjectLiteral.pos); + // let trailingComments = getTrailingCommentRanges(currentSourceFile.text, originalObjectLiteral.end); //addCommentsToSynthesizedNode(result, leadingComments, trailingComments); return result; @@ -2826,8 +2829,8 @@ module ts { // Returns 'undefined' if a property has already been accounted for // (e.g. a 'get' accessor which has already been emitted along with its 'set' accessor). function tryCreatePatchingPropertyAssignment(objectLiteral: ObjectLiteralExpression, tempVar: Identifier, property: ObjectLiteralElement): Expression { - var leftHandSide = createMemberAccessForPropertyName(tempVar, property.name); - var maybeRightHandSide = tryGetRightHandSideOfPatchingPropertyAssignment(objectLiteral, property); + let leftHandSide = createMemberAccessForPropertyName(tempVar, property.name); + let maybeRightHandSide = tryGetRightHandSideOfPatchingPropertyAssignment(objectLiteral, property); return maybeRightHandSide && createBinaryExpression(leftHandSide, SyntaxKind.EqualsToken, maybeRightHandSide, /*startsOnNewLine:*/ true); } @@ -2841,7 +2844,7 @@ module ts { // TODO: (andersh) Technically it isn't correct to make an identifier here since getExpressionNamePrefix returns // a string containing a dotted name. In general I'm not a fan of mini tree rewriters as this one, elsewhere we // manage by just emitting strings (which is a lot more performant). - //var prefix = createIdentifier(resolver.getExpressionNamePrefix((property).name)); + //let prefix = createIdentifier(resolver.getExpressionNamePrefix((property).name)); //return createPropertyAccessExpression(prefix, (property).name); return createIdentifier(resolver.getExpressionNameSubstitution((property).name)); @@ -2857,29 +2860,29 @@ module ts { return undefined; } - var propertyDescriptor = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); + let propertyDescriptor = createSynthesizedNode(SyntaxKind.ObjectLiteralExpression); - var descriptorProperties = >[]; + let descriptorProperties = >[]; if (getAccessor) { - var getProperty = createPropertyAssignment(createIdentifier("get"), createFunctionExpression(getAccessor.parameters, getAccessor.body)); + let getProperty = createPropertyAssignment(createIdentifier("get"), createFunctionExpression(getAccessor.parameters, getAccessor.body)); descriptorProperties.push(getProperty); } if (setAccessor) { - var setProperty = createPropertyAssignment(createIdentifier("set"), createFunctionExpression(setAccessor.parameters, setAccessor.body)); + let setProperty = createPropertyAssignment(createIdentifier("set"), createFunctionExpression(setAccessor.parameters, setAccessor.body)); descriptorProperties.push(setProperty); } - var trueExpr = createSynthesizedNode(SyntaxKind.TrueKeyword); + let trueExpr = createSynthesizedNode(SyntaxKind.TrueKeyword); - var enumerableTrue = createPropertyAssignment(createIdentifier("enumerable"), trueExpr); + let enumerableTrue = createPropertyAssignment(createIdentifier("enumerable"), trueExpr); descriptorProperties.push(enumerableTrue); - var configurableTrue = createPropertyAssignment(createIdentifier("configurable"), trueExpr); + let configurableTrue = createPropertyAssignment(createIdentifier("configurable"), trueExpr); descriptorProperties.push(configurableTrue); propertyDescriptor.properties = descriptorProperties; - var objectDotDefineProperty = createPropertyAccessExpression(createIdentifier("Object"), createIdentifier("defineProperty")); + let objectDotDefineProperty = createPropertyAccessExpression(createIdentifier("Object"), createIdentifier("defineProperty")); return createCallExpression(objectDotDefineProperty, createNodeArray(propertyDescriptor)); default: @@ -2888,14 +2891,14 @@ module ts { } function createParenthesizedExpression(expression: Expression) { - var result = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); + let result = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); result.expression = expression; return result; } function createNodeArray(...elements: T[]): NodeArray { - var result = >elements; + let result = >elements; result.pos = -1; result.end = -1; @@ -2903,7 +2906,7 @@ module ts { } function createBinaryExpression(left: Expression, operator: SyntaxKind, right: Expression, startsOnNewLine?: boolean): BinaryExpression { - var result = createSynthesizedNode(SyntaxKind.BinaryExpression, startsOnNewLine); + let result = createSynthesizedNode(SyntaxKind.BinaryExpression, startsOnNewLine); result.operatorToken = createSynthesizedNode(operator); result.left = left; result.right = right; @@ -2912,7 +2915,7 @@ module ts { } function createExpressionStatement(expression: Expression): ExpressionStatement { - var result = createSynthesizedNode(SyntaxKind.ExpressionStatement); + let result = createSynthesizedNode(SyntaxKind.ExpressionStatement); result.expression = expression; return result; } @@ -2933,7 +2936,7 @@ module ts { } function createPropertyAssignment(name: LiteralExpression | Identifier, initializer: Expression) { - var result = createSynthesizedNode(SyntaxKind.PropertyAssignment); + let result = createSynthesizedNode(SyntaxKind.PropertyAssignment); result.name = name; result.initializer = initializer; @@ -2941,7 +2944,7 @@ module ts { } function createFunctionExpression(parameters: NodeArray, body: Block): FunctionExpression { - var result = createSynthesizedNode(SyntaxKind.FunctionExpression); + let result = createSynthesizedNode(SyntaxKind.FunctionExpression); result.parameters = parameters; result.body = body; @@ -2949,7 +2952,7 @@ module ts { } function createPropertyAccessExpression(expression: LeftHandSideExpression, name: Identifier): PropertyAccessExpression { - var result = createSynthesizedNode(SyntaxKind.PropertyAccessExpression); + let result = createSynthesizedNode(SyntaxKind.PropertyAccessExpression); result.expression = expression; result.dotToken = createSynthesizedNode(SyntaxKind.DotToken); result.name = name; @@ -2958,7 +2961,7 @@ module ts { } function createElementAccessExpression(expression: LeftHandSideExpression, argumentExpression: Expression): ElementAccessExpression { - var result = createSynthesizedNode(SyntaxKind.ElementAccessExpression); + let result = createSynthesizedNode(SyntaxKind.ElementAccessExpression); result.expression = expression; result.argumentExpression = argumentExpression; @@ -2966,14 +2969,14 @@ module ts { } function createIdentifier(name: string, startsOnNewLine?: boolean) { - var result = createSynthesizedNode(SyntaxKind.Identifier, startsOnNewLine); + let result = createSynthesizedNode(SyntaxKind.Identifier, startsOnNewLine); result.text = name; return result; } function createCallExpression(invokedExpression: MemberExpression, arguments: NodeArray) { - var result = createSynthesizedNode(SyntaxKind.CallExpression); + let result = createSynthesizedNode(SyntaxKind.CallExpression); result.expression = invokedExpression; result.arguments = arguments; @@ -2981,22 +2984,22 @@ module ts { } function emitObjectLiteral(node: ObjectLiteralExpression): void { - var properties = node.properties; + let properties = node.properties; if (languageVersion < ScriptTarget.ES6) { - var numProperties = properties.length; + let numProperties = properties.length; // Find the first computed property. // Everything until that point can be emitted as part of the initial object literal. - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { + let numInitialNonComputedProperties = numProperties; + for (let i = 0, n = properties.length; i < n; i++) { if (properties[i].name.kind === SyntaxKind.ComputedPropertyName) { numInitialNonComputedProperties = i; break; } } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; + let hasComputedProperty = numInitialNonComputedProperties !== properties.length; if (hasComputedProperty) { emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); return; @@ -3007,7 +3010,6 @@ module ts { // or we're compiling with an ES6+ target. write("{"); - var properties = node.properties; if (properties.length) { emitLinePreservingList(node, properties, /*allowTrailingComma:*/ languageVersion >= ScriptTarget.ES5, /*spacesBetweenBraces:*/ true) } @@ -3039,10 +3041,10 @@ module ts { emit(node.name); // If short-hand property has a prefix, then regardless of the target version, we will emit it as normal property assignment. For example: // module m { - // export var y; + // export let y; // } // module m { - // export var obj = { y }; + // export let obj = { y }; // } // The short-hand property in obj need to emit as such ... = { y : m.y } regardless of the TargetScript version if (languageVersion < ScriptTarget.ES6 || resolver.getExpressionNameSubstitution(node.name)) { @@ -3055,11 +3057,11 @@ module ts { } function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean { - var constantValue = resolver.getConstantValue(node); + let constantValue = resolver.getConstantValue(node); if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); + let propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -3071,10 +3073,10 @@ module ts { // If the code is not indented, an optional valueToWriteWhenNotIndenting will be // emitted instead. function indentIfOnDifferentLines(parent: Node, node1: Node, node2: Node, valueToWriteWhenNotIndenting?: string): boolean { - var realNodesAreOnDifferentLines = preserveNewLines && !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); + let realNodesAreOnDifferentLines = preserveNewLines && !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); // Always use a newline for synthesized code if the synthesizer desires it. - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); + let synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { increaseIndent(); @@ -3095,9 +3097,9 @@ module ts { } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); write("."); - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -3134,7 +3136,7 @@ module ts { emit(node); return node; } - var temp = createAndRecordTempVariable(node); + let temp = createAndRecordTempVariable(node); write("("); emit(temp); @@ -3145,8 +3147,8 @@ module ts { } function emitCallWithSpread(node: CallExpression) { - var target: Expression; - var expr = skipParentheses(node.expression); + let target: Expression; + let expr = skipParentheses(node.expression); if (expr.kind === SyntaxKind.PropertyAccessExpression) { // Target will be emitted as "this" argument target = emitCallTarget((expr).expression); @@ -3192,7 +3194,7 @@ module ts { emitCallWithSpread(node); return; } - var superCall = false; + let superCall = false; if (node.expression.kind === SyntaxKind.SuperKeyword) { write("_super"); superCall = true; @@ -3241,7 +3243,7 @@ module ts { function emitParenExpression(node: ParenthesizedExpression) { if (!node.parent || node.parent.kind !== SyntaxKind.ArrowFunction) { if (node.expression.kind === SyntaxKind.TypeAssertionExpression) { - var operand = (node.expression).expression; + let operand = (node.expression).expression; // Make sure we consider all nested cast expressions, e.g.: // (-A).x; @@ -3309,7 +3311,7 @@ module ts { // 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) { - var operand = node.operand; + let operand = node.operand; if (node.operator === SyntaxKind.PlusToken && (operand.operator === SyntaxKind.PlusToken || operand.operator === SyntaxKind.PlusPlusToken)) { write(" "); } @@ -3332,9 +3334,9 @@ module ts { } else { emit(node.left); - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== SyntaxKind.CommaToken ? " " : undefined); + let indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== SyntaxKind.CommaToken ? " " : undefined); write(tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); + let indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); emit(node.right); decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); } @@ -3346,14 +3348,14 @@ module ts { function emitConditionalExpression(node: ConditionalExpression) { emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); + let indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); + let indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); emit(node.whenTrue); decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); + let indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); + let indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); emit(node.whenFalse); decreaseIndentIf(indentedBeforeColon, indentedAfterColon); } @@ -3373,7 +3375,7 @@ module ts { function isSingleLineEmptyBlock(node: Node) { if (node && node.kind === SyntaxKind.Block) { - var block = node; + let block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } } @@ -3422,7 +3424,7 @@ module ts { } function emitIfStatement(node: IfStatement) { - var endPos = emitToken(SyntaxKind.IfKeyword, node.pos); + let endPos = emitToken(SyntaxKind.IfKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); emit(node.expression); @@ -3463,7 +3465,7 @@ module ts { } function emitStartOfVariableDeclarationList(decl: Node, startPos?: number): void { - var tokenKind = SyntaxKind.VarKeyword; + let tokenKind = SyntaxKind.VarKeyword; if (decl && languageVersion >= ScriptTarget.ES6) { if (isLet(decl)) { tokenKind = SyntaxKind.LetKeyword; @@ -3489,12 +3491,12 @@ module ts { } function emitForStatement(node: ForStatement) { - var endPos = emitToken(SyntaxKind.ForKeyword, node.pos); + let endPos = emitToken(SyntaxKind.ForKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { - var variableDeclarationList = node.initializer; - var declarations = variableDeclarationList.declarations; + let variableDeclarationList = node.initializer; + let declarations = variableDeclarationList.declarations; emitStartOfVariableDeclarationList(declarations[0], endPos); write(" "); emitCommaList(declarations); @@ -3515,13 +3517,13 @@ module ts { return emitDownLevelForOfStatement(node); } - var endPos = emitToken(SyntaxKind.ForKeyword, node.pos); + let endPos = emitToken(SyntaxKind.ForKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - var variableDeclarationList = node.initializer; + let variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; + let decl = variableDeclarationList.declarations[0]; emitStartOfVariableDeclarationList(decl, endPos); write(" "); emit(decl); @@ -3545,18 +3547,18 @@ module ts { function emitDownLevelForOfStatement(node: ForOfStatement) { // The following ES6 code: // - // for (var v of expr) { } + // for (let v of expr) { } // // should be emitted as // - // for (var _i = 0, _a = expr; _i < _a.length; _i++) { - // var v = _a[_i]; + // for (let _i = 0, _a = expr; _i < _a.length; _i++) { + // let v = _a[_i]; // } // // where _a and _i are temps emitted to capture the RHS and the counter, // respectively. - // When the left hand side is an expression instead of a var declaration, - // the "var v" is not emitted. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. // When the left hand side is a let/const, the v is renamed if there is // another v in scope. // Note that all assignments to the LHS are emitted in the body, including @@ -3564,24 +3566,24 @@ module ts { // Note also that because an extra statement is needed to assign to the LHS, // for-of bodies are always emitted as blocks. - var endPos = emitToken(SyntaxKind.ForKeyword, node.pos); + let endPos = emitToken(SyntaxKind.ForKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); - // Do not emit the LHS var declaration yet, because it might contain destructuring. + // Do not emit the LHS let declaration yet, because it might contain destructuring. // Do not call recordTempDeclaration because we are declaring the temps // right here. Recording means they will be declared later. // In the case where the user wrote an identifier as the RHS, like this: // - // for (var v of arr) { } + // for (let v of arr) { } // // we don't want to emit a temporary variable for the RHS, just use it directly. - var rhsIsIdentifier = node.expression.kind === SyntaxKind.Identifier; - var counter = createTempVariable(node, /*forLoopVariable*/ true); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(node, /*forLoopVariable*/ false); + let rhsIsIdentifier = node.expression.kind === SyntaxKind.Identifier; + let counter = createTempVariable(node, /*forLoopVariable*/ true); + let rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(node, /*forLoopVariable*/ false); - // This is the var keyword for the counter and rhsReference. The var keyword for + // This is the let keyword for the counter and rhsReference. The let keyword for // the LHS will be emitted inside the body. emitStart(node.expression); write("var "); @@ -3624,14 +3626,14 @@ module ts { increaseIndent(); // Initialize LHS - // var v = _a[_i]; - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); + // let v = _a[_i]; + let rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { write("var "); - var variableDeclarationList = node.initializer; + let variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; + let 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. @@ -3647,7 +3649,7 @@ module ts { } else { // It's an empty declaration list. This can only happen in an error case, if the user wrote - // for (var of []) {} + // for (let of []) {} emitNodeWithoutSourceMap(createTempVariable(node, /*forLoopVariable*/ false)); write(" = "); emitNodeWithoutSourceMap(rhsIterationValue); @@ -3656,7 +3658,7 @@ module ts { else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - var assignmentExpression = createBinaryExpression(node.initializer, SyntaxKind.EqualsToken, rhsIterationValue, /*startsOnNewLine*/ false); + let 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. @@ -3702,7 +3704,7 @@ module ts { } function emitSwitchStatement(node: SwitchStatement) { - var endPos = emitToken(SyntaxKind.SwitchKeyword, node.pos); + let endPos = emitToken(SyntaxKind.SwitchKeyword, node.pos); write(" "); emitToken(SyntaxKind.OpenParenToken, endPos); emit(node.expression); @@ -3775,7 +3777,7 @@ module ts { function emitCatchClause(node: CatchClause) { writeLine(); - var endPos = emitToken(SyntaxKind.CatchKeyword, node.pos); + let endPos = emitToken(SyntaxKind.CatchKeyword, node.pos); write(" "); emitToken(SyntaxKind.OpenParenToken, endPos); emit(node.variableDeclaration); @@ -3803,7 +3805,7 @@ module ts { } function emitContainingModuleName(node: Node) { - var container = getContainingModule(node); + let container = getContainingModule(node); write(container ? resolver.getGeneratedNameForNode(container) : "exports"); } @@ -3818,9 +3820,9 @@ module ts { } function createVoidZero(): Expression { - var zero = createSynthesizedNode(SyntaxKind.NumericLiteral); + let zero = createSynthesizedNode(SyntaxKind.NumericLiteral); zero.text = "0"; - var result = createSynthesizedNode(SyntaxKind.VoidExpression); + let result = createSynthesizedNode(SyntaxKind.VoidExpression); result.expression = zero; return result; } @@ -3851,10 +3853,10 @@ module ts { isAssignmentExpressionStatement: boolean, value?: Expression, lowestNonSynthesizedAncestor?: Node) { - var emitCount = 0; + let emitCount = 0; // An exported declaration is actually emitted as an assignment (to a property on the module object), so // temporary variables in an exported declaration need to have real declarations elsewhere - var isDeclaration = (root.kind === SyntaxKind.VariableDeclaration && !(getCombinedNodeFlags(root) & NodeFlags.Export)) || root.kind === SyntaxKind.Parameter; + let isDeclaration = (root.kind === SyntaxKind.VariableDeclaration && !(getCombinedNodeFlags(root) & NodeFlags.Export)) || root.kind === SyntaxKind.Parameter; if (root.kind === SyntaxKind.BinaryExpression) { emitAssignmentExpression(root); } @@ -3884,7 +3886,7 @@ module ts { // In case the root is a synthesized node, we need to pass lowestNonSynthesizedAncestor // as the location for determining uniqueness of the variable we are about to // generate. - var identifier = createTempVariable(lowestNonSynthesizedAncestor || root); + let identifier = createTempVariable(lowestNonSynthesizedAncestor || root); if (!isDeclaration) { recordTempDeclaration(identifier); } @@ -3899,7 +3901,7 @@ module ts { // we need to generate a temporary variable value = ensureIdentifier(value); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = createSynthesizedNode(SyntaxKind.BinaryExpression); + let equals = createSynthesizedNode(SyntaxKind.BinaryExpression); equals.left = value; equals.operatorToken = createSynthesizedNode(SyntaxKind.EqualsEqualsEqualsToken); equals.right = createVoidZero(); @@ -3907,7 +3909,7 @@ module ts { } function createConditionalExpression(condition: Expression, whenTrue: Expression, whenFalse: Expression) { - var cond = createSynthesizedNode(SyntaxKind.ConditionalExpression); + let cond = createSynthesizedNode(SyntaxKind.ConditionalExpression); cond.condition = condition; cond.questionToken = createSynthesizedNode(SyntaxKind.QuestionToken); cond.whenTrue = whenTrue; @@ -3917,7 +3919,7 @@ module ts { } function createNumericLiteral(value: number) { - var node = createSynthesizedNode(SyntaxKind.NumericLiteral); + let node = createSynthesizedNode(SyntaxKind.NumericLiteral); node.text = "" + value; return node; } @@ -3926,7 +3928,7 @@ module ts { if (expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.PropertyAccessExpression || expr.kind === SyntaxKind.ElementAccessExpression) { return expr; } - var node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); + let node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); node.expression = expr; return node; } @@ -3939,14 +3941,14 @@ module ts { } function createElementAccess(object: Expression, index: Expression): Expression { - var node = createSynthesizedNode(SyntaxKind.ElementAccessExpression); + let node = createSynthesizedNode(SyntaxKind.ElementAccessExpression); node.expression = parenthesizeForAccess(object); node.argumentExpression = index; return node; } function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression) { - var properties = target.properties; + let 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. @@ -3955,21 +3957,21 @@ module ts { for (let p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { // TODO(andersh): Computed property support - var propName = ((p).name); + let propName = ((p).name); emitDestructuringAssignment((p).initializer || propName, createPropertyAccess(value, propName)); } } } function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression) { - var elements = target.elements; + let 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); } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; + for (let i = 0; i < elements.length; i++) { + let e = elements[i]; if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { emitDestructuringAssignment(e, createElementAccess(value, createNumericLiteral(i))); @@ -4002,8 +4004,8 @@ module ts { } function emitAssignmentExpression(root: BinaryExpression) { - var target = root.left; - var value = root.right; + let target = root.left; + let value = root.right; if (isAssignmentExpressionStatement) { emitDestructuringAssignment(target, value); } @@ -4031,18 +4033,18 @@ module ts { value = createVoidZero(); } if (isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; + let pattern = target.name; + let elements = pattern.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); } - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; + for (let i = 0; i < elements.length; i++) { + let element = elements[i]; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Rewrite element to a declaration with an initializer that fetches property - var propName = element.propertyName || element.name; + let propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccess(value, propName)); } else if (element.kind !== SyntaxKind.OmittedExpression) { @@ -4080,7 +4082,7 @@ module ts { renameNonTopLevelLetAndConst(node.name); emitModuleMemberName(node); - var initializer = node.initializer; + let initializer = node.initializer; if (!initializer && languageVersion < ScriptTarget.ES6) { // downlevel emit for non-initialized let bindings defined in loops @@ -4089,7 +4091,7 @@ module ts { // 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 - var isUninitializedLet = + let isUninitializedLet = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) && (getCombinedFlagsForIdentifier(node.name) & NodeFlags.Let); @@ -4106,7 +4108,7 @@ module ts { } function emitExportVariableAssignments(node: VariableDeclaration | BindingElement) { - var name = (node).name; + let name = (node).name; if (name.kind === SyntaxKind.Identifier) { emitExportMemberAssignments(name); } @@ -4137,26 +4139,26 @@ module ts { return; } - var combinedFlags = getCombinedFlagsForIdentifier(node); + let combinedFlags = getCombinedFlagsForIdentifier(node); if (((combinedFlags & NodeFlags.BlockScoped) === 0) || combinedFlags & NodeFlags.Export) { // do not rename exported or non-block scoped variables return; } // here it is known that node is a block scoped variable - var list = getAncestor(node, SyntaxKind.VariableDeclarationList); + let list = getAncestor(node, SyntaxKind.VariableDeclarationList); if (list.parent.kind === SyntaxKind.VariableStatement && list.parent.parent.kind === SyntaxKind.SourceFile) { // do not rename variables that are defined on source file level return; } - var blockScopeContainer = getEnclosingBlockScopeContainer(node); - var parent = blockScopeContainer.kind === SyntaxKind.SourceFile + let blockScopeContainer = getEnclosingBlockScopeContainer(node); + let parent = blockScopeContainer.kind === SyntaxKind.SourceFile ? blockScopeContainer : blockScopeContainer.parent; - var generatedName = generateUniqueNameForLocation(parent, (node).text); - var variableId = resolver.getBlockScopedVariableId(node); + let generatedName = generateUniqueNameForLocation(parent, (node).text); + let variableId = resolver.getBlockScopedVariableId(node); if (!generatedBlockScopeNames) { generatedBlockScopeNames = []; } @@ -4177,7 +4179,7 @@ module ts { function emitParameter(node: ParameterDeclaration) { if (languageVersion < ScriptTarget.ES6) { if (isBindingPattern(node.name)) { - var name = createTempVariable(node); + let name = createTempVariable(node); if (!tempParameters) { tempParameters = []; } @@ -4199,7 +4201,7 @@ module ts { function emitDefaultValueAssignments(node: FunctionLikeDeclaration) { if (languageVersion < ScriptTarget.ES6) { - var tempIndex = 0; + let tempIndex = 0; forEach(node.parameters, p => { if (isBindingPattern(p.name)) { writeLine(); @@ -4229,9 +4231,9 @@ module ts { function emitRestParameter(node: FunctionLikeDeclaration) { if (languageVersion < ScriptTarget.ES6 && hasRestParameters(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - var tempName = createTempVariable(node, /*forLoopVariable*/ true).text; + let restIndex = node.parameters.length - 1; + let restParam = node.parameters[restIndex]; + let tempName = createTempVariable(node, /*forLoopVariable*/ true).text; writeLine(); emitLeadingComments(restParam); emitStart(restParam); @@ -4326,8 +4328,8 @@ module ts { increaseIndent(); write("("); if (node) { - var parameters = node.parameters; - var omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameters(node) ? 1 : 0; + let parameters = node.parameters; + let omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameters(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false); } write(")"); @@ -4344,14 +4346,14 @@ module ts { } function emitSignatureAndBody(node: FunctionLikeDeclaration) { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; + let saveTempCount = tempCount; + let saveTempVariables = tempVariables; + let saveTempParameters = tempParameters; tempCount = 0; tempVariables = undefined; tempParameters = undefined; - var popFrame = enterNameScope() + let popFrame = enterNameScope() // When targeting ES6, emit arrow function natively in ES6 if (shouldEmitAsArrowFunction(node)) { @@ -4411,7 +4413,7 @@ module ts { write(" "); // Unwrap all type assertions. - var current = body; + let current = body; while (current.kind === SyntaxKind.TypeAssertionExpression) { current = (current).expression; } @@ -4424,10 +4426,10 @@ module ts { scopeEmitStart(node); increaseIndent(); - var outPos = writer.getTextPos(); + let outPos = writer.getTextPos(); emitDetachedComments(node.body); emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; + let preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); // If we didn't have to emit any preamble code, then attempt to keep the arrow @@ -4473,18 +4475,18 @@ module ts { write(" {"); scopeEmitStart(node); - var initialTextPos = writer.getTextPos(); + let initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedComments(body.statements); // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). - var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); + let startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); emitFunctionBodyPreamble(node); decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; + let preambleEmitted = writer.getTextPos() !== initialTextPos; if (preserveNewLines && !preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { for (let statement of body.statements) { @@ -4511,11 +4513,11 @@ module ts { function findInitialSuperCall(ctor: ConstructorDeclaration): ExpressionStatement { if (ctor.body) { - var statement = (ctor.body).statements[0]; + let statement = (ctor.body).statements[0]; if (statement && statement.kind === SyntaxKind.ExpressionStatement) { - var expr = (statement).expression; + let expr = (statement).expression; if (expr && expr.kind === SyntaxKind.CallExpression) { - var func = (expr).expression; + let func = (expr).expression; if (func && func.kind === SyntaxKind.SuperKeyword) { return statement; } @@ -4608,7 +4610,7 @@ module ts { emitTrailingComments(member); } else if (member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) { - var accessors = getAllAccessorDeclarations(node.members, member); + let accessors = getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); emitStart(member); @@ -4663,7 +4665,7 @@ module ts { write("var "); emitDeclarationName(node); write(" = (function ("); - var baseTypeNode = getClassBaseTypeNode(node); + let baseTypeNode = getClassBaseTypeNode(node); if (baseTypeNode) { write("_super"); } @@ -4713,14 +4715,14 @@ module ts { } function emitConstructorOfClass() { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; + let saveTempCount = tempCount; + let saveTempVariables = tempVariables; + let saveTempParameters = tempParameters; tempCount = 0; tempVariables = undefined; tempParameters = undefined; - var popFrame = enterNameScope(); + let popFrame = enterNameScope(); // Emit the constructor overload pinned comments forEach(node.members, member => { @@ -4729,7 +4731,7 @@ module ts { } }); - var ctor = getFirstConstructorWithBody(node); + let ctor = getFirstConstructorWithBody(node); if (ctor) { emitLeadingComments(ctor); } @@ -4744,11 +4746,12 @@ module ts { emitDetachedComments((ctor.body).statements); } emitCaptureThisForNodeIfNecessary(node); + let superCall: ExpressionStatement; if (ctor) { emitDefaultValueAssignments(ctor); emitRestParameter(ctor); if (baseTypeNode) { - var superCall = findInitialSuperCall(ctor); + superCall = findInitialSuperCall(ctor); if (superCall) { writeLine(); emit(superCall); @@ -4766,7 +4769,7 @@ module ts { } emitMemberAssignments(node, /*nonstatic*/0); if (ctor) { - var statements: Node[] = (ctor.body).statements; + let statements: Node[] = (ctor.body).statements; if (superCall) statements = statements.slice(1); emitLines(statements); } @@ -4796,7 +4799,7 @@ module ts { } function shouldEmitEnumDeclaration(node: EnumDeclaration) { - var isConstEnum = isConst(node); + let isConstEnum = isConst(node); return !isConstEnum || compilerOptions.preserveConstEnums; } @@ -4849,7 +4852,7 @@ module ts { } function emitEnumMember(node: EnumMember) { - var enumParent = node.parent; + let enumParent = node.parent; emitStart(node); write(resolver.getGeneratedNameForNode(enumParent)); write("["); @@ -4866,7 +4869,7 @@ module ts { function writeEnumMemberDeclarationValue(member: EnumMember) { if (!member.initializer || isConst(member.parent)) { - var value = resolver.getConstantValue(member); + let value = resolver.getConstantValue(member); if (value !== undefined) { write(value.toString()); return; @@ -4883,7 +4886,7 @@ module ts { function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration { if (moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + let recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } @@ -4894,7 +4897,7 @@ module ts { function emitModuleDeclaration(node: ModuleDeclaration) { // Emit only if this module is non-ambient. - var shouldEmit = shouldEmitModuleDeclaration(node); + let shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { return emitPinnedOrTripleSlashComments(node); @@ -4913,11 +4916,11 @@ module ts { emitEnd(node.name); write(") "); if (node.body.kind === SyntaxKind.ModuleBlock) { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; + let saveTempCount = tempCount; + let saveTempVariables = tempVariables; tempCount = 0; tempVariables = undefined; - var popFrame = enterNameScope(); + let popFrame = enterNameScope(); emit(node.body); @@ -4934,7 +4937,7 @@ module ts { emit(node.body); decreaseIndent(); writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + let moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(SyntaxKind.CloseBraceToken, moduleBlock.statements.end); scopeEmitEnd(); } @@ -4968,14 +4971,14 @@ module ts { } function emitImportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration) { - var info = getExternalImportInfo(node); + let info = getExternalImportInfo(node); if (info) { - var declarationNode = info.declarationNode; - var namedImports = info.namedImports; + let declarationNode = info.declarationNode; + let namedImports = info.namedImports; if (compilerOptions.module !== ModuleKind.AMD) { emitLeadingComments(node); emitStart(node); - var moduleName = getExternalModuleName(node); + let moduleName = getExternalModuleName(node); if (declarationNode) { if (!(declarationNode.flags & NodeFlags.Export)) write("var "); emitModuleMemberName(declarationNode); @@ -5032,7 +5035,7 @@ module ts { function emitExportDeclaration(node: ExportDeclaration) { if (node.moduleSpecifier) { emitStart(node); - var generatedName = resolver.getGeneratedNameForNode(node); + let generatedName = resolver.getGeneratedNameForNode(node); if (compilerOptions.module !== ModuleKind.AMD) { write("var "); write(generatedName); @@ -5057,7 +5060,7 @@ module ts { } else { // export * - var tempName = createTempVariable(node).text; + let tempName = createTempVariable(node).text; writeLine(); write("for (var " + tempName + " in " + generatedName + ") if (!"); emitContainingModuleName(node); @@ -5079,7 +5082,7 @@ module ts { } } else if (node.kind === SyntaxKind.ImportDeclaration) { - var importClause = (node).importClause; + let importClause = (node).importClause; if (importClause) { if (importClause.name) { return { @@ -5122,7 +5125,7 @@ module ts { if (specifier.name.text === "default") { exportDefault = exportDefault || specifier; } - var name = (specifier.propertyName || specifier.name).text; + let name = (specifier.propertyName || specifier.name).text; (exportSpecifiers[name] || (exportSpecifiers[name] = [])).push(specifier); }); } @@ -5135,7 +5138,7 @@ module ts { } } else { - var info = createExternalImportInfo(node); + let info = createExternalImportInfo(node); if (info) { if ((!info.declarationNode && !info.namedImports) || resolver.isReferencedAliasDeclaration(node)) { externalImports.push(info); @@ -5186,7 +5189,7 @@ module ts { write("[\"require\", \"exports\""); forEach(externalImports, info => { write(", "); - var moduleName = getExternalModuleName(info.rootNode); + let moduleName = getExternalModuleName(info.rootNode); if (moduleName.kind === SyntaxKind.StringLiteral) { emitLiteral(moduleName); } @@ -5195,7 +5198,7 @@ module ts { } }); forEach(node.amdDependencies, amdDependency => { - var text = "\"" + amdDependency.path + "\""; + let text = "\"" + amdDependency.path + "\""; write(", "); write(text); }); @@ -5253,7 +5256,7 @@ module ts { } function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean): number { - for (var i = 0; i < statements.length; ++i) { + for (let i = 0; i < statements.length; ++i) { if (isPrologueDirective(statements[i])) { if (startWithNewLine || i > 0) { writeLine(); @@ -5274,7 +5277,7 @@ module ts { emitDetachedComments(node); // emit prologue directives prior to __extends - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); if (!extendsEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitExtends) { writeLine(); write("var __extends = this.__extends || function (d, b) {"); @@ -5322,7 +5325,7 @@ module ts { return emitPinnedOrTripleSlashComments(node); } - var emitComments = shouldEmitLeadingAndTrailingComments(node); + let emitComments = shouldEmitLeadingAndTrailingComments(node); if (emitComments) { emitLeadingComments(node); } @@ -5533,7 +5536,7 @@ module ts { function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - var leadingComments = getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + let leadingComments = getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -5548,7 +5551,7 @@ module ts { // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments if (node.parent) { if (node.parent.kind === SyntaxKind.SourceFile || node.pos !== node.parent.pos) { - var leadingComments: CommentRange[]; + let leadingComments: CommentRange[]; if (hasDetachedComments(node.pos)) { // get comments without detached comments leadingComments = getLeadingCommentsWithoutDetachedComments(); @@ -5563,7 +5566,7 @@ module ts { } function emitLeadingDeclarationComments(node: Node) { - var leadingComments = getLeadingCommentsToEmit(node); + let leadingComments = getLeadingCommentsToEmit(node); emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); @@ -5573,7 +5576,7 @@ module ts { // Emit the trailing comments only if the parent's end doesn't match if (node.parent) { if (node.parent.kind === SyntaxKind.SourceFile || node.end !== node.parent.end) { - var trailingComments = getTrailingCommentRanges(currentSourceFile.text, node.end); + let trailingComments = getTrailingCommentRanges(currentSourceFile.text, node.end); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); } @@ -5581,7 +5584,7 @@ module ts { } function emitLeadingCommentsOfLocalPosition(pos: number) { - var leadingComments: CommentRange[]; + let leadingComments: CommentRange[]; if (hasDetachedComments(pos)) { // get comments without detached comments leadingComments = getLeadingCommentsWithoutDetachedComments(); @@ -5596,15 +5599,15 @@ module ts { } function emitDetachedCommentsAtPosition(node: TextRange) { - var leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos); + let leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos); if (leadingComments) { - var detachedComments: CommentRange[] = []; - var lastComment: CommentRange; + let detachedComments: CommentRange[] = []; + let lastComment: CommentRange; forEach(leadingComments, comment => { if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + let lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + let commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This @@ -5622,13 +5625,13 @@ module 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. - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); - var nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos)); + let lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + let nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + let currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); } @@ -5642,7 +5645,7 @@ module ts { /** Emits /// or pinned which is comment starting with /*! comments */ function emitPinnedOrTripleSlashComments(node: Node) { - var pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment); + let pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment); function isPinnedOrTripleSlashComment(comment: CommentRange) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) { @@ -5665,13 +5668,13 @@ module ts { } function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile) { - var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); + let 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) { - var declarationOutput = emitDeclarationResult.referencePathsOutput; + let declarationOutput = emitDeclarationResult.referencePathsOutput; // apply additions - var appliedSyncOutputPos = 0; + let appliedSyncOutputPos = 0; forEach(emitDeclarationResult.aliasDeclarationEmitInfo, aliasEmitInfo => { if (aliasEmitInfo.asynchronousOutput) { declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); From 35040b9a8514df9cc209398de29fa0757a38541f Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 13:11:17 -0700 Subject: [PATCH 18/19] Use 'let' in the services code. --- src/services/breakpoints.ts | 38 +- src/services/navigateTo.ts | 38 +- src/services/navigationBar.ts | 58 +- src/services/outliningElementsCollector.ts | 40 +- src/services/patternMatcher.ts | 134 +-- src/services/services.ts | 910 +++++++++++---------- src/services/signatureHelp.ts | 136 +-- src/services/utilities.ts | 76 +- 8 files changed, 719 insertions(+), 711 deletions(-) diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 1f87ae40745..c56ea72cd66 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -13,13 +13,13 @@ module ts.BreakpointResolver { return undefined; } - var tokenAtLocation = getTokenAtPosition(sourceFile, position); - var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + let tokenAtLocation = getTokenAtPosition(sourceFile, position); + let lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { // Get previous token if the token is returned starts on new line - // eg: var x =10; |--- cursor is here - // var y = 10; - // token at position will return var keyword on second line as the token but we would like to use + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line tokenAtLocation = findPrecedingToken(tokenAtLocation.pos, sourceFile); @@ -275,9 +275,9 @@ module ts.BreakpointResolver { return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.parent.kind === SyntaxKind.VariableStatement; - var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === SyntaxKind.ForStatement && contains(((variableDeclaration.parent.parent).initializer).declarations, variableDeclaration); - var declarations = isParentVariableStatement + let isParentVariableStatement = variableDeclaration.parent.parent.kind === SyntaxKind.VariableStatement; + let isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === SyntaxKind.ForStatement && contains(((variableDeclaration.parent.parent).initializer).declarations, variableDeclaration); + let declarations = isParentVariableStatement ? (variableDeclaration.parent.parent).declarationList.declarations : isDeclarationOfForStatement ? ((variableDeclaration.parent.parent).initializer).declarations @@ -287,12 +287,12 @@ module ts.BreakpointResolver { if (variableDeclaration.initializer || (variableDeclaration.flags & NodeFlags.Export)) { if (declarations && declarations[0] === variableDeclaration) { if (isParentVariableStatement) { - // First declaration - include var keyword + // First declaration - include let keyword return textSpan(variableDeclaration.parent, variableDeclaration); } else { Debug.assert(isDeclarationOfForStatement); - // Include var keyword from for statement declarations in the span + // Include let keyword from for statement declarations in the span return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); } } @@ -303,7 +303,7 @@ module ts.BreakpointResolver { } else if (declarations && declarations[0] !== variableDeclaration) { // If we cant set breakpoint on this declaration, set it on previous one - var indexOfCurrentDeclaration = indexOf(declarations, variableDeclaration); + let indexOfCurrentDeclaration = indexOf(declarations, variableDeclaration); return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]); } } @@ -319,8 +319,8 @@ module ts.BreakpointResolver { return textSpan(parameter); } else { - var functionDeclaration = parameter.parent; - var indexOfParameter = indexOf(functionDeclaration.parameters, parameter); + let functionDeclaration = parameter.parent; + let indexOfParameter = indexOf(functionDeclaration.parameters, parameter); if (indexOfParameter) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); @@ -353,7 +353,7 @@ module ts.BreakpointResolver { } function spanInFunctionBlock(block: Block): TextSpan { - var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + let nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); } @@ -387,7 +387,7 @@ module ts.BreakpointResolver { function spanInForStatement(forStatement: ForStatement): TextSpan { if (forStatement.initializer) { if (forStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { - var variableDeclarationList = forStatement.initializer; + let variableDeclarationList = forStatement.initializer; if (variableDeclarationList.declarations.length > 0) { return spanInNode(variableDeclarationList.declarations[0]); } @@ -409,11 +409,11 @@ module ts.BreakpointResolver { function spanInOpenBraceToken(node: Node): TextSpan { switch (node.parent.kind) { case SyntaxKind.EnumDeclaration: - var enumDeclaration = node.parent; + let enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); case SyntaxKind.ClassDeclaration: - var classDeclaration = node.parent; + let classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); case SyntaxKind.CaseBlock: @@ -449,8 +449,8 @@ module ts.BreakpointResolver { case SyntaxKind.CaseBlock: // breakpoint in last statement of the last clause - var caseBlock = node.parent; - var lastClause = caseBlock.clauses[caseBlock.clauses.length - 1]; + let caseBlock = node.parent; + let lastClause = caseBlock.clauses[caseBlock.clauses.length - 1]; if (lastClause) { return spanInNode(lastClause.statements[lastClause.statements.length - 1]); } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 7757a7acf3a..9871a447c05 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -2,21 +2,21 @@ module ts.NavigateTo { type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration }; export function getNavigateToItems(program: Program, cancellationToken: CancellationTokenObject, searchValue: string, maxResultCount: number): NavigateToItem[] { - var patternMatcher = createPatternMatcher(searchValue); - var rawItems: RawNavigateToItem[] = []; + let patternMatcher = createPatternMatcher(searchValue); + let rawItems: RawNavigateToItem[] = []; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] forEach(program.getSourceFiles(), sourceFile => { cancellationToken.throwIfCancellationRequested(); - var declarations = sourceFile.getNamedDeclarations(); + let declarations = sourceFile.getNamedDeclarations(); for (let declaration of declarations) { var name = getDeclarationName(declaration); if (name !== undefined) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); + let matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); if (!matches) { continue; @@ -25,7 +25,7 @@ module ts.NavigateTo { // It was a match! If the pattern has dots in it, then also see if hte // declaration container matches as well. if (patternMatcher.patternContainsDots) { - var containers = getContainers(declaration); + let containers = getContainers(declaration); if (!containers) { return undefined; } @@ -37,8 +37,8 @@ module ts.NavigateTo { } } - var fileName = sourceFile.fileName; - var matchKind = bestMatchKind(matches); + let fileName = sourceFile.fileName; + let matchKind = bestMatchKind(matches); rawItems.push({ name, fileName, matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration }); } } @@ -49,7 +49,7 @@ module ts.NavigateTo { rawItems = rawItems.slice(0, maxResultCount); } - var items = map(rawItems, createNavigateToItem); + let items = map(rawItems, createNavigateToItem); return items; @@ -67,13 +67,13 @@ module ts.NavigateTo { } function getDeclarationName(declaration: Declaration): string { - var result = getTextOfIdentifierOrLiteral(declaration.name); + let result = getTextOfIdentifierOrLiteral(declaration.name); if (result !== undefined) { return result; } if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - var expr = (declaration.name).expression; + let expr = (declaration.name).expression; if (expr.kind === SyntaxKind.PropertyAccessExpression) { return (expr).name.text; } @@ -97,7 +97,7 @@ module ts.NavigateTo { function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) { if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); + let text = getTextOfIdentifierOrLiteral(declaration.name); if (text !== undefined) { containers.unshift(text); } @@ -117,7 +117,7 @@ module ts.NavigateTo { // // [X.Y.Z]() { } function tryAddComputedPropertyName(expression: Expression, containers: string[], includeLastPortion: boolean): boolean { - var text = getTextOfIdentifierOrLiteral(expression); + let text = getTextOfIdentifierOrLiteral(expression); if (text !== undefined) { if (includeLastPortion) { containers.unshift(text); @@ -126,7 +126,7 @@ module ts.NavigateTo { } if (expression.kind === SyntaxKind.PropertyAccessExpression) { - var propertyAccess = expression; + let propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } @@ -138,7 +138,7 @@ module ts.NavigateTo { } function getContainers(declaration: Declaration) { - var containers: string[] = []; + let containers: string[] = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. @@ -164,10 +164,10 @@ module ts.NavigateTo { function bestMatchKind(matches: PatternMatch[]) { Debug.assert(matches.length > 0); - var bestMatchKind = PatternMatchKind.camelCase; + let bestMatchKind = PatternMatchKind.camelCase; for (let match of matches) { - var kind = match.kind; + let kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; } @@ -177,7 +177,7 @@ module ts.NavigateTo { } // This means "compare in a case insensitive manner." - var baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" }; + let baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" }; function compareNavigateToItems(i1: RawNavigateToItem, i2: RawNavigateToItem) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. // Right now we just sort by kind first, and then by name of the item. @@ -189,8 +189,8 @@ module ts.NavigateTo { } function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { - var declaration = rawItem.declaration; - var container = getContainerNode(declaration); + let declaration = rawItem.declaration; + let container = getContainerNode(declaration); return { name: rawItem.name, kind: getNodeKind(declaration), diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 1f67fef5e71..06eaa481dfb 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -4,16 +4,16 @@ module ts.NavigationBar { export function getNavigationBarItems(sourceFile: SourceFile): ts.NavigationBarItem[] { // If the source file has any child items, then it included in the tree // and takes lexical ownership of all other top-level items. - var hasGlobalNode = false; + let hasGlobalNode = false; return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); function getIndent(node: Node): number { // If we have a global node in the tree, // then it adds an extra layer of depth to all subnodes. - var indent = hasGlobalNode ? 1 : 0; + let indent = hasGlobalNode ? 1 : 0; - var current = node.parent; + let current = node.parent; while (current) { switch (current.kind) { case SyntaxKind.ModuleDeclaration: @@ -39,7 +39,7 @@ module ts.NavigationBar { } function getChildNodes(nodes: Node[]): Node[] { - var childNodes: Node[] = []; + let childNodes: Node[] = []; function visit(node: Node) { switch (node.kind) { @@ -60,7 +60,7 @@ module ts.NavigationBar { break; case SyntaxKind.ImportDeclaration: - var importClause = (node).importClause; + let importClause = (node).importClause; if (importClause) { // Handle default import case e.g.: // import d from "mod"; @@ -102,8 +102,8 @@ module ts.NavigationBar { } } - //for (var i = 0, n = nodes.length; i < n; i++) { - // var node = nodes[i]; + //for (let i = 0, n = nodes.length; i < n; i++) { + // let node = nodes[i]; // if (node.kind === SyntaxKind.ClassDeclaration || // node.kind === SyntaxKind.EnumDeclaration || @@ -122,7 +122,7 @@ module ts.NavigationBar { } function getTopLevelNodes(node: SourceFile): Node[] { - var topLevelNodes: Node[] = []; + let topLevelNodes: Node[] = []; topLevelNodes.push(node); addTopLevelNodes(node.statements, topLevelNodes); @@ -159,13 +159,13 @@ module ts.NavigationBar { break; case SyntaxKind.ModuleDeclaration: - var moduleDeclaration = node; + let moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes((getInnermostModule(moduleDeclaration).body).statements, topLevelNodes); break; case SyntaxKind.FunctionDeclaration: - var functionDeclaration = node; + let functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); addTopLevelNodes((functionDeclaration.body).statements, topLevelNodes); @@ -199,17 +199,17 @@ module ts.NavigationBar { } function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] { - var items: ts.NavigationBarItem[] = []; + let items: ts.NavigationBarItem[] = []; - var keyToItem: Map = {}; + let keyToItem: Map = {}; for (let child of nodes) { - var item = createItem(child); + let item = createItem(child); if (item !== undefined) { if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; + let key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; + let itemWithSameName = keyToItem[key]; if (itemWithSameName) { // We had an item with the same name. Merge these items together. merge(itemWithSameName, item); @@ -293,8 +293,8 @@ module ts.NavigationBar { case SyntaxKind.VariableDeclaration: case SyntaxKind.BindingElement: - var variableDeclarationNode: Node; - var name: Node; + let variableDeclarationNode: Node; + let name: Node; if (node.kind === SyntaxKind.BindingElement) { name = (node).name; @@ -391,7 +391,7 @@ module ts.NavigationBar { } // Otherwise, we need to aggregate each identifier to build up the qualified name. - var result: string[] = []; + let result: string[] = []; result.push(moduleDeclaration.name.text); @@ -405,9 +405,9 @@ module ts.NavigationBar { } function createModuleItem(node: ModuleDeclaration): NavigationBarItem { - var moduleName = getModuleName(node); + let moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes((getInnermostModule(node).body).statements), createChildItem); + let childItems = getItemsWorker(getChildNodes((getInnermostModule(node).body).statements), createChildItem); return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, @@ -419,7 +419,7 @@ module ts.NavigationBar { function createFunctionItem(node: FunctionDeclaration) { if (node.name && node.body && node.body.kind === SyntaxKind.Block) { - var childItems = getItemsWorker(sortNodes((node.body).statements), createChildItem); + let childItems = getItemsWorker(sortNodes((node.body).statements), createChildItem); return getNavigationBarItem(node.name.text, ts.ScriptElementKind.functionElement, @@ -433,14 +433,14 @@ module ts.NavigationBar { } function createSourceFileItem(node: SourceFile): ts.NavigationBarItem { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); + let childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); if (childItems === undefined || childItems.length === 0) { return undefined; } hasGlobalNode = true; - var rootName = isExternalModule(node) + let rootName = isExternalModule(node) ? "\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(node.fileName)))) + "\"" : "" @@ -457,22 +457,22 @@ module ts.NavigationBar { return undefined; } - var childItems: NavigationBarItem[]; + let childItems: NavigationBarItem[]; if (node.members) { - var constructor = forEach(node.members, member => { + let constructor = forEach(node.members, member => { return member.kind === SyntaxKind.Constructor && member; }); // Add the constructor parameters in as children of the class (for property parameters). // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that // are not properties will be filtered out later by createChildItem. - var nodes: Node[] = removeDynamicallyNamedProperties(node); + let nodes: Node[] = removeDynamicallyNamedProperties(node); if (constructor) { nodes.push.apply(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name))); } - var childItems = getItemsWorker(sortNodes(nodes), createChildItem); + childItems = getItemsWorker(sortNodes(nodes), createChildItem); } return getNavigationBarItem( @@ -485,7 +485,7 @@ module ts.NavigationBar { } function createEnumItem(node: EnumDeclaration): ts.NavigationBarItem { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); + let childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); return getNavigationBarItem( node.name.text, ts.ScriptElementKind.enumElement, @@ -496,7 +496,7 @@ module ts.NavigationBar { } function createIterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); + let childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); return getNavigationBarItem( node.name.text, ts.ScriptElementKind.interfaceElement, diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index eee537bbebb..4c9dcedc7a4 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -16,12 +16,12 @@ module ts { export module OutliningElementsCollector { export function collectElements(sourceFile: SourceFile): OutliningSpan[] { - var elements: OutliningSpan[] = []; - var collapseText = "..."; + let elements: OutliningSpan[] = []; + let collapseText = "..."; function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) { if (hintSpanNode && startElement && endElement) { - var span: OutliningSpan = { + let span: OutliningSpan = { textSpan: createTextSpanFromBounds(startElement.pos, endElement.end), hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), bannerText: collapseText, @@ -35,8 +35,8 @@ module ts { return isFunctionBlock(node) && node.parent.kind !== SyntaxKind.ArrowFunction; } - var depth = 0; - var maxDepth = 20; + let depth = 0; + let maxDepth = 20; function walk(n: Node): void { if (depth > maxDepth) { return; @@ -44,9 +44,9 @@ module ts { switch (n.kind) { case SyntaxKind.Block: if (!isFunctionBlock(n)) { - var parent = n.parent; - var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); - var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); + let parent = n.parent; + let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); + let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); // Check if the block is standalone, or 'attached' to some parent statement. // If the latter, we want to collaps the block, but consider its hint span @@ -66,13 +66,13 @@ module ts { if (parent.kind === SyntaxKind.TryStatement) { // Could be the try-block, or the finally-block. - var tryStatement = parent; + let tryStatement = parent; if (tryStatement.tryBlock === n) { addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { - var finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); + let finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); if (finallyKeyword) { addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); break; @@ -84,7 +84,7 @@ module ts { // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - var span = createTextSpanFromBounds(n.getStart(), n.end); + let span = createTextSpanFromBounds(n.getStart(), n.end); elements.push({ textSpan: span, hintSpan: span, @@ -95,23 +95,25 @@ module ts { } // Fallthrough. - case SyntaxKind.ModuleBlock: - var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); - var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); + case SyntaxKind.ModuleBlock: { + let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); + let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); break; + } case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.CaseBlock: - var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); - var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); + case SyntaxKind.CaseBlock: { + let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); + let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); break; + } case SyntaxKind.ArrayLiteralExpression: - var openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile); - var closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile); + let openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile); + let closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); break; } diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index f7874519334..61642552cab 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -112,13 +112,13 @@ module ts { // we see the name of a module that is used everywhere, or the name of an overload). As // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. - var stringToWordSpans: Map = {}; + let stringToWordSpans: Map = {}; pattern = pattern.trim(); - var fullPatternSegment = createSegment(pattern); - var dotSeparatedSegments = pattern.split(".").map(p => createSegment(p.trim())); - var invalidPattern = dotSeparatedSegments.length === 0 || forEach(dotSeparatedSegments, segmentIsInvalid); + let fullPatternSegment = createSegment(pattern); + let dotSeparatedSegments = pattern.split(".").map(p => createSegment(p.trim())); + let invalidPattern = dotSeparatedSegments.length === 0 || forEach(dotSeparatedSegments, segmentIsInvalid); return { getMatches, @@ -147,7 +147,7 @@ module ts { // First, check that the last part of the dot separated pattern matches the name of the // candidate. If not, then there's no point in proceeding and doing the more // expensive work. - var candidateMatch = matchSegment(candidate, lastOrUndefined(dotSeparatedSegments)); + let candidateMatch = matchSegment(candidate, lastOrUndefined(dotSeparatedSegments)); if (!candidateMatch) { return undefined; } @@ -164,16 +164,16 @@ module ts { // So far so good. Now break up the container for the candidate and check if all // the dotted parts match up correctly. - var totalMatch = candidateMatch; + let totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; + for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { - var segment = dotSeparatedSegments[i]; - var containerName = candidateContainers[j]; + let segment = dotSeparatedSegments[i]; + let containerName = candidateContainers[j]; - var containerMatch = matchSegment(containerName, segment); + let containerMatch = matchSegment(containerName, segment); if (!containerMatch) { // This container didn't match the pattern piece. So there's no match at all. return undefined; @@ -196,7 +196,7 @@ module ts { } function matchTextChunk(candidate: string, chunk: TextChunk, punctuationStripped: boolean): PatternMatch { - var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + let index = indexOfIgnoringCase(candidate, chunk.textLowerCase); if (index === 0) { if (chunk.text.length === candidate.length) { // a) Check if the part matches the candidate entirely, in an case insensitive or @@ -210,7 +210,7 @@ module ts { } } - var isLowercase = chunk.isLowerCase; + let isLowercase = chunk.isLowerCase; if (isLowercase) { if (index > 0) { // c) If the part is entirely lowercase, then check if it is contained anywhere in the @@ -220,7 +220,7 @@ module ts { // Note: We only have a substring match if the lowercase part is prefix match of some // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). - var wordSpans = getWordSpans(candidate); + let wordSpans = getWordSpans(candidate); for (let span of wordSpans) { if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, @@ -241,8 +241,8 @@ module ts { if (!isLowercase) { // e) If the part was not entirely lowercase, then attempt a camel cased match as well. if (chunk.characterSpans.length > 0) { - var candidateParts = getWordSpans(candidate); - var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false); + let candidateParts = getWordSpans(candidate); + let camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false); if (camelCaseWeight !== undefined) { return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight); } @@ -273,8 +273,8 @@ module ts { } function containsSpaceOrAsterisk(text: string): boolean { - for (var i = 0; i < text.length; i++) { - var ch = text.charCodeAt(i); + for (let i = 0; i < text.length; i++) { + let ch = text.charCodeAt(i); if (ch === CharacterCodes.space || ch === CharacterCodes.asterisk) { return true; } @@ -292,7 +292,7 @@ module ts { // Note: if the segment contains a space or an asterisk then we must assume that it's a // multi-word segment. if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) { - var match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false); + let match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false); if (match) { return [match]; } @@ -335,12 +335,12 @@ module ts { // // Only if all words have some sort of match is the pattern considered matched. - var subWordTextChunks = segment.subWordTextChunks; - var matches: PatternMatch[] = undefined; + let subWordTextChunks = segment.subWordTextChunks; + let matches: PatternMatch[] = undefined; for (let subWordTextChunk of subWordTextChunks) { // Try to match the candidate with this word - var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); + let result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); if (!result) { return undefined; } @@ -353,8 +353,8 @@ module ts { } function partStartsWith(candidate: string, candidateSpan: TextSpan, pattern: string, ignoreCase: boolean, patternSpan?: TextSpan): boolean { - var patternPartStart = patternSpan ? patternSpan.start : 0; - var patternPartLength = patternSpan ? patternSpan.length : pattern.length; + let patternPartStart = patternSpan ? patternSpan.start : 0; + let patternPartLength = patternSpan ? patternSpan.length : pattern.length; if (patternPartLength > candidateSpan.length) { // Pattern part is longer than the candidate part. There can never be a match. @@ -362,18 +362,18 @@ module ts { } if (ignoreCase) { - for (var i = 0; i < patternPartLength; i++) { - var ch1 = pattern.charCodeAt(patternPartStart + i); - var ch2 = candidate.charCodeAt(candidateSpan.start + i); + for (let i = 0; i < patternPartLength; i++) { + let ch1 = pattern.charCodeAt(patternPartStart + i); + let ch2 = candidate.charCodeAt(candidateSpan.start + i); if (toLowerCase(ch1) !== toLowerCase(ch2)) { return false; } } } else { - for (var i = 0; i < patternPartLength; i++) { - var ch1 = pattern.charCodeAt(patternPartStart + i); - var ch2 = candidate.charCodeAt(candidateSpan.start + i); + for (let i = 0; i < patternPartLength; i++) { + let ch1 = pattern.charCodeAt(patternPartStart + i); + let ch2 = candidate.charCodeAt(candidateSpan.start + i); if (ch1 !== ch2) { return false; } @@ -384,23 +384,23 @@ module ts { } function tryCamelCaseMatch(candidate: string, candidateParts: TextSpan[], chunk: TextChunk, ignoreCase: boolean): number { - var chunkCharacterSpans = chunk.characterSpans; + let chunkCharacterSpans = chunk.characterSpans; // Note: we may have more pattern parts than candidate parts. This is because multiple // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U // and I will both match in UI. - var currentCandidate = 0; - var currentChunkSpan = 0; - var firstMatch: number = undefined; - var contiguous: boolean = undefined; + let currentCandidate = 0; + let currentChunkSpan = 0; + let firstMatch: number = undefined; + let contiguous: boolean = undefined; while (true) { // Let's consider our termination cases if (currentChunkSpan === chunkCharacterSpans.length) { // We did match! We shall assign a weight to this - var weight = 0; + let weight = 0; // Was this contiguous? if (contiguous) { @@ -419,15 +419,15 @@ module ts { return undefined; } - var candidatePart = candidateParts[currentCandidate]; - var gotOneMatchThisCandidate = false; + let candidatePart = candidateParts[currentCandidate]; + let gotOneMatchThisCandidate = false; // Consider the case of matching SiUI against SimpleUIElement. The candidate parts // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to // still keep matching pattern parts against that candidate part. for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { - var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + let chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; if (gotOneMatchThisCandidate) { // We've already gotten one pattern part match in this candidate. We will @@ -537,7 +537,7 @@ module ts { // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. - var str = String.fromCharCode(ch); + let str = String.fromCharCode(ch); return str === str.toUpperCase(); } @@ -554,12 +554,12 @@ module ts { // TODO: find a way to determine this for any unicode characters in a // non-allocating manner. - var str = String.fromCharCode(ch); + let str = String.fromCharCode(ch); return str === str.toLowerCase(); } function containsUpperCaseLetter(string: string): boolean { - for (var i = 0, n = string.length; i < n; i++) { + for (let i = 0, n = string.length; i < n; i++) { if (isUpperCaseLetter(string.charCodeAt(i))) { return true; } @@ -569,7 +569,7 @@ module ts { } function startsWith(string: string, search: string) { - for (var i = 0, n = search.length; i < n; i++) { + for (let i = 0, n = search.length; i < n; i++) { if (string.charCodeAt(i) !== search.charCodeAt(i)) { return false; } @@ -580,7 +580,7 @@ module ts { // Assumes 'value' is already lowercase. function indexOfIgnoringCase(string: string, value: string): number { - for (var i = 0, n = string.length - value.length; i <= n; i++) { + for (let i = 0, n = string.length - value.length; i <= n; i++) { if (startsWithIgnoringCase(string, value, i)) { return i; } @@ -591,9 +591,9 @@ module ts { // Assumes 'value' is already lowercase. function startsWithIgnoringCase(string: string, value: string, start: number): boolean { - for (var i = 0, n = value.length; i < n; i++) { - var ch1 = toLowerCase(string.charCodeAt(i + start)); - var ch2 = value.charCodeAt(i); + for (let i = 0, n = value.length; i < n; i++) { + let ch1 = toLowerCase(string.charCodeAt(i + start)); + let ch2 = value.charCodeAt(i); if (ch1 !== ch2) { return false; @@ -628,12 +628,12 @@ module ts { } function breakPatternIntoTextChunks(pattern: string): TextChunk[] { - var result: TextChunk[] = []; - var wordStart = 0; - var wordLength = 0; + let result: TextChunk[] = []; + let wordStart = 0; + let wordLength = 0; - for (var i = 0; i < pattern.length; i++) { - var ch = pattern.charCodeAt(i); + for (let i = 0; i < pattern.length; i++) { + let ch = pattern.charCodeAt(i); if (isWordChar(ch)) { if (wordLength++ === 0) { wordStart = i; @@ -655,7 +655,7 @@ module ts { } function createTextChunk(text: string): TextChunk { - var textLowerCase = text.toLowerCase(); + let textLowerCase = text.toLowerCase(); return { text, textLowerCase, @@ -673,15 +673,15 @@ module ts { } function breakIntoSpans(identifier: string, word: boolean): TextSpan[] { - var result: TextSpan[] = []; + let result: TextSpan[] = []; - var wordStart = 0; - for (var i = 1, n = identifier.length; i < n; i++) { - var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); - var currentIsDigit = isDigit(identifier.charCodeAt(i)); + let wordStart = 0; + for (let i = 1, n = identifier.length; i < n; i++) { + let lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); + let currentIsDigit = isDigit(identifier.charCodeAt(i)); - var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); - var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); + let hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); + let hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || @@ -736,8 +736,8 @@ module ts { } function isAllPunctuation(identifier: string, start: number, end: number): boolean { - for (var i = start; i < end; i++) { - var ch = identifier.charCodeAt(i); + for (let i = start; i < end; i++) { + let ch = identifier.charCodeAt(i); // We don't consider _ or $ as punctuation as there may be things with that name. if (!charIsPunctuation(ch) || ch === CharacterCodes._ || ch === CharacterCodes.$) { @@ -758,8 +758,8 @@ module ts { // etc. if (index != wordStart && index + 1 < identifier.length) { - var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); - var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); + let currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + let nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); if (currentIsUpper && nextIsLower) { // We have a transition from an upper to a lower letter here. But we only @@ -770,7 +770,7 @@ module ts { // that follows. Note: this will make the following not split properly: // "HELLOthere". However, these sorts of names do not show up in .Net // programs. - for (var i = wordStart; i < index; i++) { + for (let i = wordStart; i < index; i++) { if (!isUpperCaseLetter(identifier.charCodeAt(i))) { return false; } @@ -785,8 +785,8 @@ module ts { } function transitionFromLowerToUpper(identifier: string, word: boolean, index: number): boolean { - var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); - var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + let lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); + let currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); // See if the casing indicates we're starting a new word. Note: if we're breaking on // words, then just seeing an upper case character isn't enough. Instead, it has to @@ -801,7 +801,7 @@ module ts { // on characters would be: A M // // We break the search string on characters. But we break the symbol name on words. - var transition = word + let transition = word ? (currentIsUpper && !lastIsUpper) : currentIsUpper; return transition; diff --git a/src/services/services.ts b/src/services/services.ts index b4c0ef2bbd8..1bf5f6336d4 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -12,7 +12,7 @@ module ts { /** The version of the language service API */ - export var servicesVersion = "0.4" + export let servicesVersion = "0.4" export interface Node { getSourceFile(): SourceFile; @@ -124,12 +124,12 @@ module ts { isLibFile: boolean } - var scanner: Scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true); + let scanner: Scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true); - var emptyArray: any[] = []; + let emptyArray: any[] = []; function createNode(kind: SyntaxKind, pos: number, end: number, flags: NodeFlags, parent?: Node): NodeObject { - var node = new (getNodeConstructor(kind))(); + let node = new (getNodeConstructor(kind))(); node.pos = pos; node.end = end; node.flags = flags; @@ -184,8 +184,8 @@ module ts { private addSyntheticNodes(nodes: Node[], pos: number, end: number): number { scanner.setTextPos(pos); while (pos < end) { - var token = scanner.scan(); - var textPos = scanner.getTextPos(); + let token = scanner.scan(); + let textPos = scanner.getTextPos(); nodes.push(createNode(token, pos, textPos, NodeFlags.Synthetic, this)); pos = textPos; } @@ -193,9 +193,9 @@ module ts { } private createSyntaxList(nodes: NodeArray): Node { - var list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, NodeFlags.Synthetic, this); + let list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, NodeFlags.Synthetic, this); list._children = []; - var pos = nodes.pos; + let pos = nodes.pos; for (let node of nodes) { if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); @@ -210,18 +210,19 @@ module ts { } private createChildren(sourceFile?: SourceFile) { + let children: Node[]; if (this.kind >= SyntaxKind.FirstNode) { scanner.setText((sourceFile || this.getSourceFile()).text); - var children: Node[] = []; - var pos = this.pos; - var processNode = (node: Node) => { + children = []; + let pos = this.pos; + let processNode = (node: Node) => { if (pos < node.pos) { pos = this.addSyntheticNodes(children, pos, node.pos); } children.push(node); pos = node.end; }; - var processNodes = (nodes: NodeArray) => { + let processNodes = (nodes: NodeArray) => { if (pos < nodes.pos) { pos = this.addSyntheticNodes(children, pos, nodes.pos); } @@ -253,7 +254,7 @@ module ts { } public getFirstToken(sourceFile?: SourceFile): Node { - var children = this.getChildren(); + let children = this.getChildren(); for (let child of children) { if (child.kind < SyntaxKind.FirstNode) { return child; @@ -264,9 +265,9 @@ module ts { } public getLastToken(sourceFile?: SourceFile): Node { - var children = this.getChildren(sourceFile); - for (var i = children.length - 1; i >= 0; i--) { - var child = children[i]; + let children = this.getChildren(sourceFile); + for (let i = children.length - 1; i >= 0; i--) { + let child = children[i]; if (child.kind < SyntaxKind.FirstNode) { return child; } @@ -312,8 +313,8 @@ module ts { } function getJsDocCommentsFromDeclarations(declarations: Declaration[], name: string, canUseParsedParamTagComments: boolean) { - var documentationComment = []; - var docComments = getJsDocCommentsSeparatedByNewLines(); + let documentationComment = []; + let docComments = getJsDocCommentsSeparatedByNewLines(); ts.forEach(docComments, docComment => { if (documentationComment.length) { documentationComment.push(lineBreakPart()); @@ -324,22 +325,22 @@ module ts { return documentationComment; function getJsDocCommentsSeparatedByNewLines() { - var paramTag = "@param"; - var jsDocCommentParts: SymbolDisplayPart[] = []; + let paramTag = "@param"; + let jsDocCommentParts: SymbolDisplayPart[] = []; ts.forEach(declarations, (declaration, indexOfDeclaration) => { // Make sure we are collecting doc comment from declaration once, // In case of union property there might be same declaration multiple times // which only varies in type parameter - // Eg. var a: Array | Array; a.length + // Eg. let a: Array | Array; a.length // The property length will have two declarations of property length coming // from Array - Array and Array if (indexOf(declarations, declaration) === indexOfDeclaration) { - var sourceFileOfDeclaration = getSourceFileOfNode(declaration); + let sourceFileOfDeclaration = getSourceFileOfNode(declaration); // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments if (canUseParsedParamTagComments && declaration.kind === SyntaxKind.Parameter) { ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), jsDocCommentTextRange => { - var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + let cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedParamJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment); } @@ -359,7 +360,7 @@ module ts { // Get the cleaned js doc comment text from the declaration ts.forEach(getJsDocCommentTextRange( declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => { - var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + let cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); } @@ -385,7 +386,7 @@ module ts { } for (; pos < end; pos++) { - var ch = sourceFile.text.charCodeAt(pos); + let ch = sourceFile.text.charCodeAt(pos); if (!isWhiteSpace(ch) || isLineBreak(ch)) { // Either found lineBreak or non whiteSpace return pos; @@ -422,19 +423,19 @@ module ts { } function getCleanedJsDocComment(pos: number, end: number, sourceFile: SourceFile) { - var spacesToRemoveAfterAsterisk: number; - var docComments: SymbolDisplayPart[] = []; - var blankLineCount = 0; - var isInParamTag = false; + let spacesToRemoveAfterAsterisk: number; + let docComments: SymbolDisplayPart[] = []; + let blankLineCount = 0; + let isInParamTag = false; while (pos < end) { - var docCommentTextOfLine = ""; + let docCommentTextOfLine = ""; // First consume leading white space pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); // If the comment starts with '*' consume the spaces on this line if (pos < end && sourceFile.text.charCodeAt(pos) === CharacterCodes.asterisk) { - var lineStartPos = pos + 1; + let lineStartPos = pos + 1; pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); // Set the spaces to remove after asterisk as margin if not already set @@ -448,7 +449,7 @@ module ts { // Analyse text on this line while (pos < end && !isLineBreak(sourceFile.text.charCodeAt(pos))) { - var ch = sourceFile.text.charAt(pos); + let ch = sourceFile.text.charAt(pos); if (ch === "@") { // If it is @param tag if (isParamTag(pos, end, sourceFile)) { @@ -486,12 +487,12 @@ module ts { } function getCleanedParamJsDocComment(pos: number, end: number, sourceFile: SourceFile) { - var paramHelpStringMargin: number; - var paramDocComments: SymbolDisplayPart[] = []; + let paramHelpStringMargin: number; + let paramDocComments: SymbolDisplayPart[] = []; while (pos < end) { if (isParamTag(pos, end, sourceFile)) { - var blankLineCount = 0; - var recordedParamTag = false; + let blankLineCount = 0; + let recordedParamTag = false; // Consume leading spaces pos = consumeWhiteSpaces(pos + paramTag.length); if (pos >= end) { @@ -501,8 +502,8 @@ module ts { // Ignore type expression if (sourceFile.text.charCodeAt(pos) === CharacterCodes.openBrace) { pos++; - for (var curlies = 1; pos < end; pos++) { - var charCode = sourceFile.text.charCodeAt(pos); + for (let curlies = 1; pos < end; pos++) { + let charCode = sourceFile.text.charCodeAt(pos); // { character means we need to find another } to match the found one if (charCode === CharacterCodes.openBrace) { @@ -545,10 +546,10 @@ module ts { break; } - var paramHelpString = ""; - var firstLineParamHelpStringPos = pos; + let paramHelpString = ""; + let firstLineParamHelpStringPos = pos; while (pos < end) { - var ch = sourceFile.text.charCodeAt(pos); + let ch = sourceFile.text.charCodeAt(pos); // at line break, set this comment line text and go to next line if (isLineBreak(ch)) { @@ -617,15 +618,15 @@ module ts { } // Now consume white spaces max - var startOfLinePos = pos; + let startOfLinePos = pos; pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); if (pos >= end) { return; } - var consumedSpaces = pos - startOfLinePos; + let consumedSpaces = pos - startOfLinePos; if (consumedSpaces < paramHelpStringMargin) { - var ch = sourceFile.text.charCodeAt(pos); + let ch = sourceFile.text.charCodeAt(pos); if (ch === CharacterCodes.asterisk) { // Consume more spaces after asterisk pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); @@ -765,18 +766,18 @@ module ts { public getNamedDeclarations() { if (!this.namedDeclarations) { - var sourceFile = this; - var namedDeclarations: Declaration[] = []; + let sourceFile = this; + let namedDeclarations: Declaration[] = []; forEachChild(sourceFile, function visit(node: Node): void { switch (node.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - var functionDeclaration = node; + let functionDeclaration = node; if (functionDeclaration.name && functionDeclaration.name.getFullWidth() > 0) { - var lastDeclaration = namedDeclarations.length > 0 ? + let lastDeclaration = namedDeclarations.length > 0 ? namedDeclarations[namedDeclarations.length - 1] : undefined; @@ -856,7 +857,7 @@ module ts { break; case SyntaxKind.ImportDeclaration: - var importClause = (node).importClause; + let importClause = (node).importClause; if (importClause) { // Handle default import case e.g.: // import d from "mod"; @@ -1324,7 +1325,7 @@ module ts { static enumElement = "enum"; // Inside module and script only - // var v = .. + // let v = .. static variableElement = "var"; // Inside function @@ -1468,7 +1469,7 @@ module ts { } // If the parent is not sourceFile or module block it is local variable - for (var parent = declaration.parent; !isFunctionBlock(parent); parent = parent.parent) { + for (let parent = declaration.parent; !isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block if (parent.kind === SyntaxKind.SourceFile || parent.kind === SyntaxKind.ModuleBlock) { return false; @@ -1520,7 +1521,7 @@ module ts { this.fileNameToEntry = {}; // Initialize the list with the root file names - var rootFileNames = host.getScriptFileNames(); + let rootFileNames = host.getScriptFileNames(); for (let fileName of rootFileNames) { this.createEntry(fileName); } @@ -1534,8 +1535,8 @@ module ts { } private createEntry(fileName: string) { - var entry: HostFileInformation; - var scriptSnapshot = this.host.getScriptSnapshot(fileName); + let entry: HostFileInformation; + let scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { entry = { hostFileName: fileName, @@ -1564,7 +1565,7 @@ module ts { } public getRootFileNames(): string[] { - var fileNames: string[] = []; + let fileNames: string[] = []; forEachKey(this.fileNameToEntry, key => { if (hasProperty(this.fileNameToEntry, key) && this.fileNameToEntry[key]) @@ -1575,12 +1576,12 @@ module ts { } public getVersion(fileName: string): string { - var file = this.getEntry(fileName); + let file = this.getEntry(fileName); return file && file.version; } public getScriptSnapshot(fileName: string): IScriptSnapshot { - var file = this.getEntry(fileName); + let file = this.getEntry(fileName); return file && file.scriptSnapshot; } } @@ -1597,14 +1598,14 @@ module ts { } public getCurrentSourceFile(fileName: string): SourceFile { - var scriptSnapshot = this.host.getScriptSnapshot(fileName); + let scriptSnapshot = this.host.getScriptSnapshot(fileName); if (!scriptSnapshot) { // The host does not know about this file. throw new Error("Could not find file: '" + fileName + "'."); } - var version = this.host.getScriptVersion(fileName); - var sourceFile: SourceFile; + let version = this.host.getScriptVersion(fileName); + let sourceFile: SourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it @@ -1612,7 +1613,7 @@ module ts { } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. - var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + let editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); } @@ -1634,14 +1635,14 @@ module ts { } export function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile { - var sourceFile = createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + let sourceFile = createSourceFile(fileName, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); setSourceFileFields(sourceFile, scriptSnapshot, version); // after full parsing we can use table with interned strings as name table sourceFile.nameTable = sourceFile.identifiers; return sourceFile; } - export var disableIncrementalParsing = false; + export let disableIncrementalParsing = false; export function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile { // If we were given a text change range, and our version or open-ness changed, then @@ -1650,7 +1651,7 @@ module ts { if (version !== sourceFile.version) { // Once incremental parsing is ready, then just call into this function. if (!disableIncrementalParsing) { - var newSourceFile = updateSourceFile(sourceFile, scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange, aggressiveChecks); + let newSourceFile = updateSourceFile(sourceFile, scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange, aggressiveChecks); setSourceFileFields(newSourceFile, scriptSnapshot, version); // after incremental parsing nameTable might not be up-to-date // drop it so it can be lazily recreated later @@ -1667,15 +1668,15 @@ module ts { export function createDocumentRegistry(): DocumentRegistry { // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. - var buckets: Map> = {}; + let buckets: Map> = {}; function getKeyFromCompilationSettings(settings: CompilerOptions): string { return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString() } function getBucketForCompilationSettings(settings: CompilerOptions, createIfMissing: boolean): Map { - var key = getKeyFromCompilationSettings(settings); - var bucket = lookUp(buckets, key); + let key = getKeyFromCompilationSettings(settings); + let bucket = lookUp(buckets, key); if (!bucket && createIfMissing) { buckets[key] = bucket = {}; } @@ -1683,11 +1684,11 @@ module ts { } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(name => name && name.charAt(0) === '_').map(name => { - var entries = lookUp(buckets, name); - var sourceFiles: { name: string; refCount: number; references: string[]; }[] = []; - for (var i in entries) { - var entry = entries[i]; + let bucketInfoArray = Object.keys(buckets).filter(name => name && name.charAt(0) === '_').map(name => { + let entries = lookUp(buckets, name); + let sourceFiles: { name: string; refCount: number; references: string[]; }[] = []; + for (let i in entries) { + let entry = entries[i]; sourceFiles.push({ name: i, refCount: entry.languageServiceRefCount, @@ -1718,13 +1719,13 @@ module ts { version: string, acquiring: boolean): SourceFile { - var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); - var entry = lookUp(bucket, fileName); + let bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); + let entry = lookUp(bucket, fileName); if (!entry) { Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents:*/ false); + let sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents:*/ false); bucket[fileName] = entry = { sourceFile: sourceFile, @@ -1755,10 +1756,10 @@ module ts { } function releaseDocument(fileName: string, compilationSettings: CompilerOptions): void { - var bucket = getBucketForCompilationSettings(compilationSettings, false); + let bucket = getBucketForCompilationSettings(compilationSettings, false); Debug.assert(bucket !== undefined); - var entry = lookUp(bucket, fileName); + let entry = lookUp(bucket, fileName); entry.languageServiceRefCount--; Debug.assert(entry.languageServiceRefCount >= 0); @@ -1776,18 +1777,18 @@ module ts { } export function preProcessFile(sourceText: string, readImportFiles = true): PreProcessedFileInfo { - var referencedFiles: FileReference[] = []; - var importedFiles: FileReference[] = []; - var isNoDefaultLib = false; + let referencedFiles: FileReference[] = []; + let importedFiles: FileReference[] = []; + let isNoDefaultLib = false; function processTripleSlashDirectives(): void { - var commentRanges = getLeadingCommentRanges(sourceText, 0); + let commentRanges = getLeadingCommentRanges(sourceText, 0); forEach(commentRanges, commentRange => { - var comment = sourceText.substring(commentRange.pos, commentRange.end); - var referencePathMatchResult = getFileReferenceFromReferencePath(comment, commentRange); + let comment = sourceText.substring(commentRange.pos, commentRange.end); + let referencePathMatchResult = getFileReferenceFromReferencePath(comment, commentRange); if (referencePathMatchResult) { isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var fileReference = referencePathMatchResult.fileReference; + let fileReference = referencePathMatchResult.fileReference; if (fileReference) { referencedFiles.push(fileReference); } @@ -1796,8 +1797,8 @@ module ts { } function recordModuleName() { - var importPath = scanner.getTokenValue(); - var pos = scanner.getTokenPos(); + let importPath = scanner.getTokenValue(); + let pos = scanner.getTokenPos(); importedFiles.push({ fileName: importPath, pos: pos, @@ -1807,7 +1808,7 @@ module ts { function processImport(): void { scanner.setText(sourceText); - var token = scanner.scan(); + let token = scanner.scan(); // Look for: // import "mod"; // import d from "mod" @@ -1972,7 +1973,7 @@ module ts { * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node: Node, labelName: string) { - for (var owner = node.parent; owner.kind === SyntaxKind.LabeledStatement; owner = owner.parent) { + for (let owner = node.parent; owner.kind === SyntaxKind.LabeledStatement; owner = owner.parent) { if ((owner).label.text === labelName) { return true; } @@ -2066,8 +2067,8 @@ module ts { return true; } else if (position === comment.end) { - var text = sourceFile.text; - var width = comment.end - comment.pos; + let text = sourceFile.text; + let width = comment.end - comment.pos; // is single line comment or just /* if (width <= 2 || text.charCodeAt(comment.pos + 1) === CharacterCodes.slash) { return true; @@ -2099,8 +2100,8 @@ module ts { } // A cache of completion entries for keywords, these do not change between sessions - var keywordCompletions: CompletionEntry[] = []; - for (var i = SyntaxKind.FirstKeyword; i <= SyntaxKind.LastKeyword; i++) { + let keywordCompletions: CompletionEntry[] = []; + for (let i = SyntaxKind.FirstKeyword; i <= SyntaxKind.LastKeyword; i++) { keywordCompletions.push({ name: tokenToString(i), kind: ScriptElementKind.keyword, @@ -2171,15 +2172,15 @@ module ts { } export function createLanguageService(host: LanguageServiceHost, documentRegistry: DocumentRegistry = createDocumentRegistry()): LanguageService { - var syntaxTreeCache: SyntaxTreeCache = new SyntaxTreeCache(host); - var ruleProvider: formatting.RulesProvider; - var program: Program; + let syntaxTreeCache: SyntaxTreeCache = new SyntaxTreeCache(host); + let ruleProvider: formatting.RulesProvider; + let program: Program; // this checker is used to answer all LS questions except errors - var typeInfoResolver: TypeChecker; - var useCaseSensitivefileNames = false; - var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); - var activeCompletionSession: CompletionSession; // The current active completion session, used to get the completion entry details + let typeInfoResolver: TypeChecker; + let useCaseSensitivefileNames = false; + let cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + let activeCompletionSession: CompletionSession; // The current active completion session, used to get the completion entry details // Check if the localized messages json is set, otherwise query the host for it if (!localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -2198,7 +2199,7 @@ module ts { function getValidSourceFile(fileName: string): SourceFile { fileName = normalizeSlashes(fileName); - var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); + let sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); if (!sourceFile) { throw new Error("Could not find file: '" + fileName + "'."); } @@ -2217,7 +2218,7 @@ module ts { function synchronizeHostData(): void { // Get a fresh cache of the host information - var hostCache = new HostCache(host); + let hostCache = new HostCache(host); // If the program is already up-to-date, we can reuse it if (programUpToDate()) { @@ -2230,12 +2231,12 @@ module ts { // the program points to old source files that have been invalidated because of // incremental parsing. - var oldSettings = program && program.getCompilerOptions(); - var newSettings = hostCache.compilationSettings(); - var changesInCompilationSettingsAffectSyntax = oldSettings && oldSettings.target !== newSettings.target; + let oldSettings = program && program.getCompilerOptions(); + let newSettings = hostCache.compilationSettings(); + let changesInCompilationSettingsAffectSyntax = oldSettings && oldSettings.target !== newSettings.target; // Now create a new compiler - var newProgram = createProgram(hostCache.getRootFileNames(), newSettings, { + let newProgram = createProgram(hostCache.getRootFileNames(), newSettings, { getSourceFile: getOrCreateSourceFile, getCancellationToken: () => cancellationToken, getCanonicalFileName: (fileName) => useCaseSensitivefileNames ? fileName : fileName.toLowerCase(), @@ -2249,9 +2250,9 @@ module ts { // Release any files we have acquired in the old program but are // not part of the new program. if (program) { - var oldSourceFiles = program.getSourceFiles(); + let oldSourceFiles = program.getSourceFiles(); for (let oldSourceFile of oldSourceFiles) { - var fileName = oldSourceFile.fileName; + let fileName = oldSourceFile.fileName; if (!newProgram.getSourceFile(fileName) || changesInCompilationSettingsAffectSyntax) { documentRegistry.releaseDocument(fileName, oldSettings); } @@ -2267,7 +2268,7 @@ module ts { // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache.getOrCreateEntry(fileName); + let hostFileInformation = hostCache.getOrCreateEntry(fileName); if (!hostFileInformation) { return undefined; } @@ -2277,7 +2278,7 @@ module ts { // can not be reused. we have to dump all syntax trees and create new ones. if (!changesInCompilationSettingsAffectSyntax) { // Check if the old program had this file already - var oldSourceFile = program && program.getSourceFile(fileName); + let oldSourceFile = program && program.getSourceFile(fileName); if (oldSourceFile) { // We already had a source file for this file name. Go to the registry to // ensure that we get the right up to date version of it. We need this to @@ -2321,7 +2322,7 @@ module ts { } // If number of files in the program do not match, it is not up-to-date - var rootFileNames = hostCache.getRootFileNames(); + let rootFileNames = hostCache.getRootFileNames(); if (program.getSourceFiles().length !== rootFileNames.length) { return false; } @@ -2376,18 +2377,18 @@ module ts { function getSemanticDiagnostics(fileName: string) { synchronizeHostData(); - var targetSourceFile = getValidSourceFile(fileName); + let targetSourceFile = getValidSourceFile(fileName); // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. - var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile); + let semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile); if (!program.getCompilerOptions().declaration) { return semanticDiagnostics; } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface - var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile); + let declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile); return semanticDiagnostics.concat(declarationDiagnostics); } @@ -2398,13 +2399,13 @@ module ts { /// Completion function getValidCompletionEntryDisplayName(symbol: Symbol, target: ScriptTarget): string { - var displayName = symbol.getName(); + let displayName = symbol.getName(); if (displayName && displayName.length > 0) { - var firstCharCode = displayName.charCodeAt(0); + let firstCharCode = displayName.charCodeAt(0); // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & SymbolFlags.Namespace) && (firstCharCode === CharacterCodes.singleQuote || firstCharCode === CharacterCodes.doubleQuote)) { // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { var x; } | // <= request completion here, "http" should not be there) + // (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there) return undefined; } @@ -2415,8 +2416,8 @@ module ts { displayName = displayName.substring(1, displayName.length - 1); } - var isValid = isIdentifierStart(displayName.charCodeAt(0), target); - for (var i = 1, n = displayName.length; isValid && i < n; i++) { + let isValid = isIdentifierStart(displayName.charCodeAt(0), target); + for (let i = 1, n = displayName.length; isValid && i < n; i++) { isValid = isIdentifierPart(displayName.charCodeAt(i), target); } @@ -2433,7 +2434,7 @@ module ts { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getValidCompletionEntryDisplayName(symbol, program.getCompilerOptions().target); + let displayName = getValidCompletionEntryDisplayName(symbol, program.getCompilerOptions().target); if (!displayName) { return undefined; } @@ -2452,16 +2453,16 @@ module ts { function getCompletionsAtPosition(fileName: string, position: number) { synchronizeHostData(); - var syntacticStart = new Date().getTime(); - var sourceFile = getValidSourceFile(fileName); + let syntacticStart = new Date().getTime(); + let sourceFile = getValidSourceFile(fileName); - var start = new Date().getTime(); - var currentToken = getTokenAtPosition(sourceFile, position); + let start = new Date().getTime(); + let currentToken = getTokenAtPosition(sourceFile, position); log("getCompletionsAtPosition: Get current token: " + (new Date().getTime() - start)); - var start = new Date().getTime(); + start = new Date().getTime(); // Completion not allowed inside comments, bail out if this is the case - var insideComment = isInsideComment(sourceFile, currentToken, position); + let insideComment = isInsideComment(sourceFile, currentToken, position); log("getCompletionsAtPosition: Is inside comment: " + (new Date().getTime() - start)); if (insideComment) { @@ -2471,14 +2472,14 @@ module ts { // The decision to provide completion depends on the previous token, so find it // Note: previousToken can be undefined if we are the beginning of the file - var start = new Date().getTime(); - var previousToken = findPrecedingToken(position, sourceFile); + start = new Date().getTime(); + let previousToken = findPrecedingToken(position, sourceFile); log("getCompletionsAtPosition: Get previous token 1: " + (new Date().getTime() - start)); // The caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier to the previous token if (previousToken && position <= previousToken.end && previousToken.kind === SyntaxKind.Identifier) { - var start = new Date().getTime(); + let start = new Date().getTime(); previousToken = findPrecedingToken(previousToken.pos, sourceFile); log("getCompletionsAtPosition: Get previous token 2: " + (new Date().getTime() - start)); } @@ -2491,8 +2492,8 @@ module ts { // Find the node where completion is requested on, in the case of a completion after a dot, it is the member access expression // other wise, it is a request for all visible symbols in the scope, and the node is the current location - var node: Node; - var isRightOfDot: boolean; + let node: Node; + let isRightOfDot: boolean; if (previousToken && previousToken.kind === SyntaxKind.DotToken && previousToken.parent.kind === SyntaxKind.PropertyAccessExpression) { node = (previousToken.parent).expression; isRightOfDot = true; @@ -2516,17 +2517,20 @@ module ts { }; log("getCompletionsAtPosition: Syntactic work: " + (new Date().getTime() - syntacticStart)); - var location = getTouchingPropertyName(sourceFile, position); + let location = getTouchingPropertyName(sourceFile, position); // Populate the completion list - var semanticStart = new Date().getTime(); + let semanticStart = new Date().getTime(); + let isMemberCompletion: boolean; + let isNewIdentifierLocation: boolean; + if (isRightOfDot) { // Right of dot member completion list - var symbols: Symbol[] = []; - var isMemberCompletion = true; - var isNewIdentifierLocation = false; + let symbols: Symbol[] = []; + isMemberCompletion = true; + isNewIdentifierLocation = false; if (node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression) { - var symbol = typeInfoResolver.getSymbolAtLocation(node); + let symbol = typeInfoResolver.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & SymbolFlags.Alias) { @@ -2543,7 +2547,7 @@ module ts { } } - var type = typeInfoResolver.getTypeAtLocation(node); + let type = typeInfoResolver.getTypeAtLocation(node); if (type) { // Filter private properties forEach(type.getApparentProperties(), symbol => { @@ -2556,21 +2560,21 @@ module ts { getCompletionEntriesFromSymbols(symbols, activeCompletionSession); } else { - var containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(previousToken); + let containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(previousToken); if (containingObjectLiteral) { // Object literal expression, look up possible property names from contextual type isMemberCompletion = true; isNewIdentifierLocation = true; - var contextualType = typeInfoResolver.getContextualType(containingObjectLiteral); + let contextualType = typeInfoResolver.getContextualType(containingObjectLiteral); if (!contextualType) { return undefined; } - var contextualTypeMembers = typeInfoResolver.getPropertiesOfType(contextualType); + let contextualTypeMembers = typeInfoResolver.getPropertiesOfType(contextualType); if (contextualTypeMembers && contextualTypeMembers.length > 0) { // Add filtered items to the completion list - var filteredMembers = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); + let filteredMembers = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties); getCompletionEntriesFromSymbols(filteredMembers, activeCompletionSession); } } @@ -2580,10 +2584,10 @@ module ts { isMemberCompletion = true; isNewIdentifierLocation = true; if (showCompletionsInImportsClause(previousToken)) { - var importDeclaration = getAncestor(previousToken, SyntaxKind.ImportDeclaration); + let importDeclaration = getAncestor(previousToken, SyntaxKind.ImportDeclaration); Debug.assert(importDeclaration !== undefined); - var exports = typeInfoResolver.getExportsOfExternalModule(importDeclaration); - var filteredExports = filterModuleExports(exports, importDeclaration); + let exports = typeInfoResolver.getExportsOfExternalModule(importDeclaration); + let filteredExports = filterModuleExports(exports, importDeclaration); getCompletionEntriesFromSymbols(filteredExports, activeCompletionSession); } } @@ -2593,8 +2597,8 @@ module ts { isNewIdentifierLocation = isNewIdentifierDefinitionLocation(previousToken); /// TODO filter meaning based on the current context - var symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias; - var symbols = typeInfoResolver.getSymbolsInScope(node, symbolMeanings); + let symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias; + let symbols = typeInfoResolver.getSymbolsInScope(node, symbolMeanings); getCompletionEntriesFromSymbols(symbols, activeCompletionSession); } @@ -2614,11 +2618,11 @@ module ts { }; function getCompletionEntriesFromSymbols(symbols: Symbol[], session: CompletionSession): void { - var start = new Date().getTime(); + let start = new Date().getTime(); forEach(symbols, symbol => { - var entry = createCompletionEntry(symbol, session.typeChecker, location); + let entry = createCompletionEntry(symbol, session.typeChecker, location); if (entry) { - var id = escapeIdentifier(entry.name); + let id = escapeIdentifier(entry.name); if (!lookUp(session.symbols, id)) { session.entries.push(entry); session.symbols[id] = symbol; @@ -2629,8 +2633,8 @@ module ts { } function isCompletionListBlocker(previousToken: Node): boolean { - var start = new Date().getTime(); - var result = isInStringOrRegularExpressionOrTemplateLiteral(previousToken) || + let start = new Date().getTime(); + let result = isInStringOrRegularExpressionOrTemplateLiteral(previousToken) || isIdentifierDefinitionLocation(previousToken) || isRightOfIllegalDot(previousToken); log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); @@ -2651,21 +2655,21 @@ module ts { function isNewIdentifierDefinitionLocation(previousToken: Node): boolean { if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + let containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case SyntaxKind.CommaToken: return containingNodeKind === SyntaxKind.CallExpression // func( a, | || containingNodeKind === SyntaxKind.Constructor // constructor( a, | public, protected, private keywords are allowed here, so show completion || containingNodeKind === SyntaxKind.NewExpression // new C(a, | || containingNodeKind === SyntaxKind.ArrayLiteralExpression // [a, | - || containingNodeKind === SyntaxKind.BinaryExpression; // var x = (a, | + || containingNodeKind === SyntaxKind.BinaryExpression; // let x = (a, | case SyntaxKind.OpenParenToken: return containingNodeKind === SyntaxKind.CallExpression // func( | || containingNodeKind === SyntaxKind.Constructor // constructor( | || containingNodeKind === SyntaxKind.NewExpression // new C(a| - || containingNodeKind === SyntaxKind.ParenthesizedExpression; // var x = (a| + || containingNodeKind === SyntaxKind.ParenthesizedExpression; // let x = (a| case SyntaxKind.OpenBracketToken: return containingNodeKind === SyntaxKind.ArrayLiteralExpression; // [ | @@ -2680,7 +2684,7 @@ module ts { return containingNodeKind === SyntaxKind.ClassDeclaration; // class A{ | case SyntaxKind.EqualsToken: - return containingNodeKind === SyntaxKind.VariableDeclaration // var x = a| + return containingNodeKind === SyntaxKind.VariableDeclaration // let x = a| || containingNodeKind === SyntaxKind.BinaryExpression; // x = a| case SyntaxKind.TemplateHead: @@ -2713,8 +2717,8 @@ module ts { || isTemplateLiteralKind(previousToken.kind)) { // The position has to be either: 1. entirely within the token text, or // 2. at the end position of an unterminated token. - var start = previousToken.getStart(); - var end = previousToken.getEnd(); + let start = previousToken.getStart(); + let end = previousToken.getEnd(); if (start < position && position < end) { return true; @@ -2731,11 +2735,11 @@ module ts { // The locations in an object literal expression that are applicable for completion are property name definition locations. if (previousToken) { - var parent = previousToken.parent; + let parent = previousToken.parent; switch (previousToken.kind) { - case SyntaxKind.OpenBraceToken: // var x = { | - case SyntaxKind.CommaToken: // var x = { a: 0, | + case SyntaxKind.OpenBraceToken: // let x = { | + case SyntaxKind.CommaToken: // let x = { a: 0, | if (parent && parent.kind === SyntaxKind.ObjectLiteralExpression) { return parent; } @@ -2765,7 +2769,7 @@ module ts { function isIdentifierDefinitionLocation(previousToken: Node): boolean { if (previousToken) { - var containingNodeKind = previousToken.parent.kind; + let containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case SyntaxKind.CommaToken: return containingNodeKind === SyntaxKind.VariableDeclaration || @@ -2792,13 +2796,13 @@ module ts { case SyntaxKind.OpenBraceToken: return containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { | containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface a { | - containingNodeKind === SyntaxKind.TypeLiteral || // var x : { | + containingNodeKind === SyntaxKind.TypeLiteral || // let x : { | containingNodeKind === SyntaxKind.ObjectBindingPattern; // function func({ x| case SyntaxKind.SemicolonToken: return containingNodeKind === SyntaxKind.PropertySignature && (previousToken.parent.parent.kind === SyntaxKind.InterfaceDeclaration || // interface a { f; | - previousToken.parent.parent.kind === SyntaxKind.TypeLiteral); // var x : { a; | + previousToken.parent.parent.kind === SyntaxKind.TypeLiteral); // let x : { a; | case SyntaxKind.LessThanToken: return containingNodeKind === SyntaxKind.ClassDeclaration || // class A< | @@ -2853,7 +2857,7 @@ module ts { function isRightOfIllegalDot(previousToken: Node): boolean { if (previousToken && previousToken.kind === SyntaxKind.NumericLiteral) { - var text = previousToken.getFullText(); + let text = previousToken.getFullText(); return text.charAt(text.length - 1) === "."; } @@ -2861,7 +2865,7 @@ module ts { } function filterModuleExports(exports: Symbol[], importDeclaration: ImportDeclaration): Symbol[] { - var exisingImports: Map = {}; + let exisingImports: Map = {}; if (!importDeclaration.importClause) { return exports; @@ -2871,7 +2875,7 @@ module ts { importDeclaration.importClause.namedBindings.kind === SyntaxKind.NamedImports) { forEach((importDeclaration.importClause.namedBindings).elements, el => { - var name = el.propertyName || el.name; + let name = el.propertyName || el.name; exisingImports[name.text] = true; }); } @@ -2887,7 +2891,7 @@ module ts { return contextualMemberSymbols; } - var existingMemberNames: Map = {}; + let existingMemberNames: Map = {}; forEach(existingMembers, m => { if (m.kind !== SyntaxKind.PropertyAssignment && m.kind !== SyntaxKind.ShorthandPropertyAssignment) { // Ignore omitted expressions for missing members in the object literal @@ -2903,7 +2907,7 @@ module ts { existingMemberNames[(m.name).text] = true; }); - var filteredMembers: Symbol[] = []; + let filteredMembers: Symbol[] = []; forEach(contextualMemberSymbols, s => { if (!existingMemberNames[s.name]) { filteredMembers.push(s); @@ -2917,25 +2921,25 @@ module ts { function getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails { // Note: No need to call synchronizeHostData, as we have captured all the data we need // in the getCompletionsAtPosition earlier - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var session = activeCompletionSession; + let session = activeCompletionSession; // Ensure that the current active completion session is still valid for this request if (!session || session.fileName !== fileName || session.position !== position) { return undefined; } - var symbol = lookUp(activeCompletionSession.symbols, escapeIdentifier(entryName)); + let symbol = lookUp(activeCompletionSession.symbols, escapeIdentifier(entryName)); if (symbol) { - var location = getTouchingPropertyName(sourceFile, position); - var completionEntry = createCompletionEntry(symbol, session.typeChecker, location); + let location = getTouchingPropertyName(sourceFile, position); + let completionEntry = createCompletionEntry(symbol, session.typeChecker, location); // TODO(drosen): Right now we just permit *all* semantic meanings when calling 'getSymbolKind' // which is permissible given that it is backwards compatible; but really we should consider // passing the meaning for the node so that we don't report that a suggestion for a value is an interface. // We COULD also just do what 'getSymbolModifiers' does, which is to use the first declaration. Debug.assert(session.typeChecker.getTypeOfSymbolAtLocation(symbol, location) !== undefined, "Could not find type for symbol"); - var displayPartsDocumentationsAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, session.typeChecker, location, SemanticMeaning.All); + let displayPartsDocumentationsAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, session.typeChecker, location, SemanticMeaning.All); return { name: entryName, kind: displayPartsDocumentationsAndSymbolKind.symbolKind, @@ -2958,7 +2962,7 @@ module ts { // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(symbol: Symbol, typeResolver: TypeChecker, location: Node): string { - var flags = symbol.getFlags(); + let flags = symbol.getFlags(); if (flags & SymbolFlags.Class) return ScriptElementKind.classElement; if (flags & SymbolFlags.Enum) return ScriptElementKind.enumElement; @@ -2966,7 +2970,7 @@ module ts { if (flags & SymbolFlags.Interface) return ScriptElementKind.interfaceElement; if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement; - var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, typeResolver, location); + let result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, typeResolver, location); if (result === ScriptElementKind.unknown) { if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement; if (flags & SymbolFlags.EnumMember) return ScriptElementKind.variableElement; @@ -3005,8 +3009,8 @@ module ts { if (flags & SymbolFlags.Property) { if (flags & SymbolFlags.UnionProperty) { // If union property is result of union of non method (property/accessors/variables), it is labeled as property - var unionPropertyKind = forEach(typeInfoResolver.getRootSymbols(symbol), rootSymbol => { - var rootSymbolFlags = rootSymbol.getFlags(); + let unionPropertyKind = forEach(typeInfoResolver.getRootSymbols(symbol), rootSymbol => { + let rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (SymbolFlags.PropertyOrAccessor | SymbolFlags.Variable)) { return ScriptElementKind.memberVariableElement; } @@ -3015,7 +3019,7 @@ module ts { if (!unionPropertyKind) { // If this was union of all methods, //make sure it has call signatures before we can label it as method - var typeOfUnionProperty = typeInfoResolver.getTypeOfSymbolAtLocation(symbol, location); + let typeOfUnionProperty = typeInfoResolver.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { return ScriptElementKind.memberFunctionElement; } @@ -3030,7 +3034,7 @@ module ts { } function getTypeKind(type: Type): string { - var flags = type.getFlags(); + let flags = type.getFlags(); if (flags & TypeFlags.Enum) return ScriptElementKind.enumElement; if (flags & TypeFlags.Class) return ScriptElementKind.classElement; @@ -3052,11 +3056,12 @@ module ts { typeResolver: TypeChecker, location: Node, // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location semanticMeaning = getMeaningFromLocation(location)) { - var displayParts: SymbolDisplayPart[] = []; - var documentation: SymbolDisplayPart[]; - var symbolFlags = symbol.flags; - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, typeResolver, location); - var hasAddedSymbolInfo: boolean; + let displayParts: SymbolDisplayPart[] = []; + let documentation: SymbolDisplayPart[]; + let symbolFlags = symbol.flags; + let symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, typeResolver, location); + let hasAddedSymbolInfo: boolean; + let type: Type; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Alias) { // If it is accessor they are allowed only if location is at name of the accessor @@ -3064,10 +3069,11 @@ module ts { symbolKind = ScriptElementKind.memberVariableElement; } - var type = typeResolver.getTypeOfSymbolAtLocation(symbol, location); + let signature: Signature; + type = typeResolver.getTypeOfSymbolAtLocation(symbol, location); if (type) { if (location.parent && location.parent.kind === SyntaxKind.PropertyAccessExpression) { - var right = (location.parent).name; + let right = (location.parent).name; // Either the location is on the right of a property access, or on the left and the right is missing if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; @@ -3075,7 +3081,7 @@ module ts { } // try get the call/construct signature from the type if it matches - var callExpression: CallExpression; + let callExpression: CallExpression; if (location.kind === SyntaxKind.CallExpression || location.kind === SyntaxKind.NewExpression) { callExpression = location; } @@ -3084,15 +3090,15 @@ module ts { } if (callExpression) { - var candidateSignatures: Signature[] = []; + let candidateSignatures: Signature[] = []; signature = typeResolver.getResolvedSignature(callExpression, candidateSignatures); if (!signature && candidateSignatures.length) { // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === SyntaxKind.NewExpression || callExpression.expression.kind === SyntaxKind.SuperKeyword; - var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + let useConstructSignatures = callExpression.kind === SyntaxKind.NewExpression || callExpression.expression.kind === SyntaxKind.SuperKeyword; + let allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); if (!contains(allSignatures, signature.target || signature)) { // Get the first signature if there @@ -3151,9 +3157,8 @@ module ts { else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & SymbolFlags.Accessor)) || // name of function declaration (location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration // get the signature from the declaration and write it - var signature: Signature; - var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getConstructSignatures() : type.getCallSignatures(); + let functionDeclaration = location.parent; + let allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeResolver.isImplementationOfOverload(functionDeclaration)) { signature = typeResolver.getSignatureFromDeclaration(functionDeclaration); } @@ -3233,8 +3238,8 @@ module ts { } else { // Method/function type parameter - var signatureDeclaration = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter).parent; - var signature = typeResolver.getSignatureFromDeclaration(signatureDeclaration); + let signatureDeclaration = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter).parent; + let signature = typeResolver.getSignatureFromDeclaration(signatureDeclaration); if (signatureDeclaration.kind === SyntaxKind.ConstructSignature) { displayParts.push(keywordPart(SyntaxKind.NewKeyword)); displayParts.push(spacePart()); @@ -3247,9 +3252,9 @@ module ts { } if (symbolFlags & SymbolFlags.EnumMember) { addPrefixForAnyFunctionOrVar(symbol, "enum member"); - var declaration = symbol.declarations[0]; + let declaration = symbol.declarations[0]; if (declaration.kind === SyntaxKind.EnumMember) { - var constantValue = typeResolver.getConstantValue(declaration); + let constantValue = typeResolver.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); @@ -3265,7 +3270,7 @@ module ts { addFullSymbolName(symbol); ts.forEach(symbol.declarations, declaration => { if (declaration.kind === SyntaxKind.ImportEqualsDeclaration) { - var importEqualsDeclaration = declaration; + let importEqualsDeclaration = declaration; if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); @@ -3276,7 +3281,7 @@ module ts { displayParts.push(punctuationPart(SyntaxKind.CloseParenToken)); } else { - var internalAliasSymbol = typeResolver.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + let internalAliasSymbol = typeResolver.getSymbolAtLocation(importEqualsDeclaration.moduleReference); if (internalAliasSymbol) { displayParts.push(spacePart()); displayParts.push(operatorPart(SyntaxKind.EqualsToken)); @@ -3300,7 +3305,7 @@ module ts { displayParts.push(spacePart()); // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & SymbolFlags.TypeParameter) { - var typeParameterParts = mapToDisplayParts(writer => { + let typeParameterParts = mapToDisplayParts(writer => { typeResolver.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); }); displayParts.push.apply(displayParts, typeParameterParts); @@ -3315,7 +3320,7 @@ module ts { symbolFlags & SymbolFlags.Signature || symbolFlags & SymbolFlags.Accessor || symbolKind === ScriptElementKind.memberFunctionElement) { - var allSignatures = type.getCallSignatures(); + let allSignatures = type.getCallSignatures(); addSignatureDisplayParts(allSignatures[0], allSignatures); } } @@ -3338,7 +3343,7 @@ module ts { } function addFullSymbolName(symbol: Symbol, enclosingDeclaration?: Node) { - var fullSymbolDisplayParts = symbolToDisplayParts(typeResolver, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, + let fullSymbolDisplayParts = symbolToDisplayParts(typeResolver, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments | SymbolFormatFlags.UseOnlyExternalAliasing); displayParts.push.apply(displayParts, fullSymbolDisplayParts); } @@ -3369,7 +3374,7 @@ module ts { } function writeTypeParametersOfSymbol(symbol: Symbol, enclosingDeclaration: Node) { - var typeParameterParts = mapToDisplayParts(writer => { + let typeParameterParts = mapToDisplayParts(writer => { typeResolver.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); }); displayParts.push.apply(displayParts, typeParameterParts); @@ -3379,13 +3384,13 @@ module ts { function getQuickInfoAtPosition(fileName: string, position: number): QuickInfo { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); - var node = getTouchingPropertyName(sourceFile, position); + let sourceFile = getValidSourceFile(fileName); + let node = getTouchingPropertyName(sourceFile, position); if (!node) { return undefined; } - var symbol = typeInfoResolver.getSymbolAtLocation(node); + let symbol = typeInfoResolver.getSymbolAtLocation(node); if (!symbol) { // Try getting just type at this position and show switch (node.kind) { @@ -3395,7 +3400,7 @@ module ts { case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: // For the identifiers/this/super etc get the type at position - var type = typeInfoResolver.getTypeAtLocation(node); + let type = typeInfoResolver.getTypeAtLocation(node); if (type) { return { kind: ScriptElementKind.unknown, @@ -3410,7 +3415,7 @@ module ts { return undefined; } - var displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), typeInfoResolver, node); + let displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), typeInfoResolver, node); return { kind: displayPartsDocumentationsAndKind.symbolKind, kindModifiers: getSymbolModifiers(symbol), @@ -3424,24 +3429,24 @@ module ts { function getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var node = getTouchingPropertyName(sourceFile, position); + let node = getTouchingPropertyName(sourceFile, position); if (!node) { return undefined; } // Labels if (isJumpStatementTarget(node)) { - var labelName = (node).text; - var label = getTargetLabel((node.parent), (node).text); + let labelName = (node).text; + let label = getTargetLabel((node.parent), (node).text); return label ? [getDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; } /// Triple slash reference comments - var comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined); + let comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined); if (comment) { - var referenceFile = tryResolveScriptReference(program, sourceFile, comment); + let referenceFile = tryResolveScriptReference(program, sourceFile, comment); if (referenceFile) { return [{ fileName: referenceFile.fileName, @@ -3455,7 +3460,7 @@ module ts { return undefined; } - var symbol = typeInfoResolver.getSymbolAtLocation(node); + let symbol = typeInfoResolver.getSymbolAtLocation(node); // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol @@ -3468,13 +3473,13 @@ module ts { // import {A, B} from "mod"; // to jump to the implementation directelly. if (symbol.flags & SymbolFlags.Alias) { - var declaration = symbol.declarations[0]; + let declaration = symbol.declarations[0]; if (node.kind === SyntaxKind.Identifier && node.parent === declaration) { symbol = typeInfoResolver.getAliasedSymbol(symbol); } } - var result: DefinitionInfo[] = []; + let result: DefinitionInfo[] = []; // Because name in short-hand property assignment has two different meanings: property name and property value, // using go-to-definition at such position should go to the variable declaration of the property value rather than @@ -3482,22 +3487,22 @@ module ts { // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { - var shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver, node); - var shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol); - var shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node); + let shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + let shorthandDeclarations = shorthandSymbol.getDeclarations(); + let shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver, node); + let shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol); + let shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node); forEach(shorthandDeclarations, declaration => { result.push(getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); }); return result } - var declarations = symbol.getDeclarations(); - var symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol - var symbolKind = getSymbolKind(symbol, typeInfoResolver, node); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : ""; + let declarations = symbol.getDeclarations(); + let symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + let symbolKind = getSymbolKind(symbol, typeInfoResolver, node); + let containerSymbol = symbol.parent; + let containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : ""; if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { @@ -3521,8 +3526,8 @@ module ts { } function tryAddSignature(signatureDeclarations: Declaration[], selectConstructors: boolean, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) { - var declarations: Declaration[] = []; - var definition: Declaration; + let declarations: Declaration[] = []; + let definition: Declaration; forEach(signatureDeclarations, d => { if ((selectConstructors && d.kind === SyntaxKind.Constructor) || @@ -3549,7 +3554,7 @@ module ts { // and in either case the symbol has a construct signature definition, i.e. class if (isNewExpressionTarget(location) || location.kind === SyntaxKind.ConstructorKeyword) { if (symbol.flags & SymbolFlags.Class) { - var classDeclaration = symbol.getDeclarations()[0]; + let classDeclaration = symbol.getDeclarations()[0]; Debug.assert(classDeclaration && classDeclaration.kind === SyntaxKind.ClassDeclaration); return tryAddSignature(classDeclaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); @@ -3570,9 +3575,9 @@ module ts { function getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var node = getTouchingWord(sourceFile, position); + let node = getTouchingWord(sourceFile, position); if (!node) { return undefined; } @@ -3660,7 +3665,7 @@ module ts { return undefined; function getIfElseOccurrences(ifStatement: IfStatement): ReferenceEntry[] { - var keywords: Node[] = []; + let keywords: Node[] = []; // Traverse upwards through all parent if-statements linked by their else-branches. while (hasKind(ifStatement.parent, SyntaxKind.IfStatement) && (ifStatement.parent).elseStatement === ifStatement) { @@ -3669,11 +3674,11 @@ module ts { // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. while (ifStatement) { - var children = ifStatement.getChildren(); + let children = ifStatement.getChildren(); pushKeywordIf(keywords, children[0], SyntaxKind.IfKeyword); // Generally the 'else' keyword is second-to-last, so we traverse backwards. - for (var i = children.length - 1; i >= 0; i--) { + for (let i = children.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, children[i], SyntaxKind.ElseKeyword)) { break; } @@ -3686,19 +3691,19 @@ module ts { ifStatement = ifStatement.elseStatement; } - var result: ReferenceEntry[] = []; + let result: ReferenceEntry[] = []; // We'd like to highlight else/ifs together if they are only separated by whitespace // (i.e. the keywords are separated by no comments, no newlines). - for (var i = 0; i < keywords.length; i++) { + for (let i = 0; i < keywords.length; i++) { if (keywords[i].kind === SyntaxKind.ElseKeyword && i < keywords.length - 1) { - var elseKeyword = keywords[i]; - var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + let elseKeyword = keywords[i]; + let ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. - var shouldHighlightNextKeyword = true; + let shouldHighlightNextKeyword = true; // Avoid recalculating getStart() by iterating backwards. - for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + for (let j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { if (!isWhiteSpace(sourceFile.text.charCodeAt(j))) { shouldHighlightNextKeyword = false; break; @@ -3724,14 +3729,14 @@ module ts { } function getReturnOccurrences(returnStatement: ReturnStatement): ReferenceEntry[] { - var func = getContainingFunction(returnStatement); + let func = getContainingFunction(returnStatement); // If we didn't find a containing function with a block body, bail out. if (!(func && hasKind(func.body, SyntaxKind.Block))) { return undefined; } - var keywords: Node[] = [] + let keywords: Node[] = [] forEachReturnStatement(func.body, returnStatement => { pushKeywordIf(keywords, returnStatement.getFirstToken(), SyntaxKind.ReturnKeyword); }); @@ -3745,13 +3750,13 @@ module ts { } function getThrowOccurrences(throwStatement: ThrowStatement) { - var owner = getThrowStatementOwner(throwStatement); + let owner = getThrowStatementOwner(throwStatement); if (!owner) { return undefined; } - var keywords: Node[] = []; + let keywords: Node[] = []; forEach(aggregateOwnedThrowStatements(owner), throwStatement => { pushKeywordIf(keywords, throwStatement.getFirstToken(), SyntaxKind.ThrowKeyword); @@ -3773,7 +3778,7 @@ module ts { * into function boundaries and try-blocks with catch-clauses. */ function aggregateOwnedThrowStatements(node: Node): ThrowStatement[] { - var statementAccumulator: ThrowStatement[] = [] + let statementAccumulator: ThrowStatement[] = [] aggregate(node); return statementAccumulator; @@ -3782,7 +3787,7 @@ module ts { statementAccumulator.push(node); } else if (node.kind === SyntaxKind.TryStatement) { - var tryStatement = node; + let tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -3810,10 +3815,10 @@ module ts { * function-block, or source file. */ function getThrowStatementOwner(throwStatement: ThrowStatement): Node { - var child: Node = throwStatement; + let child: Node = throwStatement; while (child.parent) { - var parent = child.parent; + let parent = child.parent; if (isFunctionBlock(parent) || parent.kind === SyntaxKind.SourceFile) { return parent; @@ -3822,7 +3827,7 @@ module ts { // A throw-statement is only owned by a try-statement if the try-statement has // a catch clause, and if the throw-statement occurs within the try block. if (parent.kind === SyntaxKind.TryStatement) { - var tryStatement = parent; + let tryStatement = parent; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; @@ -3836,7 +3841,7 @@ module ts { } function getTryCatchFinallyOccurrences(tryStatement: TryStatement): ReferenceEntry[] { - var keywords: Node[] = []; + let keywords: Node[] = []; pushKeywordIf(keywords, tryStatement.getFirstToken(), SyntaxKind.TryKeyword); @@ -3845,7 +3850,7 @@ module ts { } if (tryStatement.finallyBlock) { - var finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); + let finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); pushKeywordIf(keywords, finallyKeyword, SyntaxKind.FinallyKeyword); } @@ -3853,14 +3858,14 @@ module ts { } function getLoopBreakContinueOccurrences(loopNode: IterationStatement): ReferenceEntry[] { - var keywords: Node[] = []; + let keywords: Node[] = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword, SyntaxKind.DoKeyword)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. if (loopNode.kind === SyntaxKind.DoStatement) { - var loopTokens = loopNode.getChildren(); + let loopTokens = loopNode.getChildren(); - for (var i = loopTokens.length - 1; i >= 0; i--) { + for (let i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], SyntaxKind.WhileKeyword)) { break; } @@ -3868,7 +3873,7 @@ module ts { } } - var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); + let breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); forEach(breaksAndContinues, statement => { if (ownsBreakOrContinueStatement(loopNode, statement)) { @@ -3880,7 +3885,7 @@ module ts { } function getSwitchCaseDefaultOccurrences(switchStatement: SwitchStatement) { - var keywords: Node[] = []; + let keywords: Node[] = []; pushKeywordIf(keywords, switchStatement.getFirstToken(), SyntaxKind.SwitchKeyword); @@ -3888,7 +3893,7 @@ module ts { forEach(switchStatement.caseBlock.clauses, clause => { pushKeywordIf(keywords, clause.getFirstToken(), SyntaxKind.CaseKeyword, SyntaxKind.DefaultKeyword); - var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); + let breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); forEach(breaksAndContinues, statement => { if (ownsBreakOrContinueStatement(switchStatement, statement)) { @@ -3901,7 +3906,7 @@ module ts { } function getBreakOrContinueStatementOccurences(breakOrContinueStatement: BreakOrContinueStatement): ReferenceEntry[] { - var owner = getBreakOrContinueOwner(breakOrContinueStatement); + let owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { @@ -3921,7 +3926,7 @@ module ts { } function aggregateAllBreakAndContinueStatements(node: Node): BreakOrContinueStatement[] { - var statementAccumulator: BreakOrContinueStatement[] = [] + let statementAccumulator: BreakOrContinueStatement[] = [] aggregate(node); return statementAccumulator; @@ -3937,13 +3942,13 @@ module ts { } function ownsBreakOrContinueStatement(owner: Node, statement: BreakOrContinueStatement): boolean { - var actualOwner = getBreakOrContinueOwner(statement); + let actualOwner = getBreakOrContinueOwner(statement); return actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement: BreakOrContinueStatement): Node { - for (var node = statement.parent; node; node = node.parent) { + for (let node = statement.parent; node; node = node.parent) { switch (node.kind) { case SyntaxKind.SwitchStatement: if (statement.kind === SyntaxKind.ContinueStatement) { @@ -3972,9 +3977,9 @@ module ts { } function getConstructorOccurrences(constructorDeclaration: ConstructorDeclaration): ReferenceEntry[] { - var declarations = constructorDeclaration.symbol.getDeclarations() + let declarations = constructorDeclaration.symbol.getDeclarations() - var keywords: Node[] = []; + let keywords: Node[] = []; forEach(declarations, declaration => { forEach(declaration.getChildren(), token => { @@ -3986,7 +3991,7 @@ module ts { } function getGetAndSetOccurrences(accessorDeclaration: AccessorDeclaration): ReferenceEntry[] { - var keywords: Node[] = []; + let keywords: Node[] = []; tryPushAccessorKeyword(accessorDeclaration.symbol, SyntaxKind.GetAccessor); tryPushAccessorKeyword(accessorDeclaration.symbol, SyntaxKind.SetAccessor); @@ -3994,7 +3999,7 @@ module ts { return map(keywords, getReferenceEntryFromNode); function tryPushAccessorKeyword(accessorSymbol: Symbol, accessorKind: SyntaxKind): void { - var accessor = getDeclarationOfKind(accessorSymbol, accessorKind); + let accessor = getDeclarationOfKind(accessorSymbol, accessorKind); if (accessor) { forEach(accessor.getChildren(), child => pushKeywordIf(keywords, child, SyntaxKind.GetKeyword, SyntaxKind.SetKeyword)); @@ -4003,7 +4008,7 @@ module ts { } function getModifierOccurrences(modifier: SyntaxKind, declaration: Node) { - var container = declaration.parent; + let container = declaration.parent; // Make sure we only highlight the keyword when it makes sense to do so. if (declaration.flags & NodeFlags.AccessibilityModifier) { @@ -4027,10 +4032,10 @@ module ts { return undefined; } - var keywords: Node[] = []; - var modifierFlag: NodeFlags = getFlagFromModifier(modifier); + let keywords: Node[] = []; + let modifierFlag: NodeFlags = getFlagFromModifier(modifier); - var nodes: Node[]; + let nodes: Node[]; switch (container.kind) { case SyntaxKind.ModuleBlock: case SyntaxKind.SourceFile: @@ -4046,7 +4051,7 @@ module ts { // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. if (modifierFlag & NodeFlags.AccessibilityModifier) { - var constructor = forEach((container).members, member => { + let constructor = forEach((container).members, member => { return member.kind === SyntaxKind.Constructor && member; }); @@ -4118,9 +4123,9 @@ module ts { function findReferences(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReferenceEntry[] { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var node = getTouchingPropertyName(sourceFile, position); + let node = getTouchingPropertyName(sourceFile, position); if (!node) { return undefined; } @@ -4142,7 +4147,7 @@ module ts { // Labels if (isLabelName(node)) { if (isJumpStatementTarget(node)) { - var labelDefinition = getTargetLabel((node.parent), (node).text); + let labelDefinition = getTargetLabel((node.parent), (node).text); // if we have a label definition, look within its statement for references, if not, then // the label is undefined, just return a set of one for the current node. return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : [getReferenceEntryFromNode(node)]; @@ -4161,7 +4166,7 @@ module ts { return getReferencesForSuperKeyword(node); } - var symbol = typeInfoResolver.getSymbolAtLocation(node); + let symbol = typeInfoResolver.getSymbolAtLocation(node); // Could not find a symbol e.g. unknown identifier if (!symbol) { @@ -4170,24 +4175,24 @@ module ts { return [getReferenceEntryFromNode(node)]; } - var declarations = symbol.declarations; + let declarations = symbol.declarations; // The symbol was an internal symbol and does not have a declaration e.g.undefined symbol if (!declarations || !declarations.length) { return undefined; } - var result: ReferenceEntry[]; + let result: ReferenceEntry[]; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); + let searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); // Get the text to search for, we need to normalize it as external module names will have quote - var declaredName = getDeclaredName(symbol, node); + let declaredName = getDeclaredName(symbol, node); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); + let scope = getSymbolScope(symbol); if (scope) { result = []; @@ -4200,11 +4205,11 @@ module ts { getReferencesInNode(sourceFiles[0], symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result); } else { - var internedName = getInternedName(symbol, node, declarations) + let internedName = getInternedName(symbol, node, declarations) forEach(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); - var nameTable = getNameTable(sourceFile); + let nameTable = getNameTable(sourceFile); if (lookUp(nameTable, internedName)) { result = result || []; @@ -4230,15 +4235,16 @@ module ts { function getDeclaredName(symbol: Symbol, location: Node) { // Special case for function expressions, whose names are solely local to their bodies. - var functionExpression = forEach(symbol.declarations, d => d.kind === SyntaxKind.FunctionExpression ? d : undefined); + let functionExpression = forEach(symbol.declarations, d => d.kind === SyntaxKind.FunctionExpression ? d : undefined); // When a name gets interned into a SourceFile's 'identifiers' Map, // its name is escaped and stored in the same way its symbol name/identifier // name should be stored. Function expressions, however, are a special case, // because despite sometimes having a name, the binder unconditionally binds them // to a symbol with the name "__function". + let name: string; if (functionExpression && functionExpression.name) { - var name = functionExpression.name.text; + name = functionExpression.name.text; } // If this is an export or import specifier it could have been renamed using the as syntax. @@ -4248,7 +4254,7 @@ module ts { return location.getText(); } - var name = typeInfoResolver.symbolToString(symbol); + name = typeInfoResolver.symbolToString(symbol); return stripQuotes(name); } @@ -4262,25 +4268,22 @@ module ts { } // Special case for function expressions, whose names are solely local to their bodies. - var functionExpression = forEach(declarations, d => d.kind === SyntaxKind.FunctionExpression ? d : undefined); + let functionExpression = forEach(declarations, d => d.kind === SyntaxKind.FunctionExpression ? d : undefined); // When a name gets interned into a SourceFile's 'identifiers' Map, // its name is escaped and stored in the same way its symbol name/identifier // name should be stored. Function expressions, however, are a special case, // because despite sometimes having a name, the binder unconditionally binds them // to a symbol with the name "__function". - if (functionExpression && functionExpression.name) { - var name = functionExpression.name.text; - } - else { - var name = symbol.name; - } + let name = functionExpression && functionExpression.name + ? functionExpression.name.text + : symbol.name; return stripQuotes(name); } function stripQuotes(name: string) { - var length = name.length; + let length = name.length; if (length >= 2 && name.charCodeAt(0) === CharacterCodes.doubleQuote && name.charCodeAt(length - 1) === CharacterCodes.doubleQuote) { return name.substring(1, length - 1); }; @@ -4290,7 +4293,7 @@ module ts { function getSymbolScope(symbol: Symbol): Node { // If this is private property or method, the scope is the containing class if (symbol.flags & (SymbolFlags.Property | SymbolFlags.Method)) { - var privateDeclaration = forEach(symbol.getDeclarations(), d => (d.flags & NodeFlags.Private) ? d : undefined); + let privateDeclaration = forEach(symbol.getDeclarations(), d => (d.flags & NodeFlags.Private) ? d : undefined); if (privateDeclaration) { return getAncestor(privateDeclaration, SyntaxKind.ClassDeclaration); } @@ -4308,12 +4311,12 @@ module ts { return undefined; } - var scope: Node = undefined; + let scope: Node = undefined; - var declarations = symbol.getDeclarations(); + let declarations = symbol.getDeclarations(); if (declarations) { for (let declaration of declarations) { - var container = getContainerNode(declaration); + let container = getContainerNode(declaration); if (!container) { return undefined; @@ -4339,7 +4342,7 @@ module ts { } function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, start: number, end: number): number[] { - var positions: number[] = []; + let positions: number[] = []; /// TODO: Cache symbol existence for files to save text search // Also, need to make this work for unicode escapes. @@ -4349,11 +4352,11 @@ module ts { return positions; } - var text = sourceFile.text; - var sourceLength = text.length; - var symbolNameLength = symbolName.length; + let text = sourceFile.text; + let sourceLength = text.length; + let symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); + let position = text.indexOf(symbolName, start); while (position >= 0) { cancellationToken.throwIfCancellationRequested(); @@ -4362,7 +4365,7 @@ module ts { // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). - var endPosition = position + symbolNameLength; + let endPosition = position + symbolNameLength; if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), ScriptTarget.Latest)) && (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), ScriptTarget.Latest))) { @@ -4376,14 +4379,14 @@ module ts { } function getLabelReferencesInNode(container: Node, targetLabel: Identifier): ReferenceEntry[] { - var result: ReferenceEntry[] = []; - var sourceFile = container.getSourceFile(); - var labelName = targetLabel.text; - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + let result: ReferenceEntry[] = []; + let sourceFile = container.getSourceFile(); + let labelName = targetLabel.text; + let possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); forEach(possiblePositions, position => { cancellationToken.throwIfCancellationRequested(); - var node = getTouchingWord(sourceFile, position); + let node = getTouchingWord(sourceFile, position); if (!node || node.getWidth() !== labelName.length) { return; } @@ -4435,19 +4438,19 @@ module ts { findInStrings: boolean, findInComments: boolean, result: ReferenceEntry[]): void { - var sourceFile = container.getSourceFile(); - var tripleSlashDirectivePrefixRegex = /^\/\/\/\s* { cancellationToken.throwIfCancellationRequested(); - var referenceLocation = getTouchingPropertyName(sourceFile, position); + let referenceLocation = getTouchingPropertyName(sourceFile, position); if (!isValidReferencePosition(referenceLocation, searchText)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking @@ -4467,10 +4470,10 @@ module ts { return; } - var referenceSymbol = typeInfoResolver.getSymbolAtLocation(referenceLocation); + let referenceSymbol = typeInfoResolver.getSymbolAtLocation(referenceLocation); if (referenceSymbol) { - var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; - var shorthandValueSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); + let referenceSymbolDeclaration = referenceSymbol.valueDeclaration; + let shorthandValueSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); if (isRelatableToSearchSet(searchSymbols, referenceSymbol, referenceLocation)) { result.push(getReferenceEntryFromNode(referenceLocation)); } @@ -4488,21 +4491,21 @@ module ts { } function isInString(position: number) { - var token = getTokenAtPosition(sourceFile, position); + let token = getTokenAtPosition(sourceFile, position); return token && token.kind === SyntaxKind.StringLiteral && position > token.getStart(); } function isInComment(position: number) { - var token = getTokenAtPosition(sourceFile, position); + let token = getTokenAtPosition(sourceFile, position); if (token && position < token.getStart()) { // First, we have to see if this position actually landed in a comment. - var commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); + let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); // Then we want to make sure that it wasn't in a "///<" directive comment // We don't want to unintentionally update a file name. return forEach(commentRanges, c => { if (c.pos < position && position < c.end) { - var commentText = sourceFile.text.substring(c.pos, c.end); + let commentText = sourceFile.text.substring(c.pos, c.end); if (!tripleSlashDirectivePrefixRegex.test(commentText)) { return true; } @@ -4515,12 +4518,12 @@ module ts { } function getReferencesForSuperKeyword(superKeyword: Node): ReferenceEntry[] { - var searchSpaceNode = getSuperContainer(superKeyword, /*includeFunctions*/ false); + let searchSpaceNode = getSuperContainer(superKeyword, /*includeFunctions*/ false); if (!searchSpaceNode) { return undefined; } // Whether 'super' occurs in a static context within a class. - var staticFlag = NodeFlags.Static; + let staticFlag = NodeFlags.Static; switch (searchSpaceNode.kind) { case SyntaxKind.PropertyDeclaration: @@ -4537,20 +4540,20 @@ module ts { return undefined; } - var result: ReferenceEntry[] = []; + let result: ReferenceEntry[] = []; - var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + let sourceFile = searchSpaceNode.getSourceFile(); + let possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); forEach(possiblePositions, position => { cancellationToken.throwIfCancellationRequested(); - var node = getTouchingWord(sourceFile, position); + let node = getTouchingWord(sourceFile, position); if (!node || node.kind !== SyntaxKind.SuperKeyword) { return; } - var container = getSuperContainer(node, /*includeFunctions*/ false); + let container = getSuperContainer(node, /*includeFunctions*/ false); // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space @@ -4564,10 +4567,10 @@ module ts { } function getReferencesForThisKeyword(thisOrSuperKeyword: Node, sourceFiles: SourceFile[]): ReferenceEntry[] { - var searchSpaceNode = getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + let searchSpaceNode = getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. - var staticFlag = NodeFlags.Static; + let staticFlag = NodeFlags.Static; switch (searchSpaceNode.kind) { case SyntaxKind.MethodDeclaration: @@ -4598,17 +4601,18 @@ module ts { return undefined; } - var result: ReferenceEntry[] = []; + let result: ReferenceEntry[] = []; + let possiblePositions: number[]; if (searchSpaceNode.kind === SyntaxKind.SourceFile) { forEach(sourceFiles, sourceFile => { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, result); }); } else { - var sourceFile = searchSpaceNode.getSourceFile(); - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + let sourceFile = searchSpaceNode.getSourceFile(); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result); } @@ -4618,12 +4622,12 @@ module ts { forEach(possiblePositions, position => { cancellationToken.throwIfCancellationRequested(); - var node = getTouchingWord(sourceFile, position); + let node = getTouchingWord(sourceFile, position); if (!node || node.kind !== SyntaxKind.ThisKeyword) { return; } - var container = getThisContainer(node, /* includeArrowFunctions */ false); + let container = getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { case SyntaxKind.FunctionExpression: @@ -4657,7 +4661,7 @@ module ts { function populateSearchSymbolSet(symbol: Symbol, location: Node): Symbol[] { // The search set contains at least the current symbol - var result = [symbol]; + let result = [symbol]; // If the symbol is an alias, add what it alaises to the list if (isImportOrExportSpecifierImportSymbol(symbol)) { @@ -4677,13 +4681,13 @@ module ts { * property name and variable declaration of the identifier. * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service * should show both 'name' in 'obj' and 'name' in variable declaration - * var name = "Foo"; - * var obj = { name }; + * let name = "Foo"; + * let obj = { name }; * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(location.parent); + let shorthandValueSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(location.parent); if (shorthandValueSymbol) { result.push(shorthandValueSymbol); } @@ -4721,9 +4725,9 @@ module ts { function getPropertySymbolFromTypeReference(typeReference: TypeReferenceNode) { if (typeReference) { - var type = typeInfoResolver.getTypeAtLocation(typeReference); + let type = typeInfoResolver.getTypeAtLocation(typeReference); if (type) { - var propertySymbol = typeInfoResolver.getPropertyOfType(type, propertyName); + let propertySymbol = typeInfoResolver.getPropertyOfType(type, propertyName); if (propertySymbol) { result.push(propertySymbol); } @@ -4767,7 +4771,7 @@ module ts { // Finally, try all properties with the same name in any type the containing type extended or implemented, and // see if any is in the list if (rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { - var result: Symbol[] = []; + let result: Symbol[] = []; getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); return forEach(result, s => searchSymbols.indexOf(s) >= 0); } @@ -4778,21 +4782,21 @@ module ts { function getPropertySymbolsFromContextualType(node: Node): Symbol[] { if (isNameOfPropertyAssignment(node)) { - var objectLiteral = node.parent.parent; - var contextualType = typeInfoResolver.getContextualType(objectLiteral); - var name = (node).text; + let objectLiteral = node.parent.parent; + let contextualType = typeInfoResolver.getContextualType(objectLiteral); + let name = (node).text; if (contextualType) { if (contextualType.flags & TypeFlags.Union) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name) + let unionProperty = contextualType.getProperty(name) if (unionProperty) { return [unionProperty]; } else { - var result: Symbol[] = []; + let result: Symbol[] = []; forEach((contextualType).types, t => { - var symbol = t.getProperty(name); + let symbol = t.getProperty(name); if (symbol) { result.push(symbol); } @@ -4801,7 +4805,7 @@ module ts { } } else { - var symbol = contextualType.getProperty(name); + let symbol = contextualType.getProperty(name); if (symbol) { return [symbol]; } @@ -4820,6 +4824,7 @@ module ts { */ function getIntersectingMeaningFromDeclarations(meaning: SemanticMeaning, declarations: Declaration[]): SemanticMeaning { if (declarations) { + let lastIterationMeaning: SemanticMeaning; do { // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module @@ -4827,24 +4832,25 @@ module ts { // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning - var lastIterationMeaning = meaning; + lastIterationMeaning = meaning; for (let declaration of declarations) { - var declarationMeaning = getMeaningFromDeclaration(declaration); + let declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; } } - } while (meaning !== lastIterationMeaning); + } + while (meaning !== lastIterationMeaning); } return meaning; } } function getReferenceEntryFromNode(node: Node): ReferenceEntry { - var start = node.getStart(); - var end = node.getEnd(); + let start = node.getStart(); + let end = node.getEnd(); if (node.kind === SyntaxKind.StringLiteral) { start += 1; @@ -4864,13 +4870,13 @@ module ts { return true; } - var parent = node.parent; + let parent = node.parent; if (parent) { if (parent.kind === SyntaxKind.PostfixUnaryExpression || parent.kind === SyntaxKind.PrefixUnaryExpression) { return true; } else if (parent.kind === SyntaxKind.BinaryExpression && (parent).left === node) { - var operator = (parent).operatorToken.kind; + let operator = (parent).operatorToken.kind; return SyntaxKind.FirstAssignment <= operator && operator <= SyntaxKind.LastAssignment; } } @@ -4892,9 +4898,9 @@ module ts { function getEmitOutput(fileName: string): EmitOutput { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var outputFiles: OutputFile[] = []; + let outputFiles: OutputFile[] = []; function writeFile(fileName: string, data: string, writeByteOrderMark: boolean) { outputFiles.push({ @@ -4904,7 +4910,7 @@ module ts { }); } - var emitOutput = program.emit(sourceFile, writeFile); + let emitOutput = program.emit(sourceFile, writeFile); return { outputFiles, @@ -4981,8 +4987,8 @@ module ts { } function isNamespaceReference(node: Node): boolean { - var root = node; - var isLastClause = true; + let root = node; + let isLastClause = true; if (root.parent.kind === SyntaxKind.QualifiedName) { while (root.parent && root.parent.kind === SyntaxKind.QualifiedName) root = root.parent; @@ -5043,7 +5049,7 @@ module ts { function getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); return SignatureHelp.getSignatureHelpItems(sourceFile, position, typeInfoResolver, cancellationToken); } @@ -5054,10 +5060,10 @@ module ts { } function getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = getTouchingPropertyName(sourceFile, startPos); + let node = getTouchingPropertyName(sourceFile, startPos); if (!node) { return; @@ -5080,7 +5086,7 @@ module ts { return; } - var nodeForStartPos = node; + let nodeForStartPos = node; while (true) { if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) { // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node @@ -5111,13 +5117,13 @@ module ts { function getBreakpointStatementAtPosition(fileName: string, position: number) { // doesn't use compiler - no need to synchronize with host - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName: string): NavigationBarItem[]{ - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return NavigationBar.getNavigationBarItems(sourceFile); } @@ -5125,15 +5131,15 @@ module ts { function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var result: ClassifiedSpan[] = []; + let result: ClassifiedSpan[] = []; processNode(sourceFile); return result; function classifySymbol(symbol: Symbol, meaningAtPosition: SemanticMeaning) { - var flags = symbol.getFlags(); + let flags = symbol.getFlags(); if (flags & SymbolFlags.Class) { return ClassificationTypeNames.className; @@ -5178,9 +5184,9 @@ module ts { // Only walk into nodes that intersect the requested span. if (node && textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { if (node.kind === SyntaxKind.Identifier && node.getWidth() > 0) { - var symbol = typeInfoResolver.getSymbolAtLocation(node); + let symbol = typeInfoResolver.getSymbolAtLocation(node); if (symbol) { - var type = classifySymbol(symbol, getMeaningFromLocation(node)); + let type = classifySymbol(symbol, getMeaningFromLocation(node)); if (type) { result.push({ textSpan: createTextSpan(node.getStart(), node.getWidth()), @@ -5197,19 +5203,19 @@ module ts { function getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] { // doesn't use compiler - no need to synchronize with host - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Make a scanner we can get trivia from. - var triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); - var mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); + let triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); + let mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); - var result: ClassifiedSpan[] = []; + let result: ClassifiedSpan[] = []; processElement(sourceFile); return result; function classifyLeadingTrivia(token: Node): void { - var tokenStart = skipTrivia(sourceFile.text, token.pos, /*stopAfterLineBreak:*/ false); + let tokenStart = skipTrivia(sourceFile.text, token.pos, /*stopAfterLineBreak:*/ false); if (tokenStart === token.pos) { return; } @@ -5217,10 +5223,10 @@ module ts { // token has trivia. Classify them appropriately. triviaScanner.setTextPos(token.pos); while (true) { - var start = triviaScanner.getTextPos(); - var kind = triviaScanner.scan(); - var end = triviaScanner.getTextPos(); - var width = end - start; + let start = triviaScanner.getTextPos(); + let kind = triviaScanner.scan(); + let end = triviaScanner.getTextPos(); + let width = end - start; if (textSpanIntersectsWith(span, start, width)) { if (!isTrivia(kind)) { @@ -5237,8 +5243,8 @@ module ts { } if (kind === SyntaxKind.ConflictMarkerTrivia) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); + let text = sourceFile.text; + let ch = text.charCodeAt(start); // for the <<<<<<< and >>>>>>> markers, we just add them in as comments // in the classification stream. @@ -5280,11 +5286,11 @@ module ts { } function classifyDisabledCodeToken() { - var start = mergeConflictScanner.getTextPos(); - var tokenKind = mergeConflictScanner.scan(); - var end = mergeConflictScanner.getTextPos(); + let start = mergeConflictScanner.getTextPos(); + let tokenKind = mergeConflictScanner.scan(); + let end = mergeConflictScanner.getTextPos(); - var type = classifyTokenType(tokenKind); + let type = classifyTokenType(tokenKind); if (type) { result.push({ textSpan: createTextSpanFromBounds(start, end), @@ -5297,7 +5303,7 @@ module ts { classifyLeadingTrivia(token); if (token.getWidth() > 0) { - var type = classifyTokenType(token.kind, token); + let type = classifyTokenType(token.kind, token); if (type) { result.push({ textSpan: createTextSpan(token.getStart(), token.getWidth()), @@ -5398,7 +5404,7 @@ module ts { function processElement(element: Node) { // Ignore nodes that don't intersect the original span to classify. if (textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { - var children = element.getChildren(); + let children = element.getChildren(); for (let child of children) { if (isToken(child)) { classifyToken(child); @@ -5414,28 +5420,28 @@ module ts { function getOutliningSpans(fileName: string): OutliningSpan[] { // doesn't use compiler - no need to synchronize with host - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return OutliningElementsCollector.collectElements(sourceFile); } function getBraceMatchingAtPosition(fileName: string, position: number) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var result: TextSpan[] = []; + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let result: TextSpan[] = []; - var token = getTouchingToken(sourceFile, position); + let token = getTouchingToken(sourceFile, position); if (token.getStart(sourceFile) === position) { - var matchKind = getMatchingTokenKind(token); + let matchKind = getMatchingTokenKind(token); // Ensure that there is a corresponding token to match ours. if (matchKind) { - var parentElement = token.parent; + let parentElement = token.parent; - var childNodes = parentElement.getChildren(sourceFile); + let childNodes = parentElement.getChildren(sourceFile); for (let current of childNodes) { if (current.kind === matchKind) { - var range1 = createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); - var range2 = createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); + let range1 = createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); + let range2 = createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); // We want to order the braces when we return the result. if (range1.start < range2.start) { @@ -5470,30 +5476,30 @@ module ts { } function getIndentationAtPosition(fileName: string, position: number, editorOptions: EditorOptions) { - var start = new Date().getTime(); - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let start = new Date().getTime(); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); - var start = new Date().getTime(); + start = new Date().getTime(); - var result = formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + let result = formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); return result; } function getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[] { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); } function getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[] { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); return formatting.formatDocument(sourceFile, getRuleProvider(options), options); } function getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[] { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); if (key === "}") { return formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); @@ -5517,17 +5523,17 @@ module ts { // anything away. synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); cancellationToken.throwIfCancellationRequested(); - var fileContents = sourceFile.text; - var result: TodoComment[] = []; + let fileContents = sourceFile.text; + let result: TodoComment[] = []; if (descriptors.length > 0) { - var regExp = getTodoCommentsRegExp(); + let regExp = getTodoCommentsRegExp(); - var matchArray: RegExpExecArray; + let matchArray: RegExpExecArray; while (matchArray = regExp.exec(fileContents)) { cancellationToken.throwIfCancellationRequested(); @@ -5548,21 +5554,21 @@ module ts { // // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. // "hack" in position 4 means HACK did match. - var firstDescriptorCaptureIndex = 3; + let firstDescriptorCaptureIndex = 3; Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); - var preamble = matchArray[1]; - var matchPosition = matchArray.index + preamble.length; + let preamble = matchArray[1]; + let matchPosition = matchArray.index + preamble.length; // OK, we have found a match in the file. This is only an acceptable match if // it is contained within a comment. - var token = getTokenAtPosition(sourceFile, matchPosition); + let token = getTokenAtPosition(sourceFile, matchPosition); if (!isInsideComment(sourceFile, token, matchPosition)) { continue; } - var descriptor: TodoCommentDescriptor = undefined; - for (var i = 0, n = descriptors.length; i < n; i++) { + let descriptor: TodoCommentDescriptor = undefined; + for (let i = 0, n = descriptors.length; i < n; i++) { if (matchArray[i + firstDescriptorCaptureIndex]) { descriptor = descriptors[i]; } @@ -5575,7 +5581,7 @@ module ts { continue; } - var message = matchArray[2]; + let message = matchArray[2]; result.push({ descriptor: descriptor, message: message, @@ -5606,14 +5612,14 @@ module ts { // // The following three regexps are used to match the start of the text up to the TODO // comment portion. - var singleLineCommentStart = /(?:\/\/+\s*)/.source; - var multiLineCommentStart = /(?:\/\*+\s*)/.source; - var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + let singleLineCommentStart = /(?:\/\/+\s*)/.source; + let multiLineCommentStart = /(?:\/\*+\s*)/.source; + let anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; // Match any of the above three TODO comment start regexps. // Note that the outermost group *is* a capture group. We want to capture the preamble // so that we can determine the starting position of the TODO comment match. - var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + let preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; // Takes the descriptors and forms a regexp that matches them as if they were literals. // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: @@ -5623,17 +5629,17 @@ module ts { // Note that the outermost group is *not* a capture group, but the innermost groups // *are* capture groups. By capturing the inner literals we can determine after // matching which descriptor we are dealing with. - var literals = "(?:" + map(descriptors, d => "(" + escapeRegExp(d.text) + ")").join("|") + ")"; + let literals = "(?:" + map(descriptors, d => "(" + escapeRegExp(d.text) + ")").join("|") + ")"; // After matching a descriptor literal, the following regexp matches the rest of the // text up to the end of the line (or */). - var endOfLineOrEndOfComment = /(?:$|\*\/)/.source - var messageRemainder = /(?:.*?)/.source + let endOfLineOrEndOfComment = /(?:$|\*\/)/.source + let messageRemainder = /(?:.*?)/.source // This is the portion of the match we'll return as part of the TODO comment result. We // match the literal portion up to the end of the line or end of comment. - var messagePortion = "(" + literals + messageRemainder + ")"; - var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + let messagePortion = "(" + literals + messageRemainder + ")"; + let regExpString = preamble + messagePortion + endOfLineOrEndOfComment; // The final regexp will look like this: // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim @@ -5659,30 +5665,30 @@ module ts { function getRenameInfo(fileName: string, position: number): RenameInfo { synchronizeHostData(); - var sourceFile = getValidSourceFile(fileName); + let sourceFile = getValidSourceFile(fileName); - var node = getTouchingWord(sourceFile, position); + let node = getTouchingWord(sourceFile, position); // Can only rename an identifier. if (node && node.kind === SyntaxKind.Identifier) { - var symbol = typeInfoResolver.getSymbolAtLocation(node); + let symbol = typeInfoResolver.getSymbolAtLocation(node); // Only allow a symbol to be renamed if it actually has at least one declaration. if (symbol) { - var declarations = symbol.getDeclarations(); + let declarations = symbol.getDeclarations(); if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. - var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + let defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); if (defaultLibFileName) { for (let current of declarations) { - var sourceFile = current.getSourceFile(); + let sourceFile = current.getSourceFile(); if (sourceFile && getCanonicalFileName(ts.normalizePath(sourceFile.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { return getRenameInfoError(getLocaleSpecificMessage(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library.key)); } } } - var kind = getSymbolKind(symbol, typeInfoResolver, node); + let kind = getSymbolKind(symbol, typeInfoResolver, node); if (kind) { return { canRename: true, @@ -5757,7 +5763,7 @@ module ts { } function initializeNameTable(sourceFile: SourceFile): void { - var nameTable: Map = {}; + let nameTable: Map = {}; walk(sourceFile); sourceFile.nameTable = nameTable; @@ -5795,13 +5801,13 @@ module ts { /// Classifier export function createClassifier(): Classifier { - var scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false); + let scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false); /// We do not have a full parser support to know when we should parse a regex or not /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. - var noRegexTable: boolean[] = []; + let noRegexTable: boolean[] = []; noRegexTable[SyntaxKind.Identifier] = true; noRegexTable[SyntaxKind.StringLiteral] = true; noRegexTable[SyntaxKind.NumericLiteral] = true; @@ -5835,7 +5841,7 @@ module ts { // // Where on the second line, you will get the 'return' keyword, // a string literal, and a template end consisting of '} } `'. - var templateStack: SyntaxKind[] = []; + let templateStack: SyntaxKind[] = []; function isAccessibilityModifier(kind: SyntaxKind) { switch (kind) { @@ -5874,9 +5880,9 @@ module ts { // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), // we will be more conservative in order to avoid conflicting with the syntactic classifier. function getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult { - var offset = 0; - var token = SyntaxKind.Unknown; - var lastNonTriviaToken = SyntaxKind.Unknown; + let offset = 0; + let token = SyntaxKind.Unknown; + let lastNonTriviaToken = SyntaxKind.Unknown; // Empty out the template stack for reuse. while (templateStack.length > 0) { @@ -5916,7 +5922,7 @@ module ts { scanner.setText(text); - var result: ClassificationResult = { + let result: ClassificationResult = { finalLexState: EndOfLineState.Start, entries: [] }; @@ -5940,7 +5946,7 @@ module ts { // In order to determine if the user is potentially typing something generic, we use a // weak heuristic where we track < and > tokens. It's a weak heuristic, but should // work well enough in practice. - var angleBracketStack = 0; + let angleBracketStack = 0; do { token = scanner.scan(); @@ -5998,7 +6004,7 @@ module ts { // If we don't have anything on the template stack, // then we aren't trying to keep track of a previously scanned template head. if (templateStack.length > 0) { - var lastTemplateStackToken = lastOrUndefined(templateStack); + let lastTemplateStackToken = lastOrUndefined(templateStack); if (lastTemplateStackToken === SyntaxKind.TemplateHead) { token = scanner.reScanTemplateToken(); @@ -6028,26 +6034,26 @@ module ts { return result; function processToken(): void { - var start = scanner.getTokenPos(); - var end = scanner.getTextPos(); + let start = scanner.getTokenPos(); + let end = scanner.getTextPos(); addResult(end - start, classFromKind(token)); if (end >= text.length) { if (token === SyntaxKind.StringLiteral) { // Check to see if we finished up on a multiline string literal. - var tokenText = scanner.getTokenText(); + let tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { - var lastCharIndex = tokenText.length - 1; + let lastCharIndex = tokenText.length - 1; - var numBackslashes = 0; + let numBackslashes = 0; while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === CharacterCodes.backslash) { numBackslashes++; } // If we have an odd number of backslashes, then the multiline string is unclosed if (numBackslashes & 1) { - var quoteChar = tokenText.charCodeAt(0); + let quoteChar = tokenText.charCodeAt(0); result.finalLexState = quoteChar === CharacterCodes.doubleQuote ? EndOfLineState.InDoubleQuoteStringLiteral : EndOfLineState.InSingleQuoteStringLiteral; @@ -6192,7 +6198,7 @@ module ts { } /// getDefaultLibraryFilePath - declare var __dirname: string; + declare let __dirname: string; /** * Get the path of the default library file (lib.d.ts) as distributed with the typescript @@ -6213,7 +6219,7 @@ module ts { getNodeConstructor: kind => { function Node() { } - var proto = kind === SyntaxKind.SourceFile ? new SourceFileObject() : new NodeObject(); + let proto = kind === SyntaxKind.SourceFile ? new SourceFileObject() : new NodeObject(); proto.kind = kind; proto.pos = 0; proto.end = 0; diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 3a677c9506c..419d4819ba6 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -8,15 +8,15 @@ module ts.SignatureHelp { // will return the generic identifier that started the expression (e.g. "foo" in "foo[]; - var resolvedSignature = typeInfoResolver.getResolvedSignature(call, candidates); + let call = argumentInfo.invocation; + let candidates = []; + let resolvedSignature = typeInfoResolver.getResolvedSignature(call, candidates); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { @@ -211,7 +211,7 @@ module ts.SignatureHelp { */ function getImmediatelyContainingArgumentInfo(node: Node): ArgumentListInfo { if (node.parent.kind === SyntaxKind.CallExpression || node.parent.kind === SyntaxKind.NewExpression) { - var callExpression = node.parent; + let callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -230,8 +230,8 @@ module ts.SignatureHelp { node.kind === SyntaxKind.OpenParenToken) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + let list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); + let isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; Debug.assert(list !== undefined); return { kind: isTypeArgList ? ArgumentListKind.TypeArguments : ArgumentListKind.CallArguments, @@ -248,13 +248,13 @@ module ts.SignatureHelp { // - Between the type arguments and the arguments (greater than token) // - On the target of the call (parent.func) // - On the 'new' keyword in a 'new' expression - var listItemInfo = findListItemInfo(node); + let listItemInfo = findListItemInfo(node); if (listItemInfo) { - var list = listItemInfo.list; - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + let list = listItemInfo.list; + let isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; - var argumentIndex = getArgumentIndex(list, node); - var argumentCount = getArgumentCount(list); + let argumentIndex = getArgumentIndex(list, node); + let argumentCount = getArgumentCount(list); Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`); @@ -276,18 +276,18 @@ module ts.SignatureHelp { } } else if (node.kind === SyntaxKind.TemplateHead && node.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) { - var templateExpression = node.parent; - var tagExpression = templateExpression.parent; + let templateExpression = node.parent; + let tagExpression = templateExpression.parent; Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression); - var argumentIndex = isInsideTemplateLiteral(node, position) ? 0 : 1; + let argumentIndex = isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } else if (node.parent.kind === SyntaxKind.TemplateSpan && node.parent.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; + let templateSpan = node.parent; + let templateExpression = templateSpan.parent; + let tagExpression = templateExpression.parent; Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression); // If we're just after a template tail, don't show signature help. @@ -295,8 +295,8 @@ module ts.SignatureHelp { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); - var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node); + let spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + let argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node); return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } @@ -316,8 +316,8 @@ module ts.SignatureHelp { // on. In that case, even if we're after the trailing comma, we'll still see // that trailing comma in the list, and we'll have generated the appropriate // arg index. - var argumentIndex = 0; - var listChildren = argumentsList.getChildren(); + let argumentIndex = 0; + let listChildren = argumentsList.getChildren(); for (let child of listChildren) { if (child === node) { break; @@ -342,9 +342,9 @@ module ts.SignatureHelp { // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, givin us an // arg count of 3. - var listChildren = argumentsList.getChildren(); + let listChildren = argumentsList.getChildren(); - var argumentCount = countWhere(listChildren, arg => arg.kind !== SyntaxKind.CommaToken); + let argumentCount = countWhere(listChildren, arg => arg.kind !== SyntaxKind.CommaToken); if (listChildren.length > 0 && lastOrUndefined(listChildren).kind === SyntaxKind.CommaToken) { argumentCount++; } @@ -378,7 +378,7 @@ module ts.SignatureHelp { function getArgumentListInfoForTemplate(tagExpression: TaggedTemplateExpression, argumentIndex: number): ArgumentListInfo { // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. - var argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral + let argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral ? 1 : (tagExpression.template).templateSpans.length + 1; @@ -402,15 +402,15 @@ module ts.SignatureHelp { // // The applicable span is from the first bar to the second bar (inclusive, // but not including parentheses) - var applicableSpanStart = argumentsList.getFullStart(); - var applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + let applicableSpanStart = argumentsList.getFullStart(); + let applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getApplicableSpanForTaggedTemplate(taggedTemplate: TaggedTemplateExpression): TextSpan { - var template = taggedTemplate.template; - var applicableSpanStart = template.getStart(); - var applicableSpanEnd = template.getEnd(); + let template = taggedTemplate.template; + let applicableSpanStart = template.getStart(); + let applicableSpanEnd = template.getEnd(); // We need to adjust the end position for the case where the template does not have a tail. // Otherwise, we will not show signature help past the expression. @@ -422,7 +422,7 @@ module ts.SignatureHelp { // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === SyntaxKind.TemplateExpression) { - var lastSpan = lastOrUndefined((template).templateSpans); + let lastSpan = lastOrUndefined((template).templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -432,7 +432,7 @@ module ts.SignatureHelp { } function getContainingArgumentInfo(node: Node): ArgumentListInfo { - for (var n = node; n.kind !== SyntaxKind.SourceFile; n = n.parent) { + for (let n = node; n.kind !== SyntaxKind.SourceFile; n = n.parent) { if (isFunctionBlock(n)) { return undefined; } @@ -443,7 +443,7 @@ module ts.SignatureHelp { Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); } - var argumentInfo = getImmediatelyContainingArgumentInfo(n); + let argumentInfo = getImmediatelyContainingArgumentInfo(n); if (argumentInfo) { return argumentInfo; } @@ -455,8 +455,8 @@ module ts.SignatureHelp { } function getChildListThatStartsWithOpenerToken(parent: Node, openerToken: Node, sourceFile: SourceFile): Node { - var children = parent.getChildren(sourceFile); - var indexOfOpenerToken = children.indexOf(openerToken); + let children = parent.getChildren(sourceFile); + let indexOfOpenerToken = children.indexOf(openerToken); Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } @@ -470,10 +470,10 @@ module ts.SignatureHelp { * or the one with the most parameters. */ function selectBestInvalidOverloadIndex(candidates: Signature[], argumentCount: number): number { - var maxParamsSignatureIndex = -1; - var maxParams = -1; - for (var i = 0; i < candidates.length; i++) { - var candidate = candidates[i]; + let maxParamsSignatureIndex = -1; + let maxParams = -1; + for (let i = 0; i < candidates.length; i++) { + let candidate = candidates[i]; if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { return i; @@ -489,17 +489,17 @@ module ts.SignatureHelp { } function createSignatureHelpItems(candidates: Signature[], bestSignature: Signature, argumentListInfo: ArgumentListInfo): SignatureHelpItems { - var applicableSpan = argumentListInfo.argumentsSpan; - var isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments; + let applicableSpan = argumentListInfo.argumentsSpan; + let isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments; - var invocation = argumentListInfo.invocation; - var callTarget = getInvokedExpression(invocation) - var callTargetSymbol = typeInfoResolver.getSymbolAtLocation(callTarget); - var callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeInfoResolver, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); - var items: SignatureHelpItem[] = map(candidates, candidateSignature => { - var signatureHelpParameters: SignatureHelpParameter[]; - var prefixDisplayParts: SymbolDisplayPart[] = []; - var suffixDisplayParts: SymbolDisplayPart[] = []; + let invocation = argumentListInfo.invocation; + let callTarget = getInvokedExpression(invocation) + let callTargetSymbol = typeInfoResolver.getSymbolAtLocation(callTarget); + let callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeInfoResolver, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + let items: SignatureHelpItem[] = map(candidates, candidateSignature => { + let signatureHelpParameters: SignatureHelpParameter[]; + let prefixDisplayParts: SymbolDisplayPart[] = []; + let suffixDisplayParts: SymbolDisplayPart[] = []; if (callTargetDisplayParts) { prefixDisplayParts.push.apply(prefixDisplayParts, callTargetDisplayParts); @@ -507,25 +507,25 @@ module ts.SignatureHelp { if (isTypeParameterList) { prefixDisplayParts.push(punctuationPart(SyntaxKind.LessThanToken)); - var typeParameters = candidateSignature.typeParameters; + let typeParameters = candidateSignature.typeParameters; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken)); - var parameterParts = mapToDisplayParts(writer => + let parameterParts = mapToDisplayParts(writer => typeInfoResolver.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation)); suffixDisplayParts.push.apply(suffixDisplayParts, parameterParts); } else { - var typeParameterParts = mapToDisplayParts(writer => + let typeParameterParts = mapToDisplayParts(writer => typeInfoResolver.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation)); prefixDisplayParts.push.apply(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(punctuationPart(SyntaxKind.OpenParenToken)); - var parameters = candidateSignature.parameters; + let parameters = candidateSignature.parameters; signatureHelpParameters = parameters.length > 0 ? map(parameters, createSignatureHelpParameterForParameter) : emptyArray; suffixDisplayParts.push(punctuationPart(SyntaxKind.CloseParenToken)); } - var returnTypeParts = mapToDisplayParts(writer => + let returnTypeParts = mapToDisplayParts(writer => typeInfoResolver.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation)); suffixDisplayParts.push.apply(suffixDisplayParts, returnTypeParts); @@ -539,12 +539,12 @@ module ts.SignatureHelp { }; }); - var argumentIndex = argumentListInfo.argumentIndex; + let argumentIndex = argumentListInfo.argumentIndex; // argumentCount is the *apparent* number of arguments. - var argumentCount = argumentListInfo.argumentCount; + let argumentCount = argumentListInfo.argumentCount; - var selectedItemIndex = candidates.indexOf(bestSignature); + let selectedItemIndex = candidates.indexOf(bestSignature); if (selectedItemIndex < 0) { selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); } @@ -560,10 +560,10 @@ module ts.SignatureHelp { }; function createSignatureHelpParameterForParameter(parameter: Symbol): SignatureHelpParameter { - var displayParts = mapToDisplayParts(writer => + let displayParts = mapToDisplayParts(writer => typeInfoResolver.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation)); - var isOptional = hasQuestionToken(parameter.valueDeclaration); + let isOptional = hasQuestionToken(parameter.valueDeclaration); return { name: parameter.name, @@ -574,7 +574,7 @@ module ts.SignatureHelp { } function createSignatureHelpParameterForTypeParameter(typeParameter: TypeParameter): SignatureHelpParameter { - var displayParts = mapToDisplayParts(writer => + let displayParts = mapToDisplayParts(writer => typeInfoResolver.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation)); return { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 332ddffc910..452395f454a 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -7,18 +7,18 @@ module ts { export function getEndLinePosition(line: number, sourceFile: SourceFile): number { Debug.assert(line >= 0); - var lineStarts = sourceFile.getLineStarts(); + let lineStarts = sourceFile.getLineStarts(); - var lineIndex = line; + let lineIndex = line; if (lineIndex + 1 === lineStarts.length) { // last line - return EOF return sourceFile.text.length - 1; } else { // current line start - var start = lineStarts[lineIndex]; + let start = lineStarts[lineIndex]; // take the start position of the next line -1 = it should be some line break - var pos = lineStarts[lineIndex + 1] - 1; + let pos = lineStarts[lineIndex + 1] - 1; Debug.assert(isLineBreak(sourceFile.text.charCodeAt(pos))); // walk backwards skipping line breaks, stop the the beginning of current line. // i.e: @@ -32,8 +32,8 @@ module ts { } export function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number { - var lineStarts = sourceFile.getLineStarts(); - var line = sourceFile.getLineAndCharacterOfPosition(position).line; + let lineStarts = sourceFile.getLineStarts(); + let line = sourceFile.getLineAndCharacterOfPosition(position).line; return lineStarts[line]; } @@ -54,13 +54,13 @@ module ts { } export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number) { - var start = Math.max(start1, start2); - var end = Math.min(end1, end2); + let start = Math.max(start1, start2); + let end = Math.min(end1, end2); return start < end; } export function findListItemInfo(node: Node): ListItemInfo { - var list = findContainingList(node); + let list = findContainingList(node); // It is possible at this point for syntaxList to be undefined, either if // node.parent had no list child, or if none of its list children contained @@ -70,8 +70,8 @@ module ts { return undefined; } - var children = list.getChildren(); - var listItemIndex = indexOf(children, node); + let children = list.getChildren(); + let listItemIndex = indexOf(children, node); return { listItemIndex, @@ -88,7 +88,7 @@ module ts { // be parented by the container of the SyntaxList, not the SyntaxList itself. // In order to find the list item index, we first need to locate SyntaxList itself and then search // for the position of the relevant node (or comma). - var syntaxList = forEach(node.parent.getChildren(), c => { + let syntaxList = forEach(node.parent.getChildren(), c => { // find syntax list that covers the span of the node if (c.kind === SyntaxKind.SyntaxList && c.pos <= node.pos && c.end >= node.end) { return c; @@ -126,7 +126,7 @@ module ts { /** Get the token whose text contains the position */ function getTokenAtPositionWorker(sourceFile: SourceFile, position: number, allowPositionInLeadingTrivia: boolean, includeItemAtEndPosition: (n: Node) => boolean): Node { - var current: Node = sourceFile; + let current: Node = sourceFile; outer: while (true) { if (isToken(current)) { // exit early @@ -134,17 +134,17 @@ module ts { } // find the child that contains 'position' - for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { - var child = current.getChildAt(i); - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); + for (let i = 0, n = current.getChildCount(sourceFile); i < n; i++) { + let child = current.getChildAt(i); + let start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); if (start <= position) { - var end = child.getEnd(); + let end = child.getEnd(); if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) { current = child; continue outer; } else if (includeItemAtEndPosition && end === position) { - var previousToken = findPrecedingToken(position, sourceFile, child); + let previousToken = findPrecedingToken(position, sourceFile, child); if (previousToken && includeItemAtEndPosition(previousToken)) { return previousToken; } @@ -166,7 +166,7 @@ module ts { export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position); + let tokenAtPosition = getTokenAtPosition(file, position); if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -183,9 +183,9 @@ module ts { return n; } - var children = n.getChildren(); + let children = n.getChildren(); for (let child of children) { - var shouldDiveInChildNode = + let shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child @@ -208,8 +208,8 @@ module ts { return n; } - var children = n.getChildren(); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + let children = n.getChildren(); + let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); return candidate && findRightmostToken(candidate); } @@ -219,14 +219,14 @@ module ts { return n; } - var children = n.getChildren(); - for (var i = 0, len = children.length; i < len; i++) { + let children = n.getChildren(); + for (let i = 0, len = children.length; i < len; i++) { let child = children[i]; if (nodeHasTokens(child)) { if (position <= child.end) { if (child.getStart(sourceFile) >= position) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); return candidate && findRightmostToken(candidate) } else { @@ -244,14 +244,14 @@ module ts { // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); return candidate && findRightmostToken(candidate); } } /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' function findRightmostChildNodeWithTokens(children: Node[], exclusiveStartPosition: number): Node { - for (var i = exclusiveStartPosition - 1; i >= 0; --i) { + for (let i = exclusiveStartPosition - 1; i >= 0; --i) { if (nodeHasTokens(children[i])) { return children[i]; } @@ -266,8 +266,8 @@ module ts { } export function getNodeModifiers(node: Node): string { - var flags = getCombinedNodeFlags(node); - var result: string[] = []; + let flags = getCombinedNodeFlags(node); + let result: string[] = []; if (flags & NodeFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier); if (flags & NodeFlags.Protected) result.push(ScriptElementKindModifier.protectedMemberModifier); @@ -317,7 +317,7 @@ module ts { } export function compareDataObjects(dst: any, src: any): boolean { - for (var e in dst) { + for (let e in dst) { if (typeof dst[e] === "object") { if (!compareDataObjects(dst[e], src[e])) { return false; @@ -339,11 +339,11 @@ module ts { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === SyntaxKind.Parameter; } - var displayPartWriter = getDisplayPartWriter(); + let displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter(): DisplayPartsSymbolWriter { - var displayParts: SymbolDisplayPart[]; - var lineStart: boolean; - var indent: number; + let displayParts: SymbolDisplayPart[]; + let lineStart: boolean; + let indent: number; resetWriter(); return { @@ -364,7 +364,7 @@ module ts { function writeIndent() { if (lineStart) { - var indentString = getIndentString(indent); + let indentString = getIndentString(indent); if (indentString) { displayParts.push(displayPart(indentString, SymbolDisplayPartKind.space)); } @@ -398,7 +398,7 @@ module ts { return displayPart(text, displayPartKind(symbol), symbol); function displayPartKind(symbol: Symbol): SymbolDisplayPartKind { - var flags = symbol.flags; + let flags = symbol.flags; if (flags & SymbolFlags.Variable) { return isFirstDeclarationOfSymbolParameter(symbol) ? SymbolDisplayPartKind.parameterName : SymbolDisplayPartKind.localName; @@ -455,7 +455,7 @@ module ts { export function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] { writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); + let result = displayPartWriter.displayParts(); displayPartWriter.clear(); return result; } From e90a5dc5bb90c5bcf30505cb6c8d3b20b544e286 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Fri, 13 Mar 2015 13:43:46 -0700 Subject: [PATCH 19/19] Update baselines. --- tests/baselines/reference/APISample_compile.js | 4 ++-- tests/baselines/reference/APISample_compile.types | 4 ++-- tests/baselines/reference/APISample_linter.js | 4 ++-- tests/baselines/reference/APISample_linter.types | 4 ++-- tests/baselines/reference/APISample_transform.js | 4 ++-- tests/baselines/reference/APISample_transform.types | 4 ++-- tests/baselines/reference/APISample_watcher.js | 4 ++-- tests/baselines/reference/APISample_watcher.types | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/tests/baselines/reference/APISample_compile.js b/tests/baselines/reference/APISample_compile.js index 6e6adb2cd45..a03f254e699 100644 --- a/tests/baselines/reference/APISample_compile.js +++ b/tests/baselines/reference/APISample_compile.js @@ -1488,7 +1488,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -1975,7 +1975,7 @@ declare module "typescript" { throwIfCancellationRequested(): void; } function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createDocumentRegistry(): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; diff --git a/tests/baselines/reference/APISample_compile.types b/tests/baselines/reference/APISample_compile.types index 17ce175ebdf..bd19b3bbf9f 100644 --- a/tests/baselines/reference/APISample_compile.types +++ b/tests/baselines/reference/APISample_compile.types @@ -4768,7 +4768,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; >servicesVersion : string interface Node { @@ -6118,7 +6118,7 @@ declare module "typescript" { >setNodeParents : boolean >SourceFile : SourceFile - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; >disableIncrementalParsing : boolean function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/tests/baselines/reference/APISample_linter.js b/tests/baselines/reference/APISample_linter.js index 4f1fc899a89..99b7bc6d549 100644 --- a/tests/baselines/reference/APISample_linter.js +++ b/tests/baselines/reference/APISample_linter.js @@ -1519,7 +1519,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -2006,7 +2006,7 @@ declare module "typescript" { throwIfCancellationRequested(): void; } function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createDocumentRegistry(): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; diff --git a/tests/baselines/reference/APISample_linter.types b/tests/baselines/reference/APISample_linter.types index d1dcad98d85..0970d0cc2fb 100644 --- a/tests/baselines/reference/APISample_linter.types +++ b/tests/baselines/reference/APISample_linter.types @@ -4914,7 +4914,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; >servicesVersion : string interface Node { @@ -6264,7 +6264,7 @@ declare module "typescript" { >setNodeParents : boolean >SourceFile : SourceFile - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; >disableIncrementalParsing : boolean function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/tests/baselines/reference/APISample_transform.js b/tests/baselines/reference/APISample_transform.js index 3ef3d7bc0f5..105acc069be 100644 --- a/tests/baselines/reference/APISample_transform.js +++ b/tests/baselines/reference/APISample_transform.js @@ -1520,7 +1520,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -2007,7 +2007,7 @@ declare module "typescript" { throwIfCancellationRequested(): void; } function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createDocumentRegistry(): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; diff --git a/tests/baselines/reference/APISample_transform.types b/tests/baselines/reference/APISample_transform.types index 4bfac42f571..17cbd063332 100644 --- a/tests/baselines/reference/APISample_transform.types +++ b/tests/baselines/reference/APISample_transform.types @@ -4864,7 +4864,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; >servicesVersion : string interface Node { @@ -6214,7 +6214,7 @@ declare module "typescript" { >setNodeParents : boolean >SourceFile : SourceFile - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; >disableIncrementalParsing : boolean function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/tests/baselines/reference/APISample_watcher.js b/tests/baselines/reference/APISample_watcher.js index c85be654c89..1d67d4df950 100644 --- a/tests/baselines/reference/APISample_watcher.js +++ b/tests/baselines/reference/APISample_watcher.js @@ -1557,7 +1557,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; interface Node { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; @@ -2044,7 +2044,7 @@ declare module "typescript" { throwIfCancellationRequested(): void; } function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile; - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createDocumentRegistry(): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; diff --git a/tests/baselines/reference/APISample_watcher.types b/tests/baselines/reference/APISample_watcher.types index e4b53feeac0..7ecf2dca8ef 100644 --- a/tests/baselines/reference/APISample_watcher.types +++ b/tests/baselines/reference/APISample_watcher.types @@ -5037,7 +5037,7 @@ declare module "typescript" { } declare module "typescript" { /** The version of the language service API */ - var servicesVersion: string; + let servicesVersion: string; >servicesVersion : string interface Node { @@ -6387,7 +6387,7 @@ declare module "typescript" { >setNodeParents : boolean >SourceFile : SourceFile - var disableIncrementalParsing: boolean; + let disableIncrementalParsing: boolean; >disableIncrementalParsing : boolean function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;