diff --git a/Jakefile.js b/Jakefile.js index 517f5e862d510..d91e04bc0156c 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -361,7 +361,7 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca /*keepComments*/ true, /*noResolve*/ false, /*stripInternal*/ true, - /*callback*/ function () { + /*callback*/ function () { jake.cpR(servicesFile, nodePackageFile, {silent: true}); prependFile(copyright, standaloneDefinitionsFile); @@ -379,12 +379,12 @@ compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(se var lsslFile = path.join(builtLocalDirectory, "tslssl.js"); compileFile( - lsslFile, - languageServiceLibrarySources, + lsslFile, + languageServiceLibrarySources, [builtLocalDirectory, copyright].concat(languageServiceLibrarySources), - /*prefixes*/ [copyright], - /*useBuiltCompiler*/ true, - /*noOutFile*/ false, + /*prefixes*/ [copyright], + /*useBuiltCompiler*/ true, + /*noOutFile*/ false, /*generateDeclarations*/ true); // Local target to build the language service server library @@ -488,7 +488,7 @@ var refTest262Baseline = path.join(internalTests, "baselines/test262/reference") desc("Builds the test infrastructure using the built compiler"); task("tests", ["local", run].concat(libraryTargets)); -function exec(cmd, completeHandler) { +function exec(cmd, completeHandler, errorHandler) { var ex = jake.createExec([cmd], {windowsVerbatimArguments: true}); // Add listeners for output and error ex.addListener("stdout", function(output) { @@ -504,8 +504,12 @@ function exec(cmd, completeHandler) { complete(); }); ex.addListener("error", function(e, status) { - fail("Process exited with code " + status); - }) + if(errorHandler) { + errorHandler(e, status); + } else { + fail("Process exited with code " + status); + } + }); ex.run(); } @@ -721,3 +725,17 @@ task("update-sublime", [serverFile], function() { jake.cpR(serverFile, "../TypeScript-Sublime-Plugin/tsserver/"); jake.cpR(serverFile + ".map", "../TypeScript-Sublime-Plugin/tsserver/"); }); + +// if the codebase were free of linter errors we could make jake runtests +// run this task automatically +desc("Runs tslint on the compiler sources"); +task("lint", [], function() { + for(var i in compilerSources) { + var f = compilerSources[i]; + var cmd = 'tslint -f ' + f; + exec(cmd, + function() { console.log('SUCCESS: No linter errors'); }, + function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n'); + }); + } +}, { async: true }); diff --git a/package.json b/package.json index d6a8f538b78c6..82ab734d6f1df 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,8 @@ "mocha": "latest", "chai": "latest", "browserify": "latest", - "istanbul": "latest" + "istanbul": "latest", + "tslint": "latest" }, "scripts": { "test": "jake runtests" diff --git a/scripts/errorCheck.ts b/scripts/errorCheck.ts index 36489c5f3123a..a5cb27417f16e 100644 --- a/scripts/errorCheck.ts +++ b/scripts/errorCheck.ts @@ -74,7 +74,7 @@ fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, console.log('Consumed ' + allSrc.length + ' characters of source'); let count = 0; - console.log('== List of errors not used in source ==') + console.log('== List of errors not used in source =='); for (let errName of errorNames) { if (allSrc.indexOf(errName) < 0) { console.log(errName); @@ -84,4 +84,3 @@ fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, console.log(count + ' of ' + errorNames.length + ' errors are not used in source'); }); }); - diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 5a39e96b11903..802bf6df35835 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -11,7 +11,7 @@ namespace ts { } export function getModuleInstanceState(node: Node): ModuleInstanceState { - // A module is uninstantiated if it contains only + // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) { return ModuleInstanceState.NonInstantiated; @@ -53,7 +53,7 @@ namespace ts { } const enum ContainerFlags { - // The current node is not a container, and no container manipulation should happen before + // The current node is not a container, and no container manipulation should happen before // recursing into it. None = 0, @@ -90,13 +90,13 @@ namespace ts { let lastContainer: Node; // If this file is an external module, then it is automatically in strict-mode according to - // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // ES6. If it is not an external module, then we'll determine if it is in strict mode or // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). let inStrictMode = !!file.externalModuleIndicator; let symbolCount = 0; let Symbol = objectAllocator.getSymbolConstructor(); - let classifiableNames: Map = {}; + let classifiableNames: Map = {}; if (!file.locals) { bind(file); @@ -179,7 +179,7 @@ namespace ts { * @param parent - node's parent declaration. * @param node - The declaration to be added to the symbol table * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. */ function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { Debug.assert(!hasDynamicName(node)); @@ -192,13 +192,13 @@ namespace ts { // Check and see if the symbol table already has a symbol with this name. If not, // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict + // give the new symbol any flags *yet*. This ensures that it will not conflict // with the 'excludes' flags we pass in. // // If we do get an existing symbol, see if it conflicts with the new symbol we're // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this // declaration. // // If we created a new symbol, either because we didn't have a symbol with this name @@ -259,7 +259,7 @@ namespace ts { // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set // on it. There are 2 main reasons: // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // 1. We treat locals and exports of the same name as mutually exclusive within a container. // That means the binder will issue a Duplicate Identifier error if you mix locals and exports // with the same name in the same container. // TODO: Make this a more specific error and decouple it from the exclusion logic. @@ -282,11 +282,11 @@ namespace ts { } } - // All container nodes are kept on a linked list in declaration order. This list is used by - // the getLocalNameOfContainer function in the type checker to validate that the local name + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name // used for a container is unique. function bindChildren(node: Node) { - // Before we recurse into a node's chilren, we first save the existing parent, container + // Before we recurse into a node's chilren, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. let saveParent = parent; @@ -295,16 +295,16 @@ namespace ts { // This node will now be set as the parent of all of its children as we recurse into them. parent = node; - + // Depending on what kind of node this is, we may have to adjust the current container // and block-container. If the current node is a container, then it is automatically // considered the current block-container as well. Also, for containers that we know // may contain locals, we proactively initialize the .locals field. We do this because // it's highly likely that the .locals will be needed to place some child in (for example, // a parameter, or variable declaration). - // + // // However, we do not proactively create the .locals for block-containers because it's - // totally normal and common for block-containers to never actually have a block-scoped + // totally normal and common for block-containers to never actually have a block-scoped // variable in them. We don't want to end up allocating an object for every 'block' we // run into when most of them won't be necessary. // @@ -345,7 +345,7 @@ namespace ts { case SyntaxKind.TypeLiteral: case SyntaxKind.ObjectLiteralExpression: return ContainerFlags.IsContainer; - + case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: @@ -373,7 +373,7 @@ namespace ts { case SyntaxKind.Block: // do not treat blocks directly inside a function as a block-scoped-container. - // Locals that reside in this block should go to the function locals. Othewise 'x' + // Locals that reside in this block should go to the function locals. Othewise 'x' // would not appear to be a redeclaration of a block scoped local in the following // example: // @@ -386,7 +386,7 @@ namespace ts { // the block, then there would be no collision. // // By not creating a new block-scoped-container here, we ensure that both 'var x' - // and 'let x' go into the Function-container's locals, and we do get a collision + // and 'let x' go into the Function-container's locals, and we do get a collision // conflict. return isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer; } @@ -484,13 +484,13 @@ namespace ts { } function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean { - var body = node.kind === SyntaxKind.SourceFile ? node : (node).body; + let body = node.kind === SyntaxKind.SourceFile ? node : (node).body; if (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock) { for (let stat of (body).statements) { if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) { return true; } - } + }; } return false; } @@ -536,8 +536,8 @@ namespace ts { // For a given function symbol "<...>(...) => T" we want to generate a symbol identical // to the one we would get for: { <...>(...): T } // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); @@ -638,7 +638,7 @@ namespace ts { } function getStrictModeIdentifierMessage(node: Node) { - // Provide specialized messages to help the user understand why we think they're in + // Provide specialized messages to help the user understand why we think they're in // strict mode. if (getContainingClass(node)) { return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; @@ -696,7 +696,7 @@ namespace ts { } function getStrictModeEvalOrArgumentsMessage(node: Node) { - // Provide specialized messages to help the user understand why we think they're in + // Provide specialized messages to help the user understand why we think they're in // strict mode. if (getContainingClass(node)) { return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; @@ -760,24 +760,24 @@ namespace ts { function bind(node: Node) { node.parent = parent; - var savedInStrictMode = inStrictMode; + let savedInStrictMode = inStrictMode; if (!savedInStrictMode) { updateStrictMode(node); } // First we bind declaration nodes to a symbol if possible. We'll both create a symbol - // and then potentially add the symbol to an appropriate symbol table. Possible + // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: - // + // // 1) The 'exports' table of the current container's symbol. // 2) The 'members' table of the current container's symbol. // 3) The 'locals' table of the current container. // - // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols // (like TypeLiterals for example) will not be put in any table. bindWorker(node); - // Then we recurse into the children of the node to bind them as well. For certain + // Then we recurse into the children of the node to bind them as well. For certain // symbols we do specialized work when we recurse. For example, we'll keep track of // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. @@ -817,7 +817,7 @@ namespace ts { } } } - + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) function isUseStrictPrologueDirective(node: ExpressionStatement): boolean { let nodeText = getTextOfNodeFromSourceText(file.text, node.expression); @@ -972,9 +972,9 @@ namespace ts { let symbol = node.symbol; // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the + // 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 + // argument for each type parameter. It is an error to explicitly declare a static // property member with the name 'prototype'. // // Note: we check for this here because this class may be merging into a module. The @@ -1000,7 +1000,7 @@ namespace ts { function bindVariableDeclarationOrBindingElement(node: VariableDeclaration | BindingElement) { if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name) + checkStrictModeEvalOrArguments(node, node.name); } if (!isBindingPattern(node.name)) { @@ -1039,7 +1039,7 @@ namespace ts { declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); } - // If this is a property-parameter, then also declare the property symbol into the + // If this is a property-parameter, then also declare the property symbol into the // containing class. if (node.flags & NodeFlags.AccessibilityModifier && node.parent.kind === SyntaxKind.Constructor && @@ -1056,4 +1056,4 @@ namespace ts { : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } -} +} diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6b59bd2df2ba5..1eccfd32af741 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -25,12 +25,12 @@ namespace ts { // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers - // who set the cancellation token should catch if a cancellation exception occurs, and + // who set the cancellation token should catch if a cancellation exception occurs, and // should throw away and create a new TypeChecker. // // Currently we only support setting the cancellation token when getting diagnostics. This // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if - // they no longer need the information (for example, if the user started editing again). + // they no longer need the information (for example, if the user started editing again). let cancellationToken: CancellationToken; let Symbol = objectAllocator.getSymbolConstructor(); @@ -117,7 +117,7 @@ namespace ts { let globals: SymbolTable = {}; let globalESSymbolConstructorSymbol: Symbol; - + let getGlobalPromiseConstructorSymbol: () => Symbol; let globalObjectType: ObjectType; @@ -148,7 +148,7 @@ namespace ts { let getInstantiatedGlobalPromiseLikeType: () => ObjectType; let getGlobalPromiseConstructorLikeType: () => ObjectType; let getGlobalThenableType: () => ObjectType; - + let tupleTypes: Map = {}; let unionTypes: Map = {}; let intersectionTypes: Map = {}; @@ -158,7 +158,7 @@ namespace ts { let emitParam = false; let emitAwaiter = false; let emitGenerator = false; - + let resolutionTargets: Object[] = []; let resolutionResults: boolean[] = []; @@ -323,7 +323,7 @@ namespace ts { function getSymbolLinks(symbol: Symbol): SymbolLinks { if (symbol.flags & SymbolFlags.Transient) return symbol; - var id = getSymbolId(symbol); + let id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); } @@ -406,7 +406,7 @@ namespace ts { let moduleExports = getSymbolOfNode(location).exports; if (location.kind === SyntaxKind.SourceFile || (location.kind === SyntaxKind.ModuleDeclaration && (location).name.kind === SyntaxKind.StringLiteral)) { - + // It's an external module. Because of module/namespace merging, a module's exports are in scope, // yet we never want to treat an export specifier as putting a member in scope. Therefore, // if the name we find is purely an export specifier, it is not actually considered in scope. @@ -526,7 +526,7 @@ namespace ts { } break; case SyntaxKind.Decorator: - // Decorators are resolved at the class declaration. Resolving at the parameter + // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // // function y() {} @@ -581,7 +581,7 @@ namespace ts { } function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { - Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0) + Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0); // Block-scoped variables cannot be used before their definition let declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); @@ -671,7 +671,7 @@ namespace ts { } function getTargetOfNamespaceImport(node: NamespaceImport): Symbol { - var moduleSpecifier = (node.parent.parent).moduleSpecifier; + let moduleSpecifier = (node.parent.parent).moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } @@ -726,7 +726,7 @@ namespace ts { function getPropertyOfVariable(symbol: Symbol, name: string): Symbol { if (symbol.flags & SymbolFlags.Variable) { - var typeAnnotation = (symbol.valueDeclaration).type; + let typeAnnotation = (symbol.valueDeclaration).type; if (typeAnnotation) { return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } @@ -1348,7 +1348,7 @@ namespace ts { // Mark the unexported alias as visible if its parent is visible // because these kind of aliases can be used to name types in declaration file - var anyImportSyntax = getAnyImportSyntax(declaration); + let anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && !(anyImportSyntax.flags & NodeFlags.Export) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { @@ -2098,7 +2098,7 @@ namespace ts { case SyntaxKind.ParenthesizedType: return isDeclarationVisible(node.parent); - // Default binding, import specifier and namespace import is visible + // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible case SyntaxKind.ImportClause: case SyntaxKind.NamespaceImport: @@ -2130,14 +2130,14 @@ namespace ts { } function collectLinkedAliases(node: Identifier): Node[] { - var exportSymbol: Symbol; + let exportSymbol: Symbol; if (node.parent && node.parent.kind === SyntaxKind.ExportAssignment) { exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === SyntaxKind.ExportSpecifier) { exportSymbol = getTargetOfExportSpecifier(node.parent); } - var result: Node[] = []; + let result: Node[] = []; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } @@ -2146,16 +2146,16 @@ namespace ts { function buildVisibleNodeList(declarations: Declaration[]) { forEach(declarations, declaration => { getNodeLinks(declaration).isVisible = true; - var resultNode = getAnyImportSyntax(declaration) || declaration; + let resultNode = getAnyImportSyntax(declaration) || declaration; if (!contains(result, resultNode)) { result.push(resultNode); } if (isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible - var internalModuleReference = (declaration).moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, + let internalModuleReference = (declaration).moduleReference; + let firstIdentifier = getFirstIdentifier(internalModuleReference); + let importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, firstIdentifier); buildVisibleNodeList(importSymbol.declarations); } @@ -2650,7 +2650,7 @@ namespace ts { // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] { - var declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + let declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); return appendOuterTypeParameters(undefined, declaration); } @@ -3864,7 +3864,7 @@ namespace ts { function getGlobalType(name: string, arity = 0): ObjectType { return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); } - + function tryGetGlobalType(name: string, arity = 0): ObjectType { return getTypeOfGlobalSymbol(getGlobalSymbol(name, SymbolFlags.Type, /*diagnostic*/ undefined), arity); } @@ -3874,8 +3874,8 @@ namespace ts { * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace: string, name: string): Type { - var namespaceSymbol = getGlobalSymbol(namespace, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, SymbolFlags.Type); + let namespaceSymbol = getGlobalSymbol(namespace, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined); + let typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, SymbolFlags.Type); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } @@ -3892,7 +3892,7 @@ namespace ts { ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) : emptyObjectType; } - + /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -4117,7 +4117,7 @@ namespace ts { } return links.resolvedType; } - + function getTypeFromTypeNode(node: TypeNode): Type { switch (node.kind) { case SyntaxKind.AnyKeyword: @@ -4233,7 +4233,7 @@ namespace ts { } } return t; - } + }; } function identityMapper(type: Type): Type { @@ -4269,7 +4269,7 @@ namespace ts { parameterName: signature.typePredicate.parameterName, parameterIndex: signature.typePredicate.parameterIndex, type: instantiateType(signature.typePredicate.type, mapper) - } + }; } let result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), @@ -4697,7 +4697,6 @@ namespace ts { } 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 @@ -6053,7 +6052,7 @@ namespace ts { error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } } - + if (node.parserContextFlags & ParserContextFlags.Await) { getNodeLinks(container).flags |= NodeCheckFlags.CaptureArguments; getNodeLinks(node).flags |= NodeCheckFlags.LexicalArguments; @@ -6746,7 +6745,7 @@ namespace ts { // c is represented in the tree as a spread element in an array literal. // But c really functions as a rest element, and its purpose is to provide // a contextual type for the right hand side of the assignment. Therefore, - // instead of calling checkExpression on "...c", which will give an error + // instead of calling checkExpression on "...c", which will give an error // if c is not iterable/array-like, we need to act as if we are trying to // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error @@ -6754,7 +6753,7 @@ namespace ts { let restArrayType = checkExpression((e).expression, contextualMapper); let restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); - if (restElementType) { + if (restElementType) { elementTypes.push(restElementType); } } @@ -7214,7 +7213,7 @@ namespace ts { return links.resolvedJsxType = anyType; } - var propsName = getJsxElementPropertiesName(); + let propsName = getJsxElementPropertiesName(); if (propsName === undefined) { // There is no type ElementAttributesProperty, return 'any' return links.resolvedJsxType = anyType; @@ -7224,7 +7223,7 @@ namespace ts { return links.resolvedJsxType = elemInstanceType; } else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + let attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); if (!attributesType) { // There is no property named 'props' on this instance type @@ -7381,7 +7380,7 @@ namespace ts { */ function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { let flags = getDeclarationFlagsFromSymbol(prop); - let declaringClass = getDeclaredTypeOfSymbol(prop.parent);; + let declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === SyntaxKind.SuperKeyword) { let errorNode = node.kind === SyntaxKind.PropertyAccessExpression ? @@ -7405,7 +7404,7 @@ namespace ts { if (flags & NodeFlags.Abstract) { // A method cannot be accessed in a super property access if the method is abstract. - // This error could mask a private property access error. But, a member + // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. @@ -7484,7 +7483,7 @@ namespace ts { } return unknownType; } - + getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & SymbolFlags.Class) { @@ -7881,7 +7880,7 @@ namespace ts { let paramType = getTypeAtPosition(signature, i); let argType = getEffectiveArgumentType(node, i, arg); - // If the effective argument type is 'undefined', there is no synthetic type + // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all @@ -7953,8 +7952,8 @@ namespace ts { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) let paramType = getTypeAtPosition(signature, i); let argType = getEffectiveArgumentType(node, i, arg); - - // If the effective argument type is 'undefined', there is no synthetic type + + // If the effective argument type is 'undefined', there is no synthetic type // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === SyntaxKind.StringLiteral && !reportErrors @@ -8007,18 +8006,17 @@ namespace ts { return args; } - /** * Returns the effective argument count for a node that works like a function invocation. * If 'node' is a Decorator, the number of arguments is derived from the decoration * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument + * If 'node.target' is a class declaration or class expression, the effective argument * count is 1. * If 'node.target' is a parameter declaration, the effective argument count is 3. * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count + * If 'node.target' is a method or accessor declaration, the effective argument count * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. + * us to match a property decorator. * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node: CallLikeExpression, args: Expression[], signature: Signature) { @@ -8030,7 +8028,7 @@ namespace ts { return 1; case SyntaxKind.PropertyDeclaration: - // A property declaration decorator will have two arguments (see + // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; @@ -8039,12 +8037,12 @@ namespace ts { case SyntaxKind.SetAccessor: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If the method decorator signature only accepts a target and a key, we will only + // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; case SyntaxKind.Parameter: - // A parameter declaration decorator will have three arguments (see + // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -8054,47 +8052,47 @@ namespace ts { return args.length; } } - + /** * Returns the effective type of the first argument to a decorator. * If 'node' is a class declaration or class expression, the effective argument type * is the type of the static side of the class. * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, + * of the static or instance side of the class for the parameter's parent method, * depending on whether the method is declared static. * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. */ function getEffectiveDecoratorFirstArgumentType(node: Node): Type { // The first argument to a decorator is its `target`. switch (node.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: - // For a class decorator, the `target` is the type of the class (e.g. the + // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) let classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); case SyntaxKind.Parameter: - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. node = node.parent; if (node.kind === SyntaxKind.Constructor) { let classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - + // fall-through - - case SyntaxKind.PropertyDeclaration: + + case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the + // declared "static"; otherwise, it is the "instance"-side type of the // parent of the member. return getParentTypeOfClassElement(node); @@ -8103,19 +8101,19 @@ namespace ts { return unknownType; } } - + /** * Returns the effective type for the second argument to a decorator. * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * If 'node.parent' is a constructor, the effective argument type is 'any', as we * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * If 'node.parent' is a member with an identifier, numeric, or string literal name, * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will + * If 'node.parent' is a computed property name, the effective argument type will * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the + * If 'node' is a member with an identifier, numeric, or string literal name, the * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either + * If 'node' is a computed property name, the effective argument type will either * be a symbol type or the string type. * A class decorator does not have a second argument type. */ @@ -8132,18 +8130,18 @@ namespace ts { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } - - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - - // fall-through - - case SyntaxKind.PropertyDeclaration: + + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + + // fall-through + + case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; + // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. let element = node; @@ -8167,17 +8165,17 @@ namespace ts { return unknownType; } - - default: + + default: Debug.fail("Unsupported decorator target."); return unknownType; } } - + /** * Returns the effective argument type for the third argument to a decorator. * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a + * If 'node' is a method or accessor, the effective argument type is a * `TypedPropertyDescriptor` instantiated with the type of the member. * Class and property decorators do not have a third effective argument. */ @@ -8210,7 +8208,7 @@ namespace ts { return unknownType; } } - + /** * Returns the effective argument type for the provided argument to a decorator. */ @@ -8228,12 +8226,12 @@ namespace ts { Debug.fail("Decorators should not have a fourth synthetic argument."); return unknownType; } - + /** * Gets the effective argument type for an argument in a call expression. */ function getEffectiveArgumentType(node: CallLikeExpression, argIndex: number, arg: Expression): Type { - // Decorators provide special arguments, a tagged template expression provides + // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors if (node.kind === SyntaxKind.Decorator) { @@ -8244,12 +8242,12 @@ namespace ts { } // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. + // to signal that the caller needs to check the argument. return undefined; } - + /** - * Gets the effective argument expression for an argument in a call expression. + * Gets the effective argument expression for an argument in a call expression. */ function getEffectiveArgument(node: CallLikeExpression, args: Expression[], argIndex: number) { // For a decorator or the first argument of a tagged template expression we return undefined. @@ -8315,7 +8313,7 @@ namespace ts { // For a tagged template, then the first argument be 'undefined' if necessary // because it represents a TemplateStringsArray. // - // For a decorator, no arguments are susceptible to contextual typing due to the fact + // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. let excludeArgument: boolean[]; if (!isDecorator) { @@ -8395,7 +8393,7 @@ namespace ts { } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, headMessage) + checkTypeArguments(candidateForTypeArgumentError, (node).typeArguments, [], /*reportErrors*/ true, headMessage); } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -8460,7 +8458,7 @@ namespace ts { let typeArgumentTypes: Type[]; if (typeArguments) { typeArgumentTypes = new Array(candidate.typeParameters.length); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false) + typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); @@ -8657,7 +8655,7 @@ namespace ts { return resolveCall(node, callSignatures, candidatesOutArray); } - + /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. */ @@ -8803,7 +8801,7 @@ namespace ts { links.type = instantiateType(getTypeOfSymbol(lastOrUndefined(context.parameters)), mapper); } } - + function createPromiseType(promisedType: Type): Type { // creates a `Promise` type where `T` is the promisedType argument let globalPromiseType = getGlobalPromiseType(); @@ -8812,7 +8810,7 @@ namespace ts { promisedType = getAwaitedType(promisedType); return createTypeReference(globalPromiseType, [promisedType]); } - + return emptyObjectType; } @@ -8821,15 +8819,15 @@ namespace ts { if (!func.body) { return unknownType; } - + let isAsync = isAsyncFunctionLike(func); let type: Type; if (func.body.kind !== SyntaxKind.Block) { - type = checkExpressionCached(func.body, contextualMapper); + type = checkExpressionCached(func.body, contextualMapper); if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body should be unwrapped to its awaited type, which we will wrap in + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in // the native Promise type later in this function. type = checkAwaitedType(type, func, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } @@ -8858,13 +8856,13 @@ namespace ts { error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); return unknownType; } - + return promiseType; } else { return voidType; } - } + } } // When yield/return statements are contextually typed we allow the return type to be a union type. // Otherwise we require the yield/return expressions to have a best common supertype. @@ -8887,19 +8885,19 @@ namespace ts { if (!contextualSignature) { reportErrorsFromWidening(func, type); } - + let widenedType = getWidenedType(type); if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. let promiseType = createPromiseType(widenedType); if (promiseType === emptyObjectType) { error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); return unknownType; } - - return promiseType; + + return promiseType; } else { return widenedType; @@ -8934,13 +8932,13 @@ namespace ts { forEachReturnStatement(body, returnStatement => { let expr = returnStatement.expression; if (expr) { - let type = checkExpressionCached(expr, contextualMapper); + let type = checkExpressionCached(expr, contextualMapper); if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in // the native Promise type by the caller. - type = checkAwaitedType(type, body.parent, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + type = checkAwaitedType(type, body.parent, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); } if (!contains(aggregatedTypes, type)) { @@ -9012,12 +9010,12 @@ namespace ts { if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } - + let isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - + let links = getNodeLinks(node); let type = getTypeOfSymbol(node.symbol); // Check if function expression is contextually typed and assign parameter types if so @@ -9054,7 +9052,7 @@ namespace ts { function checkFunctionExpressionOrObjectLiteralMethodBody(node: FunctionExpression | MethodDeclaration) { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); - + let isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; @@ -9065,7 +9063,7 @@ namespace ts { if (returnType && isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - + if (returnType && !node.asteriskToken) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); } @@ -9084,10 +9082,10 @@ namespace ts { checkSourceElement(node.body); } else { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so we - // should not be checking assignability of a promise to the return type. Instead, we need to - // check assignability of the awaited type of the expression body against the promised type of + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. let exprType = checkExpression(node.body); if (returnType) { @@ -9099,7 +9097,7 @@ namespace ts { checkTypeAssignableTo(exprType, returnType, node.body); } } - + checkFunctionAndClassExpressionBodies(node.body); } } @@ -9221,7 +9219,7 @@ namespace ts { let operandType = checkExpression(node.expression); return checkAwaitedType(operandType, node); } - + function checkPrefixUnaryExpression(node: PrefixUnaryExpression): Type { let operandType = checkExpression(node.operand); switch (node.operator) { @@ -9608,7 +9606,7 @@ namespace ts { } function isYieldExpressionInClass(node: YieldExpression): boolean { - let current: Node = node + let current: Node = node; let parent = node.parent; while (parent) { if (isFunctionLike(parent) && current === (parent).body) { @@ -9694,7 +9692,7 @@ namespace ts { node.contextualType = saveContextualType; return result; } - + function checkExpressionCached(node: Expression, contextualMapper?: TypeMapper): Type { let links = getNodeLinks(node); if (!links.resolvedType) { @@ -9901,7 +9899,7 @@ namespace ts { if (node.questionToken && isBindingPattern(node.name) && func.body) { error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } - + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. if (node.dotDotDotToken && !isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { @@ -10119,10 +10117,10 @@ namespace ts { // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration checkFunctionLikeDeclaration(node); - + // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if(node.flags & NodeFlags.Abstract && node.body) { + if (node.flags & NodeFlags.Abstract && node.body) { error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name)); } } @@ -10554,7 +10552,7 @@ namespace ts { } // Abstract methods can't have an implementation -- in particular, they don't need one. - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & NodeFlags.Abstract) ) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -10672,13 +10670,13 @@ namespace ts { if (!message) { message = Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; } - + error(location, message); } - + return unknownType; } - + return type; } @@ -10696,16 +10694,16 @@ namespace ts { // ) => any // ): any; // } - // - + // + if (promise.flags & TypeFlags.Any) { return undefined; } - + if ((promise.flags & TypeFlags.Reference) && (promise).target === tryGetGlobalPromiseType()) { return (promise).typeArguments[0]; } - + let globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; @@ -10715,58 +10713,58 @@ namespace ts { if (thenFunction && (thenFunction.flags & TypeFlags.Any)) { return undefined; } - + let thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray; if (thenSignatures.length === 0) { return undefined; } - + let onfulfilledParameterType = getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)); if (onfulfilledParameterType.flags & TypeFlags.Any) { return undefined; } - + let onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - + let valueParameterType = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); return valueParameterType; } - + function getTypeOfFirstParameterOfSignature(signature: Signature) { return getTypeAtPosition(signature, 0); } - + /** * Gets the "awaited type" of a type. * @param type The type to await. - * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a * Promise-like type; otherwise, it is the type of the expression. This is used to reflect * The runtime behavior of the `await` keyword. */ function getAwaitedType(type: Type) { return checkAwaitedType(type, /*location*/ undefined, /*message*/ undefined); } - + function checkAwaitedType(type: Type, location?: Node, message?: DiagnosticMessage) { return checkAwaitedTypeWorker(type); - + function checkAwaitedTypeWorker(type: Type): Type { if (type.flags & TypeFlags.Union) { let types: Type[] = []; for (let constituentType of (type).types) { types.push(checkAwaitedTypeWorker(constituentType)); } - + return getUnionType(types); } else { let promisedType = getPromisedType(type); if (promisedType === undefined) { // The type was not a PromiseLike, so it could not be unwrapped any further. - // As long as the type does not have a callable "then" property, it is + // As long as the type does not have a callable "then" property, it is // safe to return the type; otherwise, an error will have been reported in // the call to checkNonThenableType and we will return unknownType. // @@ -10777,7 +10775,7 @@ namespace ts { // The "thenable" does not match the minimal definition for a PromiseLike. When // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise // will never settle. We treat this as an error to help flag an early indicator - // of a runtime problem. If the user wants to return this value from an async + // of a runtime problem. If the user wants to return this value from an async // function, they would need to wrap it in some other value. If they want it to // be treated as a promise, they can cast to . return checkNonThenableType(type, location, message); @@ -10785,70 +10783,70 @@ namespace ts { else { if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // We have a bad actor in the form of a promise whose promised type is - // the same promise type, or a mutually recursive promise. Return the - // unknown type as we cannot guess the shape. If this were the actual + // the same promise type, or a mutually recursive promise. Return the + // unknown type as we cannot guess the shape. If this were the actual // case in the JavaScript, this Promise would never resolve. // - // An example of a bad actor with a singly-recursive promise type might + // An example of a bad actor with a singly-recursive promise type might // be: // // interface BadPromise { // then( - // onfulfilled: (value: BadPromise) => any, + // onfulfilled: (value: BadPromise) => any, // onrejected: (error: any) => any): BadPromise; // } // - // The above interface will pass the PromiseLike check, and return a - // promised type of `BadPromise`. Since this is a self reference, we + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we // don't want to keep recursing ad infinitum. // - // An example of a bad actor in the form of a mutually-recursive + // An example of a bad actor in the form of a mutually-recursive // promise type might be: // // interface BadPromiseA { // then( - // onfulfilled: (value: BadPromiseB) => any, + // onfulfilled: (value: BadPromiseB) => any, // onrejected: (error: any) => any): BadPromiseB; // } // // interface BadPromiseB { // then( - // onfulfilled: (value: BadPromiseA) => any, + // onfulfilled: (value: BadPromiseA) => any, // onrejected: (error: any) => any): BadPromiseA; // } // if (location) { error( - location, - Diagnostics._0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method, + location, + Diagnostics._0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method, symbolToString(type.symbol)); } - + return unknownType; } - + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. // See the comments above for more information. awaitedTypeStack.push(type.id); let awaitedType = checkAwaitedTypeWorker(promisedType); awaitedTypeStack.pop(); - return awaitedType; + return awaitedType; } } } } /** - * Checks the return type of an async function to ensure it is a compatible + * Checks the return type of an async function to ensure it is a compatible * Promise implementation. * @param node The signature to check * @param returnType The return type for the function - * @remarks - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a + * @remarks + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a + * a `resolve` function as one of its arguments and results in an object with a * callable `then` signature. */ function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { @@ -10861,7 +10859,7 @@ namespace ts { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics - // for __awaiter, we must also check that the type of the declaration (e.g. the static + // for __awaiter, we must also check that the type of the declaration (e.g. the static // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. // // An example might be (from lib.es6.d.ts): @@ -10869,11 +10867,11 @@ namespace ts { // interface Promise { ... } // interface PromiseConstructor { // new (...): Promise; - // } + // } // declare var Promise: PromiseConstructor; // - // When an async function declares a return type annotation of `Promise`, we - // need to get the type of the `Promise` variable declaration above, which would + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would // be `PromiseConstructor`. // // The same case applies to a class: @@ -10885,20 +10883,20 @@ namespace ts { // // When we get the type of the `Promise` symbol here, we get the type of the static // side of the `Promise` class, which would be `{ new (...): Promise }`. - + let promiseType = getTypeFromTypeNode(node.type); if (promiseType === unknownType && compilerOptions.isolatedModules) { - // If we are compiling with isolatedModules, we may not be able to resolve the + // If we are compiling with isolatedModules, we may not be able to resolve the // type as a value. As such, we will just return unknownType; return unknownType; } - + let promiseConstructor = getMergedSymbol(promiseType.symbol); if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { error(node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeToString(promiseType)); - return unknownType + return unknownType; } - + // Validate the promise constructor type. let promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { @@ -10919,7 +10917,7 @@ namespace ts { // Get and return the awaited type of the return type. return checkAwaitedType(promiseType, node, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); } - + /** Check a decorator */ function checkDecorator(node: Decorator): void { let signature = getResolvedSignature(node); @@ -10969,11 +10967,11 @@ namespace ts { headMessage, errorInfo); } - + /** Checks a type reference node as an expression. */ function checkTypeNodeAsExpression(node: TypeNode) { // When we are emitting type metadata for decorators, we need to try to check the type - // as if it were an expression so that we can emit the type in a value position when we + // as if it were an expression so that we can emit the type in a value position when we // serialize the type metadata. if (node && node.kind === SyntaxKind.TypeReference) { let type = getTypeFromTypeNode(node); @@ -10988,7 +10986,7 @@ namespace ts { } /** - * Checks the type annotation of an accessor declaration or property declaration as + * Checks the type annotation of an accessor declaration or property declaration as * an expression if it is a type reference to a type with a value declaration. */ function checkTypeAnnotationAsExpression(node: AccessorDeclaration | PropertyDeclaration | ParameterDeclaration | MethodDeclaration) { @@ -11010,7 +11008,7 @@ namespace ts { break; } } - + /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node: FunctionLikeDeclaration) { // ensure all type annotations with a value declaration are checked as an expression @@ -11039,7 +11037,7 @@ namespace ts { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { case SyntaxKind.ClassDeclaration: - var constructor = getFirstConstructorWithBody(node); + let constructor = getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } @@ -11084,9 +11082,9 @@ namespace ts { if (!compilerOptions.experimentalAsyncFunctions) { error(node, Diagnostics.Experimental_support_for_async_functions_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalAsyncFunctions_to_remove_this_warning); } - + emitAwaiter = true; - } + } // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including @@ -11126,7 +11124,7 @@ namespace ts { if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - + checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); } @@ -11304,7 +11302,7 @@ namespace ts { return; } - var symbol = getSymbolOfNode(node); + let symbol = getSymbolOfNode(node); if (symbol.flags & SymbolFlags.FunctionScopedVariable) { let localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); if (localDeclarationSymbol && @@ -11338,7 +11336,7 @@ namespace ts { } } } - + // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node: VariableLikeDeclaration): void { if (getRootDeclaration(node).kind !== SyntaxKind.Parameter) { @@ -11459,7 +11457,7 @@ namespace ts { if (inBlockOrObjectLiteralExpression(node)) { if (isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { - return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); + return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); } } else { @@ -11477,7 +11475,7 @@ namespace ts { node = node.parent; } - + return false; } @@ -11523,10 +11521,10 @@ namespace ts { if (node.initializer) { if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - forEach((node.initializer).declarations, checkVariableDeclaration) + forEach((node.initializer).declarations, checkVariableDeclaration); } else { - checkExpression(node.initializer) + checkExpression(node.initializer); } } @@ -11536,7 +11534,7 @@ namespace ts { } function checkForOfStatement(node: ForOfStatement): void { - checkGrammarForInOrForOfStatement(node) + checkGrammarForInOrForOfStatement(node); // Check the LHS and RHS // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS @@ -11672,7 +11670,7 @@ namespace ts { return elementType || anyType; } - + /** * We want to treat type as an iterable, and get the type it is an iterable of. The iterable * must have the following structure (annotated with the names of the variables below): @@ -12029,7 +12027,7 @@ namespace ts { let identifierName = (catchClause.variableDeclaration.name).text; let locals = catchClause.block.locals; if (locals && hasProperty(locals, identifierName)) { - let 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); } @@ -12178,7 +12176,7 @@ namespace ts { // Interfaces cannot be merged with non-ambient classes. if (getSymbolOfNode(node).flags & SymbolFlags.Interface && !isInAmbientContext(node)) { - error(node, Diagnostics.Only_an_ambient_class_can_be_merged_with_an_interface) + error(node, Diagnostics.Only_an_ambient_class_can_be_merged_with_an_interface); } forEach(node.members, checkSourceElement); @@ -12299,20 +12297,20 @@ namespace ts { // In order to resolve whether the inherited method was overriden in the base class or not, // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* // type declaration, derived and base resolve to the same symbol even in the case of generic classes. - if (derived === base) { + if (derived === base) { // derived class inherits base without override/redeclaration let derivedClassDecl = getDeclarationOfKind(type.symbol, SyntaxKind.ClassDeclaration); // It is an error to inherit an abstract member without implementing it or being declared abstract. - // If there is no declaration for the derived class (as in the case of class expressions), - // then the class cannot be declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. if ( baseDeclarationFlags & NodeFlags.Abstract && (!derivedClassDecl || !(derivedClassDecl.flags & NodeFlags.Abstract))) { error(derivedClassDecl, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); } } - else { + else { // derived overrides base. let derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); if ((baseDeclarationFlags & NodeFlags.Private) || (derivedDeclarationFlags & NodeFlags.Private)) { @@ -12610,7 +12608,7 @@ namespace ts { } // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName - var current = expression; + let current = expression; while (current) { if (current.kind === SyntaxKind.Identifier) { break; @@ -12783,7 +12781,7 @@ namespace ts { } } - // if the module merges with a class declaration in the same lexical scope, + // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. let mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); if (mergedClass && @@ -13317,7 +13315,7 @@ namespace ts { forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); potentialThisCollisions.length = 0; } - + if (emitExtends) { links.flags |= NodeCheckFlags.EmitExtends; } @@ -13329,11 +13327,11 @@ namespace ts { if (emitParam) { links.flags |= NodeCheckFlags.EmitParam; } - + if (emitAwaiter) { links.flags |= NodeCheckFlags.EmitAwaiter; } - + if (emitGenerator || (emitAwaiter && languageVersion < ScriptTarget.ES6)) { links.flags |= NodeCheckFlags.EmitGenerator; } @@ -13732,7 +13730,7 @@ namespace ts { } /** - * Gets either the static or instance type of a class element, based on + * Gets either the static or instance type of a class element, based on * whether the element is declared as "static". */ function getParentTypeOfClassElement(node: ClassElement) { @@ -13741,7 +13739,7 @@ namespace ts { ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } - + // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type: Type): Symbol[] { @@ -13874,7 +13872,7 @@ namespace ts { return false; } - var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + let isValue = isAliasResolvedToValue(getSymbolOfNode(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } @@ -13958,7 +13956,7 @@ namespace ts { // here has no effect anyway as an identifier in a type name is not an expression. // var substitution = getExpressionNameSubstitution(node, getGeneratedNameForNode); // var text = substitution || (node).text; - var text = (node).text; + let text = (node).text; if (fallbackPath) { fallbackPath.push(text); } @@ -13967,8 +13965,8 @@ namespace ts { } } else { - var left = serializeEntityName((node).left, fallbackPath); - var right = serializeEntityName((node).right, fallbackPath); + let left = serializeEntityName((node).left, fallbackPath); + let right = serializeEntityName((node).right, fallbackPath); if (!fallbackPath) { return left + "." + right; } @@ -14008,7 +14006,7 @@ namespace ts { return "Symbol"; } else if (type === unknownType) { - var fallbackPath: string[] = []; + let fallbackPath: string[] = []; serializeEntityName(node.typeName, fallbackPath); return fallbackPath; } @@ -14080,7 +14078,7 @@ namespace ts { // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. // * The serialized type of any other FunctionLikeDeclaration is "Function". // * The serialized type of any other node is "void 0". - // + // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { case SyntaxKind.ClassDeclaration: return "Function"; @@ -14094,17 +14092,17 @@ namespace ts { } return "void 0"; } - + /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ function serializeParameterTypesOfNode(node: Node): (string | string[])[] { // serialization of parameter types uses the following rules: // // * If the declaration is a class, the parameters of the first constructor with a body are used. // * If the declaration is function-like and has a body, the parameters of the function are used. - // + // // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { - var valueDeclaration: FunctionLikeDeclaration; + let valueDeclaration: FunctionLikeDeclaration; if (node.kind === SyntaxKind.ClassDeclaration) { valueDeclaration = getFirstConstructorWithBody(node); } @@ -14112,14 +14110,14 @@ namespace ts { valueDeclaration = node; } if (valueDeclaration) { - var result: (string | string[])[]; - var parameters = valueDeclaration.parameters; - var parameterCount = parameters.length; + let result: (string | string[])[]; + let parameters = valueDeclaration.parameters; + let parameterCount = parameters.length; if (parameterCount > 0) { result = new Array(parameterCount); - for (var i = 0; i < parameterCount; i++) { + for (let i = 0; i < parameterCount; i++) { if (parameters[i].dotDotDotToken) { - var parameterType = parameters[i].type; + let parameterType = parameters[i].type; if (parameterType.kind === SyntaxKind.ArrayType) { parameterType = (parameterType).elementType; } @@ -14166,7 +14164,7 @@ namespace ts { } function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - var type = getTypeOfExpression(expr); + let type = getTypeOfExpression(expr); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -14318,21 +14316,21 @@ namespace ts { anyArrayType = createArrayType(anyType); } - + function createInstantiatedPromiseLikeType(): ObjectType { let promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyObjectType) { return createTypeReference(promiseLikeType, [anyType]); } - + return emptyObjectType; } - + function createThenableType() { // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. let thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - + let thenableType = createObjectType(TypeFlags.Anonymous); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); @@ -14509,7 +14507,7 @@ namespace ts { } flags |= NodeFlags.Ambient; lastDeclare = modifier; - break; + break; case SyntaxKind.AbstractKeyword: if (flags & NodeFlags.Abstract) { @@ -14545,7 +14543,7 @@ namespace ts { } flags |= NodeFlags.Async; lastAsync = modifier; - break; + break; } } @@ -14761,7 +14759,7 @@ namespace ts { if (types && types.length === 0) { let listType = tokenToString(node.token); let sourceFile = getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType) + return grammarErrorAtPos(sourceFile, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType); } } @@ -14773,7 +14771,7 @@ namespace ts { for (let heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen) + return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); } if (seenImplementsClause) { @@ -15134,13 +15132,13 @@ namespace ts { ? 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) + return grammarErrorOnNode(node, message); } else { 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) + return grammarErrorOnNode(node, message); } } @@ -15419,7 +15417,7 @@ namespace ts { // Find containing block which is either Block, ModuleBlock, SourceFile 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) + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } // We are either parented by another statement, or some sort of block. diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index df980d7fd7e62..ba7d8ca9ce347 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -5,7 +5,7 @@ namespace ts { /* @internal */ - export var optionDeclarations: CommandLineOption[] = [ + export let optionDeclarations: CommandLineOption[] = [ { name: "charset", type: "string", @@ -222,11 +222,11 @@ namespace ts { ]; export function parseCommandLine(commandLine: string[]): ParsedCommandLine { - var options: CompilerOptions = {}; - var fileNames: string[] = []; - var errors: Diagnostic[] = []; - var shortOptionNames: Map = {}; - var optionNameMap: Map = {}; + let options: CompilerOptions = {}; + let fileNames: string[] = []; + let errors: Diagnostic[] = []; + let shortOptionNames: Map = {}; + let optionNameMap: Map = {}; forEach(optionDeclarations, option => { optionNameMap[option.name.toLowerCase()] = option; @@ -242,9 +242,9 @@ namespace ts { }; function parseStrings(args: string[]) { - var i = 0; + let i = 0; while (i < args.length) { - var s = args[i++]; + let s = args[i++]; if (s.charCodeAt(0) === CharacterCodes.at) { parseResponseFile(s.slice(1)); } @@ -257,7 +257,7 @@ namespace ts { } if (hasProperty(optionNameMap, s)) { - var opt = optionNameMap[s]; + let opt = optionNameMap[s]; // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { @@ -276,8 +276,8 @@ namespace ts { break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: - var map = >opt.type; - var key = (args[i++] || "").toLowerCase(); + let map = >opt.type; + let key = (args[i++] || "").toLowerCase(); if (hasProperty(map, key)) { options[opt.name] = map[key]; } @@ -297,19 +297,19 @@ namespace ts { } function parseResponseFile(fileName: string) { - var text = sys.readFile(fileName); + let text = sys.readFile(fileName); if (!text) { errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName)); return; } - var args: string[] = []; - var pos = 0; + let args: string[] = []; + let pos = 0; while (true) { while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++; if (pos >= text.length) break; - var start = pos; + let start = pos; if (text.charCodeAt(start) === CharacterCodes.doubleQuote) { pos++; while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++; @@ -335,8 +335,9 @@ namespace ts { * @param fileName The path to the config file */ export function readConfigFile(fileName: string): { config?: any; error?: Diagnostic } { + let text = ''; try { - var text = sys.readFile(fileName); + text = sys.readFile(fileName); } catch (e) { return { error: createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; @@ -362,10 +363,10 @@ namespace ts { * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir + * file to. e.g. outDir */ export function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine { - var errors: Diagnostic[] = []; + let errors: Diagnostic[] = []; return { options: getCompilerOptions(), @@ -374,22 +375,22 @@ namespace ts { }; function getCompilerOptions(): CompilerOptions { - var options: CompilerOptions = {}; - var optionNameMap: Map = {}; + let options: CompilerOptions = {}; + let optionNameMap: Map = {}; forEach(optionDeclarations, option => { optionNameMap[option.name] = option; }); - var jsonOptions = json["compilerOptions"]; + let jsonOptions = json["compilerOptions"]; if (jsonOptions) { - for (var id in jsonOptions) { + for (let id in jsonOptions) { if (hasProperty(optionNameMap, id)) { - var opt = optionNameMap[id]; - var optType = opt.type; - var value = jsonOptions[id]; - var expectedType = typeof optType === "string" ? optType : "string"; + let opt = optionNameMap[id]; + let optType = opt.type; + let value = jsonOptions[id]; + let expectedType = typeof optType === "string" ? optType : "string"; if (typeof value === expectedType) { if (typeof optType !== "string") { - var key = value.toLowerCase(); + let key = value.toLowerCase(); if (hasProperty(optType, key)) { value = optType[key]; } @@ -424,7 +425,7 @@ namespace ts { } else { let exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; - let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); + let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); for (let i = 0; i < sysFiles.length; i++) { let name = sysFiles[i]; if (fileExtensionIs(name, ".d.ts")) { @@ -435,7 +436,7 @@ namespace ts { } else if (fileExtensionIs(name, ".ts")) { if (!contains(sysFiles, name + "x")) { - fileNames.push(name) + fileNames.push(name); } } else { diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 427084b57795c..ec171d4aee298 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -25,7 +25,7 @@ namespace ts { contains, remove, forEachValue: forEachValueInMap - } + }; function set(fileName: string, value: T) { files[normalizeKey(fileName)] = value; @@ -170,7 +170,7 @@ namespace ts { to.push(v); } } - } + } export function rangeEquals(array1: T[], array2: T[], pos: number, end: number) { while (pos < end) { @@ -372,7 +372,7 @@ namespace ts { } let text = getLocaleSpecificMessage(message.key); - + if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); } @@ -542,7 +542,7 @@ namespace ts { else { // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, // e.g. "path//file.ts". Drop these before re-joining the parts. - if(part) { + if (part) { normalized.push(part); } } @@ -600,20 +600,20 @@ namespace ts { function getNormalizedPathComponentsOfUrl(url: string) { // Get root length of http://www.website.com/folder1/foler2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] let urlLength = url.length; // Initial root length is http:// part let rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { - // Consume all immediate slashes in the protocol + // Consume all immediate slashes in the protocol // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// if (url.charCodeAt(rootLength) === CharacterCodes.slash) { rootLength++; } else { - // non slash character means we continue proceeding to next component of root search + // non slash character means we continue proceeding to next component of root search break; } } @@ -626,15 +626,15 @@ namespace ts { // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) let indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { - // Found the "/" after the website.com so the root is length of http://www.website.com/ + // 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 rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } else { - // Can't find the host assume the rest of the string as component + // Can't find the host assume the rest of the string as component // but make sure we append "/" to it as root is not joined using "/" - // eg. if url passed in was http://website.com we want to use root as [http://website.com/] + // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + directorySeparator]; } @@ -774,7 +774,7 @@ namespace ts { getSymbolConstructor: () => Symbol, getTypeConstructor: () => Type, getSignatureConstructor: () => Signature - } + }; export const enum AssertionLevel { None = 0, diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 8c012f2678e61..36feaa515ffb8 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -130,7 +130,7 @@ namespace ts { moduleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput, - } + }; function hasInternalAnnotation(range: CommentRange) { let text = currentSourceFile.text; @@ -188,7 +188,7 @@ namespace ts { if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { moduleElementEmitInfo = forEach(asynchronousSubModuleDeclarationEmitInfo, declEmitInfo => declEmitInfo.node === nodeToCheck ? 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. @@ -198,7 +198,7 @@ namespace ts { // we would write alias foo declaration when we visit it since it would now be marked as visible if (moduleElementEmitInfo) { if (moduleElementEmitInfo.node.kind === SyntaxKind.ImportDeclaration) { - // we have to create asynchronous output only after we have collected complete information + // we have to create asynchronous output only after we have collected complete information // because it is possible to enable multiple bindings as asynchronously visible moduleElementEmitInfo.isVisible = true; } @@ -600,7 +600,7 @@ namespace ts { } function writeImportEqualsDeclaration(node: ImportEqualsDeclaration) { - // note usage of writer. methods instead of aliases created, just to make sure we are using + // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); if (node.flags & NodeFlags.Export) { @@ -642,7 +642,7 @@ namespace ts { function writeImportDeclaration(node: ImportDeclaration) { if (!node.importClause && !(node.flags & NodeFlags.Export)) { - // do not write non-exported import declarations that don't have import clauses + // do not write non-exported import declarations that don't have import clauses return; } emitJsDocComments(node); @@ -764,7 +764,7 @@ namespace ts { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (isConst(node)) { - write("const ") + write("const "); } write("enum "); writeTextOfNode(currentSourceFile, node.name); @@ -1343,7 +1343,7 @@ namespace ts { return { diagnosticMessage, - errorNode: node.name || node, + errorNode: node.name || node }; } } @@ -1517,7 +1517,7 @@ namespace ts { } } } - } + } } function emitNode(node: Node) { @@ -1565,7 +1565,7 @@ namespace ts { ? 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 - : removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file + : removeFileExtension(compilerOptions.out) + ".d.ts"; // Global out file declFileName = getRelativePathToDirectoryOrUrl( getDirectoryPath(normalizeSlashes(jsFilePath)), @@ -1577,7 +1577,7 @@ namespace ts { referencePathsOutput += "/// " + newLine; } } - + /* @internal */ export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) { let emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); @@ -1604,4 +1604,4 @@ namespace ts { return declarationOutput; } } -} \ No newline at end of file +} diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 9a05f145e6d8a..69f8c25a1479d 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -9,9 +9,9 @@ namespace ts { // Flags enum to track count of temp variables and a few dedicated names const enum TempFlags { - Auto = 0x00000000, // No preferred name + Auto = 0x00000000, // No preferred name CountMask = 0x0FFFFFFF, // Temp variable counter - _i = 0x10000000, // Use/preference flag for '_i' + _i = 0x10000000, // Use/preference flag for '_i' } // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature @@ -129,7 +129,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let writeLine = writer.writeLine; let increaseIndent = writer.increaseIndent; let decreaseIndent = writer.decreaseIndent; - + let currentSourceFile: SourceFile; // name of an exporter function if file is a System external module // System.register([...], function () {...}) @@ -182,10 +182,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi /** 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 */ - let scopeEmitStart = function (scopeDeclaration: Node, scopeName?: string) { } + let scopeEmitStart = function(scopeDeclaration: Node, scopeName?: string) { }; /** Called after coming out of the scope */ - let scopeEmitEnd = function () { } + let scopeEmitEnd = function() { }; /** Sourcemap data that will get encoded */ let sourceMapData: SourceMapData; @@ -227,7 +227,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. function makeTempVariableName(flags: TempFlags): string { if (flags && !(tempFlags & flags)) { - var name = flags === TempFlags._i ? "_i" : "_n" + let name = flags === TempFlags._i ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; return name; @@ -897,13 +897,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { return getQuotedEscapedLiteralText('"', node.text, '"'); } - + // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (node.parent) { return getSourceTextOfNodeFromSourceFile(currentSourceFile, node); } - + // If we can't reach the original source text, use the canonical form if it's a number, // or an escaped quoted form of the original text if it's string-like. switch (node.kind) { @@ -933,14 +933,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // 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". 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 "${" let isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; text = text.substring(1, text.length - (isLast ? 1 : 2)); - + // Newline normalization: // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's // and LineTerminatorSequences are normalized to for both TV and TRV. @@ -981,7 +981,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); write("("); emit(tempVariable); - + // Now we emit the expressions if (node.template.kind === SyntaxKind.TemplateExpression) { forEach((node.template).templateSpans, templateSpan => { @@ -1044,7 +1044,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // with the head will force the result up to this point to be a string. // Emitting a '+ ""' has no semantic effect for middles and tails. if (templateSpan.literal.text.length !== 0) { - write(" + ") + write(" + "); emitLiteral(templateSpan.literal); } } @@ -1358,7 +1358,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } else if (node.kind === SyntaxKind.ComputedPropertyName) { // if this is a decorated computed property, we will need to capture the result - // of the property expression so that we can apply decorators later. This is to ensure + // of the property expression so that we can apply decorators later. This is to ensure // we don't introduce unintended side effects: // // class C { @@ -1468,7 +1468,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("_arguments"); return; } - + let container = resolver.getReferencedExportContainer(node); if (container) { if (container.kind === SyntaxKind.SourceFile) { @@ -1552,7 +1552,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("super"); } else { - var flags = resolver.getNodeCheckFlags(node); + let flags = resolver.getNodeCheckFlags(node); if (flags & NodeCheckFlags.SuperInstance) { write("_super.prototype"); } @@ -1608,7 +1608,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node.expression); } } - + function emitAwaitExpression(node: AwaitExpression) { let needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); if (needsParenthesis) { @@ -1688,7 +1688,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi group++; } if (group > 1) { - if(useConcat) { + if (useConcat) { write(")"); } } @@ -1723,7 +1723,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("{"); if (numElements > 0) { - var properties = node.properties; + let properties = node.properties; // If we are not doing a downlevel transformation for object literals, // then try to preserve the original shape of the object literal. @@ -1771,7 +1771,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Write out the first non-computed properties // (or all properties if none of them are computed), // then emit the rest through indexing on the temp variable. - emit(tempVar) + emit(tempVar); write(" = "); emitObjectLiteralBody(node, firstComputedPropertyIndex); @@ -1780,7 +1780,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let property = properties[i]; - emitStart(property) + emitStart(property); if (property.kind === SyntaxKind.GetAccessor || property.kind === SyntaxKind.SetAccessor) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. let accessors = getAllAccessorDeclarations(node.properties, property); @@ -1796,7 +1796,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(", {"); increaseIndent(); if (accessors.getAccessor) { - writeLine() + writeLine(); emitLeadingComments(accessors.getAccessor); write("get: "); emitStart(accessors.getAccessor); @@ -2021,8 +2021,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return false; } - // Returns 'true' if the code was actually indented, false otherwise. - // If the code is not indented, an optional valueToWriteWhenNotIndenting will be + // Returns 'true' if the code was actually indented, false otherwise. + // If the code is not indented, an optional valueToWriteWhenNotIndenting will be // emitted instead. function indentIfOnDifferentLines(parent: Node, node1: Node, node2: Node, valueToWriteWhenNotIndenting?: string): boolean { let realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); @@ -2050,8 +2050,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node.expression); let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); - - // 1 .toString is a valid property access, emit a space after the literal + + // 1 .toString is a valid property access, emit a space after the literal let shouldEmitSpace: boolean; if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) { let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); @@ -2059,7 +2059,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (shouldEmitSpace) { - write(" ."); + write(" ."); } else { write("."); @@ -2384,14 +2384,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false); } - /* + /* * Checks if given node is a source file level declaration (not nested in module/function). * If 'isExported' is true - then declaration must also be exported. * This function is used in two cases: - * - check if node is a exported source file level value to determine + * - check if node is a exported source file level value to determine * if we should also export the value after its it changed - * - check if node is a source level declaration to emit it differently, - * i.e non-exported variable statement 'var x = 1' is hoisted so + * - check if node is a source level declaration to emit it differently, + * i.e non-exported variable statement 'var x = 1' is hoisted so * we we emit variable statement 'var' should be dropped. */ function isSourceFileLevelDeclarationInSystemJsModule(node: Node, isExported: boolean): boolean { @@ -2402,7 +2402,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let current: Node = node; while (current) { if (current.kind === SyntaxKind.SourceFile) { - return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0) + return !isExported || ((getCombinedNodeFlags(node) & NodeFlags.Export) !== 0); } else if (isFunctionLike(current) || current.kind === SyntaxKind.ModuleBlock) { return false; @@ -2460,7 +2460,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi decreaseIndentIf(indentedBeforeColon, indentedAfterColon); } - // Helper function to decrease the indent if we previously indented. Allows multiple + // Helper function to decrease the indent if we previously indented. Allows multiple // previous indent values to be considered at a time. This also allows caller to just // call this once, passing in all their appropriate indent values, instead of needing // to call this helper function multiple times. @@ -2587,7 +2587,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (startPos !== undefined) { emitToken(tokenKind, startPos); - write(" ") + write(" "); } else { switch (tokenKind) { @@ -2702,13 +2702,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // all destructuring. // Note also that because an extra statement is needed to assign to the LHS, // for-of bodies are always emitted as blocks. - + let endPos = emitToken(SyntaxKind.ForKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); - + // 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: @@ -2724,7 +2724,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // the LHS will be emitted inside the body. emitStart(node.expression); write("var "); - + // _i = 0 emitNodeWithoutSourceMap(counter); write(" = 0"); @@ -2741,7 +2741,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } write("; "); - + // _i < _a.length; emitStart(node.initializer); emitNodeWithoutSourceMap(counter); @@ -2752,19 +2752,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitEnd(node.initializer); write("; "); - + // _i++) emitStart(node.initializer); emitNodeWithoutSourceMap(counter); write("++"); emitEnd(node.initializer); emitToken(SyntaxKind.CloseParenToken, node.expression.end); - + // Body write(" {"); writeLine(); increaseIndent(); - + // Initialize LHS // let v = _a[_i]; let rhsIterationValue = createElementAccessExpression(rhsReference, counter); @@ -2850,7 +2850,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node.expression); endPos = emitToken(SyntaxKind.CloseParenToken, node.expression.end); write(" "); - emitCaseBlock(node.caseBlock, endPos) + emitCaseBlock(node.caseBlock, endPos); } function emitCaseBlock(node: CaseBlock, startPos: number): void { @@ -2952,7 +2952,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitModuleMemberName(node: Declaration) { emitStart(node.name); if (getCombinedNodeFlags(node) & NodeFlags.Export) { - var container = getContainingModule(node); + let container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); @@ -2991,7 +2991,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } write(`", `); emitDeclarationName(node); - write(")") + write(")"); } else { if (node.flags & NodeFlags.Default) { @@ -3022,7 +3022,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitNodeWithoutSourceMap(specifier.name); write(`", `); emitExpressionIdentifier(name); - write(")") + write(")"); emitEnd(specifier.name); } else { @@ -3312,7 +3312,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitOptional(" = ", initializer); if (exportChanged) { - write(")") + write(")"); } } } @@ -3612,10 +3612,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node.parameters[0]); return; } - + emitSignatureParameters(node); } - + function emitAsyncFunctionBodyForES6(node: FunctionLikeDeclaration) { let promiseConstructor = getEntityNameFromTypeNode(node.type); let isArrowFunction = node.kind === SyntaxKind.ArrowFunction; @@ -3625,7 +3625,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the + // passed to `__awaiter` is executed inside of the callback to the // promise constructor. // // The emit for an async arrow without a lexical `arguments` binding might be: @@ -3693,7 +3693,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // }); // } // - + // If this is not an async arrow, emit the opening brace of the function body // and the start of the return statement. if (!isArrowFunction) { @@ -3702,7 +3702,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); write("return"); } - + write(" __awaiter(this"); if (hasLexicalArguments) { write(", arguments"); @@ -3718,7 +3718,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { write(", Promise"); } - + // Emit the call to __awaiter. if (hasLexicalArguments) { write(", function* (_arguments)"); @@ -3726,11 +3726,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { write(", function* ()"); } - + // Emit the signature and body for the inner generator function. emitFunctionBody(node); write(")"); - + // If this is not an async arrow, emit the closing brace of the outer function body. if (!isArrowFunction) { write(";"); @@ -3739,10 +3739,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("}"); } } - + function emitFunctionBody(node: FunctionLikeDeclaration) { if (!node.body) { - // There can be no body when there are parse errors. Just emit an empty block + // There can be no body when there are parse errors. Just emit an empty block // in that case. write(" { }"); } @@ -3753,7 +3753,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { emitExpressionFunctionBody(node, node.body); } - } + } } function emitSignatureAndBody(node: FunctionLikeDeclaration) { @@ -3772,7 +3772,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { emitSignatureParameters(node); } - + let isAsync = isAsyncFunctionLike(node); if (isAsync && languageVersion === ScriptTarget.ES6) { emitAsyncFunctionBodyForES6(node); @@ -3780,7 +3780,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { emitFunctionBody(node); } - + if (!isES6ExportedDeclaration(node)) { emitExportMemberAssignment(node); } @@ -3803,7 +3803,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - // For es6 and higher we can emit the expression as is. However, in the case + // For es6 and higher we can emit the expression as is. However, in the case // where the expression might end up looking like a block when emitted, we'll // also wrap it in parentheses first. For example if you have: a => {} // then we need to generate: a => ({}) @@ -4075,8 +4075,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitOnlyPinnedOrTripleSlashComments(member); } else if (member.kind === SyntaxKind.MethodDeclaration || - member.kind === SyntaxKind.GetAccessor || - member.kind === SyntaxKind.SetAccessor) { + member.kind === SyntaxKind.GetAccessor || + member.kind === SyntaxKind.SetAccessor) { writeLine(); emitLeadingComments(member); emitStart(member); @@ -4210,7 +4210,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); if (ctor) { - var statements: Node[] = (ctor.body).statements; + let statements: Node[] = (ctor.body).statements; if (superCall) { statements = statements.slice(1); } @@ -4320,9 +4320,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // If the class has static properties, and it's a class expression, then we'll need - // to specialize the emit a bit. for a class expression of the form: + // to specialize the emit a bit. for a class expression of the form: // - // class C { static a = 1; static b = 2; ... } + // class C { static a = 1; static b = 2; ... } // // We'll emit: // @@ -4339,7 +4339,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("("); increaseIndent(); emit(tempVariable); - write(" = ") + write(" = "); } write("class"); @@ -4350,7 +4350,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitDeclarationName(node); } - var baseTypeNode = getClassExtendsHeritageClauseElement(node); + let baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { write(" extends "); emit(baseTypeNode.expression); @@ -4368,7 +4368,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi scopeEmitEnd(); // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. - + // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: // @@ -4613,7 +4613,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // // The emit for a method is: // - // Object.defineProperty(C.prototype, "method", + // Object.defineProperty(C.prototype, "method", // __decorate([ // dec, // __param(0, dec2), @@ -4621,10 +4621,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // __metadata("design:paramtypes", [Object]), // __metadata("design:returntype", void 0) // ], C.prototype, "method", Object.getOwnPropertyDescriptor(C.prototype, "method"))); - // + // // The emit for an accessor is: // - // Object.defineProperty(C.prototype, "accessor", + // Object.defineProperty(C.prototype, "accessor", // __decorate([ // dec // ], C.prototype, "accessor", Object.getOwnPropertyDescriptor(C.prototype, "accessor"))); @@ -4714,7 +4714,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function shouldEmitTypeMetadata(node: Declaration): boolean { // This method determines whether to emit the "design:type" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata + // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { case SyntaxKind.MethodDeclaration: @@ -4729,7 +4729,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function shouldEmitReturnTypeMetadata(node: Declaration): boolean { // This method determines whether to emit the "design:returntype" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata + // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { case SyntaxKind.MethodDeclaration: @@ -4740,7 +4740,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function shouldEmitParamTypesMetadata(node: Declaration): boolean { // This method determines whether to emit the "design:paramtypes" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata + // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata // compiler option is set. switch (node.kind) { case SyntaxKind.ClassDeclaration: @@ -4757,7 +4757,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let argumentsWritten = 0; if (compilerOptions.emitDecoratorMetadata) { if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node); + let serializedType = resolver.serializeTypeOfNode(node); if (serializedType) { if (writeComma) { write(", "); @@ -4770,7 +4770,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node); + let serializedTypes = resolver.serializeParameterTypesOfNode(node); if (serializedTypes) { if (writeComma || argumentsWritten) { write(", "); @@ -4788,7 +4788,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node); + let serializedType = resolver.serializeReturnTypeOfNode(node); if (serializedType) { if (writeComma || argumentsWritten) { write(", "); @@ -5289,7 +5289,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); emitStart(node); write("export default "); - var expression = node.expression; + let expression = node.expression; emit(expression); if (expression.kind !== SyntaxKind.FunctionDeclaration && expression.kind !== SyntaxKind.ClassDeclaration) { @@ -5419,7 +5419,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // do not create variable declaration for exports and imports that lack import clause let skipNode = importNode.kind === SyntaxKind.ExportDeclaration || - (importNode.kind === SyntaxKind.ImportDeclaration && !(importNode).importClause) + (importNode.kind === SyntaxKind.ImportDeclaration && !(importNode).importClause); if (skipNode) { continue; @@ -5537,14 +5537,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("}"); decreaseIndent(); writeLine(); - write("}") + write("}"); return exportStarFunction; } function writeExportedName(node: Identifier | Declaration): void { // do not record default exports - // they are local to module and never overwritten (explicitly skipped) by star export + // they are local to module and never overwritten (explicitly skipped) by star export if (node.kind !== SyntaxKind.Identifier && node.flags & NodeFlags.Default) { return; } @@ -5570,7 +5570,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function processTopLevelVariableAndFunctionDeclarations(node: SourceFile): (Identifier | Declaration)[] { - // per ES6 spec: + // per ES6 spec: // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method // - var declarations are initialized to undefined - 14.a.ii // - function/generator declarations are instantiated - 16.a.iv @@ -5625,7 +5625,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi exportedDeclarations.push(local); } } - write(";") + write(";"); } if (hoistedFunctionDeclarations) { @@ -5725,7 +5725,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // hoist variable if // - it is not block scoped // - it is top level block scoped - // if block scoped variables are nested in some another block then + // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0 || getEnclosingBlockScopeContainer(node).kind === SyntaxKind.SourceFile; @@ -5774,8 +5774,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // } emitVariableDeclarationsForImports(); writeLine(); - var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) + let exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); + let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); writeLine(); write("return {"); increaseIndent(); @@ -5852,7 +5852,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // export {a, b as c} for (let element of (namedBindings).elements) { emitExportMemberAssignments(element.name || element.propertyName); - writeLine() + writeLine(); } } } @@ -5891,7 +5891,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi break; } - write("}") + write("}"); decreaseIndent(); } write("],"); @@ -5917,7 +5917,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } decreaseIndent(); writeLine(); - write("}") // execute + write("}"); // execute } function emitSystemModule(node: SourceFile, startIndex: number): void { @@ -5925,10 +5925,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // System modules has the following shape // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values. - // 'exports' returns its 'value' argument so in most cases expressions + // 'exports' returns its 'value' argument so in most cases expressions // that mutate exported values can be rewritten as: - // expr -> exports('name', expr). - // The only exception in this rule is postfix unary operators, + // expr -> exports('name', expr). + // The only exception in this rule is postfix unary operators, // see comment to 'emitPostfixUnaryExpression' for more details Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers @@ -5937,7 +5937,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.moduleName) { write(`"${node.moduleName}", `); } - write("[") + write("["); for (let i = 0; i < externalImports.length; ++i) { let text = getExternalModuleNameText(externalImports[i]); if (i !== 0) { @@ -5968,13 +5968,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // `import "module"` or `` // we need to add modules without alias names to the end of the dependencies list - let aliasedModuleNames: string[] = []; // names of modules with corresponding parameter in the - // factory function. - let unaliasedModuleNames: string[] = []; // names of modules with no corresponding parameters in - // factory function. - let importAliasNames: string[] = []; // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. + // names of modules with corresponding parameter in the factory function + let aliasedModuleNames: string[] = []; + // names of modules with no corresponding parameters in factory function + let unaliasedModuleNames: string[] = []; + let importAliasNames: string[] = []; // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. // Fill in amd-dependency tags for (let amdDependency of node.amdDependencies) { @@ -6081,7 +6081,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); emitTempDeclarations(/*newLine*/ true); - // Emit exportDefault if it exists will happen as part + // Emit exportDefault if it exists will happen as part // or normal statement emit. } @@ -6222,7 +6222,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitDetachedComments(node); // emit prologue directives prior to __extends - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); // Only emit helpers if the user did not say otherwise. if (!compilerOptions.noEmitHelpers) { @@ -6245,7 +6245,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLines(paramHelper); paramEmitted = true; } - + if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitAwaiter) { writeLines(awaiterHelper); awaiterEmitted = true; @@ -6329,7 +6329,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return shouldEmitEnumDeclaration(node); } - // If this is the expression body of an arrow function that we're down-leveling, + // If this is the expression body of an arrow function that we're down-leveling, // then we don't want to emit comments when we emit the body. It will have already // been taken care of when we emitted the 'return' statement for the function // expression body. @@ -6594,7 +6594,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitTrailingComments(node: Node) { // Emit the trailing comments only if the parent's end doesn't match - var trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments); + let trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); @@ -6686,4 +6686,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } } -} +} diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 3635a88b608c8..fecff11b1b4b8 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -410,7 +410,7 @@ namespace ts { export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile { return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); } - + /* @internal */ export function parseIsolatedJSDocComment(content: string, start?: number, length?: number) { return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); @@ -585,7 +585,7 @@ namespace ts { fixupParentReferences(sourceFile); } - // If this is a javascript file, proactively see if we can get JSDoc comments for + // If this is a javascript file, proactively see if we can get JSDoc comments for // relevant nodes in the file. We'll use these to provide typing informaion if they're // available. if (isJavaScript(fileName)) { @@ -685,17 +685,17 @@ namespace ts { function setDecoratorContext(val: boolean) { setContextFlag(val, ParserContextFlags.Decorator); } - + function setAwaitContext(val: boolean) { setContextFlag(val, ParserContextFlags.Await); } - + function doOutsideOfContext(context: ParserContextFlags, func: () => T): T { - // contextFlagsToClear will contain only the context flags that are + // contextFlagsToClear will contain only the context flags that are // currently set that we need to temporarily clear // We don't just blindly reset to the previous flags to ensure // that we do not mutate cached flags for the incremental - // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and // HasAggregatedChildData). let contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { @@ -710,13 +710,13 @@ namespace ts { // no need to do anything special as we are not in any of the requested contexts return func(); } - + function doInsideOfContext(context: ParserContextFlags, func: () => T): T { // contextFlagsToSet will contain only the context flags that // are not currently set that we need to temporarily enable. // We don't just blindly reset to the previous flags to ensure // that we do not mutate cached flags for the incremental - // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and // HasAggregatedChildData). let contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { @@ -727,11 +727,11 @@ namespace ts { setContextFlag(false, contextFlagsToSet); return result; } - + // no need to do anything special as we are already in all of the requested contexts return func(); } - + function allowInAnd(func: () => T): T { return doOutsideOfContext(ParserContextFlags.DisallowIn, func); } @@ -739,7 +739,7 @@ namespace ts { function disallowInAnd(func: () => T): T { return doInsideOfContext(ParserContextFlags.DisallowIn, func); } - + function doInYieldContext(func: () => T): T { return doInsideOfContext(ParserContextFlags.Yield, func); } @@ -751,23 +751,23 @@ namespace ts { function doInDecoratorContext(func: () => T): T { return doInsideOfContext(ParserContextFlags.Decorator, func); } - + function doInAwaitContext(func: () => T): T { return doInsideOfContext(ParserContextFlags.Await, func); } - + function doOutsideOfAwaitContext(func: () => T): T { return doOutsideOfContext(ParserContextFlags.Await, func); } - + function doInYieldAndAwaitContext(func: () => T): T { return doInsideOfContext(ParserContextFlags.Yield | ParserContextFlags.Await, func); } - + function doOutsideOfYieldAndAwaitContext(func: () => T): T { return doOutsideOfContext(ParserContextFlags.Yield | ParserContextFlags.Await, func); } - + function inContext(flags: ParserContextFlags) { return (contextFlags & flags) !== 0; } @@ -787,7 +787,7 @@ namespace ts { function inAwaitContext() { return inContext(ParserContextFlags.Await); } - + function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void { let start = scanner.getTokenPos(); let length = scanner.getTextPos() - start; @@ -843,7 +843,7 @@ namespace ts { function scanJsxIdentifier(): SyntaxKind { return token = scanner.scanJsxIdentifier(); } - + 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). @@ -903,7 +903,7 @@ namespace ts { if (token === SyntaxKind.YieldKeyword && inYieldContext()) { return false; } - + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is // considered a keyword and is not an identifier. if (token === SyntaxKind.AwaitKeyword && inAwaitContext()) { @@ -1102,7 +1102,7 @@ namespace ts { function parseContextualModifier(t: SyntaxKind): boolean { return token === t && tryParse(nextTokenCanFollowModifier); } - + function nextTokenCanFollowModifier() { if (token === SyntaxKind.ConstKeyword) { // 'const' is only a modifier if followed by 'enum'. @@ -1121,7 +1121,7 @@ namespace ts { nextToken(); return canFollowModifier(); } - + function parseAnyContextualModifier(): boolean { return isModifier(token) && tryParse(nextTokenCanFollowModifier); } @@ -1229,7 +1229,7 @@ namespace ts { // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // - // extends {} { + // extends {} { // extends {}, // extends {} extends // extends {} implements @@ -1844,7 +1844,7 @@ namespace ts { do { templateSpans.push(parseTemplateSpan()); } - while (lastOrUndefined(templateSpans).literal.kind === SyntaxKind.TemplateMiddle) + while (lastOrUndefined(templateSpans).literal.kind === SyntaxKind.TemplateMiddle); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; @@ -1859,7 +1859,7 @@ namespace ts { let literal: LiteralExpression; if (token === SyntaxKind.CloseBraceToken) { - reScanTemplateToken() + reScanTemplateToken(); literal = parseLiteralNode(); } else { @@ -2019,7 +2019,7 @@ namespace ts { // ambient contexts. return finishNode(node); } - + function parseBindingElementInitializer(inParameter: boolean) { return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); } @@ -2027,7 +2027,7 @@ namespace ts { function parseParameterInitializer() { return parseInitializer(/*inParameter*/ true); } - + function fillSignature( returnToken: SyntaxKind, yieldContext: boolean, @@ -2065,15 +2065,15 @@ namespace ts { if (parseExpected(SyntaxKind.OpenParenToken)) { let savedYieldContext = inYieldContext(); let savedAwaitContext = inAwaitContext(); - + setYieldContext(yieldContext); setAwaitContext(awaitContext); - + let result = parseDelimitedList(ParsingContext.Parameters, parseParameter); - + setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); - + if (!parseExpected(SyntaxKind.CloseParenToken) && requireCompleteParameterList) { // Caller insisted that we had to end with a ) We didn't. So just return // undefined here. @@ -2088,7 +2088,7 @@ namespace ts { // then just return an empty set of parameters. return requireCompleteParameterList ? undefined : createMissingList(); } - + function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. // First check if it was a comma. If so, we're done with the member. @@ -2180,7 +2180,7 @@ namespace ts { node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); - return finishNode(node) + return finishNode(node); } function parsePropertyOrMethodSignature(): Declaration { @@ -2471,7 +2471,7 @@ namespace 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. + // apply to 'type' contexts. So we disable these parameters here before moving on. return doOutsideOfContext(ParserContextFlags.TypeExcludesFlags, parseTypeWorker); } @@ -2559,7 +2559,7 @@ namespace ts { token !== SyntaxKind.AtToken && isStartOfExpression(); } - + function allowInAndParseExpression(): Expression { return allowInAnd(parseExpression); } @@ -2748,7 +2748,7 @@ namespace ts { // It's definitely not a parenthesized arrow function expression. return undefined; } - + // If we definitely have an arrow function, then we can just parse one, not requiring a // 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 @@ -2761,12 +2761,12 @@ namespace ts { // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - + let isAsync = !!(arrowFunction.flags & NodeFlags.Async); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - var lastToken = token; + let lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/false, Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken) ? parseArrowFunctionExpressionBody(isAsync) @@ -2804,7 +2804,7 @@ namespace ts { return Tristate.False; } } - + let first = token; let second = nextToken(); @@ -2892,7 +2892,7 @@ namespace ts { if (isArrowFunctionInJsx) { return Tristate.True; } - + return Tristate.False; } @@ -2909,7 +2909,7 @@ namespace ts { let node = createNode(SyntaxKind.ArrowFunction); setModifiers(node, parseModifiersForArrowFunction()); let isAsync = !!(node.flags & NodeFlags.Async); - + // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -2966,7 +2966,7 @@ namespace ts { // Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error. return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ true); } - + return isAsync ? doInAwaitContext(parseAssignmentExpressionOrHigher) : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); @@ -3133,7 +3133,7 @@ namespace ts { node.expression = parseUnaryExpressionOrHigher(); return finishNode(node); } - + function isAwaitExpression(): boolean { if (token === SyntaxKind.AwaitKeyword) { if (inAwaitContext()) { @@ -3158,7 +3158,7 @@ namespace ts { if (isAwaitExpression()) { return parseAwaitExpression(); } - + switch (token) { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: @@ -3177,7 +3177,7 @@ namespace ts { if (sourceFile.languageVariant !== LanguageVariant.JSX) { return parseTypeAssertion(); } - if(lookAhead(nextTokenIsIdentifierOrKeyword)) { + if (lookAhead(nextTokenIsIdentifierOrKeyword)) { return parseJsxElementOrSelfClosingElement(); } // Fall through @@ -3307,7 +3307,7 @@ namespace ts { node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } - + function parseJsxElementOrSelfClosingElement(): JsxElement|JsxSelfClosingElement { let opening = parseJsxOpeningOrSelfClosingElement(); if (opening.kind === SyntaxKind.JsxOpeningElement) { @@ -3349,7 +3349,7 @@ namespace ts { let saveParsingContext = parsingContext; parsingContext |= 1 << ParsingContext.JsxChildren; - while(true) { + while (true) { token = scanner.reScanJsxToken(); if (token === SyntaxKind.LessThanSlashToken) { break; @@ -3367,7 +3367,7 @@ namespace ts { return result; } - + function parseJsxOpeningOrSelfClosingElement(): JsxOpeningElement|JsxSelfClosingElement { let fullStart = scanner.getStartPos(); @@ -3392,7 +3392,7 @@ namespace ts { return finishNode(node); } - + function parseJsxElementName(): EntityName { scanJsxIdentifier(); let elementName: EntityName = parseIdentifierName(); @@ -3477,7 +3477,7 @@ namespace ts { continue; } - // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(SyntaxKind.OpenBracketToken)) { let indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); indexedAccess.expression = expression; @@ -3599,7 +3599,7 @@ namespace ts { case SyntaxKind.CommaToken: // foo, case SyntaxKind.OpenBraceToken: // foo { // We don't want to treat these as type arguments. Otherwise we'll parse this - // as an invocation expression. Instead, we want to parse out the expression + // as an invocation expression. Instead, we want to parse out the expression // in isolation from the type arguments. default: @@ -3627,7 +3627,7 @@ namespace ts { case SyntaxKind.OpenBraceToken: return parseObjectLiteralExpression(); case SyntaxKind.AsyncKeyword: - // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. // If we encounter `async [no LineTerminator here] function` then this is an async // function; otherwise, its an identifier. if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { @@ -3759,12 +3759,12 @@ namespace ts { if (saveDecoratorContext) { setDecoratorContext(false); } - + let node = createNode(SyntaxKind.FunctionExpression); setModifiers(node, parseModifiers()); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - + let isGenerator = !!node.asteriskToken; let isAsync = !!(node.flags & NodeFlags.Async); node.name = @@ -3772,14 +3772,14 @@ namespace ts { isGenerator ? doInYieldContext(parseOptionalIdentifier) : isAsync ? doInAwaitContext(parseOptionalIdentifier) : parseOptionalIdentifier(); - + fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); - + if (saveDecoratorContext) { setDecoratorContext(true); } - + return finishNode(node); } @@ -3815,11 +3815,11 @@ namespace ts { function parseFunctionBlock(allowYield: boolean, allowAwait: boolean, ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { let savedYieldContext = inYieldContext(); setYieldContext(allowYield); - + let savedAwaitContext = inAwaitContext(); setAwaitContext(allowAwait); - // We may be in a [Decorator] context when parsing a function expression or + // We may be in a [Decorator] context when parsing a function expression or // arrow function. The body of the function is not in [Decorator] context. let saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { @@ -4081,7 +4081,7 @@ namespace ts { nextToken(); return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak(); } - + function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); return token === SyntaxKind.FunctionKeyword && !scanner.hasPrecedingLineBreak(); @@ -4150,7 +4150,7 @@ namespace ts { return true; } continue; - + case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: @@ -4229,7 +4229,7 @@ namespace ts { } function isLetDeclaration() { - // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { // or [. return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); } @@ -4335,7 +4335,7 @@ namespace ts { default: if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration - // would follow. For recovery and error reporting purposes, return an incomplete declaration. + // would follow. For recovery and error reporting purposes, return an incomplete declaration. let node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; @@ -4550,7 +4550,7 @@ namespace ts { function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ClassElement { 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. let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); @@ -4694,7 +4694,7 @@ namespace ts { modifiers = []; modifiers.pos = modifierStart; } - + flags |= modifierToFlag(modifierKind); modifiers.push(finishNode(createNode(modifierKind, modifierStart))); } @@ -4719,7 +4719,7 @@ namespace ts { modifiers.flags = flags; modifiers.end = scanner.getStartPos(); } - + return modifiers; } @@ -4779,9 +4779,9 @@ namespace ts { function parseClassDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ClassDeclaration { return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, SyntaxKind.ClassDeclaration); } - + function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration { - var node = createNode(kind, fullStart); + let node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ClassKeyword); @@ -4791,7 +4791,7 @@ namespace ts { if (parseExpected(SyntaxKind.OpenBraceToken)) { // ClassTail[Yield,Await] : (Modified) See 14.5 - // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } node.members = parseClassMembers(); parseExpected(SyntaxKind.CloseBraceToken); } @@ -5008,7 +5008,7 @@ namespace ts { } function parseImportClause(identifier: Identifier, fullStart: number) { - //ImportClause: + // ImportClause: // ImportedDefaultBinding // NameSpaceImport // NamedImports @@ -5301,7 +5301,7 @@ namespace ts { /* @internal */ export function parseJSDocTypeExpression(start: number, length: number): JSDocTypeExpression { scanner.setText(sourceText, start, length); - + // Prime the first token for us to start processing. token = nextToken(); @@ -5316,15 +5316,15 @@ namespace ts { } function parseJSDocTopLevelType(): JSDocType { - var type = parseJSDocType(); + let type = parseJSDocType(); if (token === SyntaxKind.BarToken) { - var unionType = createNode(SyntaxKind.JSDocUnionType, type.pos); + let unionType = createNode(SyntaxKind.JSDocUnionType, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === SyntaxKind.EqualsToken) { - var optionalType = createNode(SyntaxKind.JSDocOptionalType, type.pos); + let optionalType = createNode(SyntaxKind.JSDocOptionalType, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -5638,9 +5638,9 @@ namespace ts { let tags: NodeArray; let pos: number; - - // NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I - // considered using an actual Scanner, but this would complicate things. The + + // NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I + // considered using an actual Scanner, but this would complicate things. The // scanner would need to know it was in a Doc Comment. Otherwise, it would then // produce comments *inside* the doc comment. In the end it was just easier to // write a simple scanner rather than go that route. @@ -5655,13 +5655,13 @@ namespace ts { let canParseTag = true; let seenAsterisk = true; - for (pos = start + "/**".length; pos < end;) { + for (pos = start + "/**".length; pos < end; ) { let ch = content.charCodeAt(pos); pos++; if (ch === CharacterCodes.at && canParseTag) { parseTag(); - + // Once we parse out a tag, we cannot keep parsing out tags on this line. canParseTag = false; continue; @@ -5927,7 +5927,7 @@ namespace ts { if (sourceFile.statements.length === 0) { // If we don't have any statements in the current source file, then there's no real // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true) + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true); } // Make sure we're not trying to incrementally update a source file more than once. Once @@ -5991,7 +5991,7 @@ namespace ts { // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - let result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true) + let result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); return result; } @@ -6006,8 +6006,9 @@ namespace ts { return; function visitNode(node: IncrementalNode) { + let text = ''; if (aggressiveChecks && shouldCheckNode(node)) { - var text = oldText.substring(node.pos, node.end); + text = oldText.substring(node.pos, node.end); } // Ditch any existing LS children we may have created. This way we can avoid @@ -6357,17 +6358,17 @@ namespace ts { interface IncrementalElement extends TextRange { parent?: Node; - intersectsChange: boolean + intersectsChange: boolean; length?: number; _children: Node[]; } export interface IncrementalNode extends Node, IncrementalElement { - hasBeenIncrementallyParsed: boolean + hasBeenIncrementallyParsed: boolean; } interface IncrementalNodeArray extends NodeArray, IncrementalElement { - length: number + length: number; } // Allows finding nodes in the source file at a certain position in an efficient manner. diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 28efaf24cca19..5ce4846b43b33 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -11,12 +11,12 @@ namespace ts { export const version = "1.5.3"; export function findConfigFile(searchPath: string): string { - var fileName = "tsconfig.json"; + let fileName = "tsconfig.json"; while (true) { if (sys.fileExists(fileName)) { return fileName; } - var parentPath = getDirectoryPath(searchPath); + let parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } @@ -35,7 +35,7 @@ namespace ts { // otherwise use toLowerCase as a canonical form. return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } - + // returned by CScript sys environment let unsupportedFileEncodingErrorCode = -2147024809; @@ -79,7 +79,7 @@ namespace ts { function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { try { - var start = new Date().getTime(); + let start = new Date().getTime(); ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data, writeByteOrderMark); ioWriteTime += new Date().getTime() - start; @@ -239,8 +239,8 @@ namespace ts { function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult { // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) { return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; } @@ -311,14 +311,14 @@ namespace ts { } catch (e) { if (e instanceof OperationCanceledException) { - // We were canceled while performing the operation. Because our type checker + // We were canceled while performing the operation. Because our type checker // might be a bad state, we need to throw it away. // // Note: we are overly agressive here. We do not actually *have* to throw away // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep // the lifetimes of these two TypeCheckers the same. Also, we generally only // cancel when the user has made a change anyways. And, in that case, we (the - // program instance) will get thrown away anyways. So trying to keep one of + // program instance) will get thrown away anyways. So trying to keep one of // these type checkers alive doesn't serve much purpose. noDiagnosticsTypeChecker = undefined; diagnosticsProducingTypeChecker = undefined; @@ -341,16 +341,16 @@ namespace ts { }); } - function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { + function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. - var writeFile: WriteFileCallback = () => { }; + let writeFile: WriteFileCallback = () => { }; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); - } + } function getOptionsDiagnostics(): Diagnostic[] { let allDiagnostics: Diagnostic[] = []; @@ -396,7 +396,7 @@ namespace ts { } } else { - var nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + let nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; @@ -496,7 +496,7 @@ namespace ts { let moduleNameText = (moduleNameExpr).text; if (moduleNameText) { let searchPath = basePath; - let searchName: string; + let searchName: string; while (true) { searchName = normalizePath(combinePaths(searchPath, moduleNameText)); if (forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, moduleNameExpr))) { @@ -513,7 +513,7 @@ namespace ts { } else if (node.kind === SyntaxKind.ModuleDeclaration && (node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 - // An AmbientExternalModuleDeclaration declares an external module. + // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted @@ -525,7 +525,7 @@ namespace ts { let moduleName = nameLiteral.text; if (moduleName) { // TypeScript 1.0 spec (April 2014): 12.1.6 - // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules + // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules // only through top - level external module names. Relative external module names are not permitted. let searchName = normalizePath(combinePaths(basePath, moduleName)); forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, nameLiteral)); @@ -664,7 +664,7 @@ namespace ts { } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) { - // We cannot use createDiagnosticFromNode because nodes do not have parents yet + // We cannot use createDiagnosticFromNode because nodes do not have parents yet let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); } @@ -691,7 +691,7 @@ namespace ts { } if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly + // Make sure directory path ends with directory separator so this string can directly // used to replace with "" to get the relative path of the source file and the relative path doesn't // start with / making it rooted path commonSourceDirectory += directorySeparator; @@ -707,12 +707,12 @@ namespace ts { diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); } } - + if (options.emitDecoratorMetadata && !options.experimentalDecorators) { diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified)); } - + if (options.experimentalAsyncFunctions && options.target !== ScriptTarget.ES6) { diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower)); diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index b7cead60381b4..d52f96c912b97 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -32,13 +32,13 @@ namespace ts { setScriptTarget(scriptTarget: ScriptTarget): void; setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; - // Invokes the provided callback then unconditionally restores the scanner to the state it + // Invokes the provided callback then unconditionally restores the scanner to the state it // was in immediately prior to invoking the callback. The result of invoking the callback // is returned from this function. lookAhead(callback: () => T): T; // Invokes the provided callback. If the callback returns something falsy, then it restores - // the scanner to the state it was in immediately prior to invoking the callback. If the + // the scanner to the state it was in immediately prior to invoking the callback. If the // callback returns something truthy, then the scanner state is not rolled back. The result // of invoking the callback is returned from this function. tryScan(callback: () => T): T; @@ -275,7 +275,7 @@ namespace ts { return textToToken[s]; } - /* @internal */ + /* @internal */ export function computeLineStarts(text: string): number[] { let result: number[] = new Array(); let pos = 0; @@ -307,22 +307,22 @@ namespace ts { return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); } - /* @internal */ + /* @internal */ export function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number): number { Debug.assert(line >= 0 && line < lineStarts.length); return lineStarts[line] + character; } - /* @internal */ + /* @internal */ export function getLineStarts(sourceFile: SourceFile): number[] { return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); } - /* @internal */ + /* @internal */ export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) { let lineNumber = binarySearch(lineStarts, position); if (lineNumber < 0) { - // If the actual position was not found, + // If the actual position was not found, // the binary search returns the negative value of the next line start // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 // then the search will return -2 @@ -355,125 +355,125 @@ namespace ts { ch === CharacterCodes.mathematicalSpace || ch === CharacterCodes.ideographicSpace || ch === CharacterCodes.byteOrderMark; - } - - export function isLineBreak(ch: number): boolean { - // ES5 7.3: - // The ECMAScript line terminator characters are listed in Table 3. - // Table 3: Line Terminator Characters - // Code Unit Value Name Formal Name - // \u000A Line Feed - // \u000D Carriage Return - // \u2028 Line separator - // \u2029 Paragraph separator - // Only the characters in Table 3 are treated as line terminators. Other new line or line - // breaking characters are treated as white space but not as line terminators. - - return ch === CharacterCodes.lineFeed || - ch === CharacterCodes.carriageReturn || - ch === CharacterCodes.lineSeparator || - ch === CharacterCodes.paragraphSeparator; - } - - function isDigit(ch: number): boolean { - return ch >= CharacterCodes._0 && ch <= CharacterCodes._9; - } - - /* @internal */ - export function isOctalDigit(ch: number): boolean { - return ch >= CharacterCodes._0 && ch <= CharacterCodes._7; - } - - export function couldStartTrivia(text: string, pos: number): boolean { - // Keep in sync with skipTrivia - let ch = text.charCodeAt(pos); - switch (ch) { - case CharacterCodes.carriageReturn: - case CharacterCodes.lineFeed: - case CharacterCodes.tab: - case CharacterCodes.verticalTab: - case CharacterCodes.formFeed: - case CharacterCodes.space: - case CharacterCodes.slash: - // starts of normal trivia - case CharacterCodes.lessThan: - case CharacterCodes.equals: - case CharacterCodes.greaterThan: - // Starts of conflict marker trivia - return true; - default: - return ch > CharacterCodes.maxAsciiCharacter; - } - } - - /* @internal */ - export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number { - // Keep in sync with couldStartTrivia - while (true) { - let ch = text.charCodeAt(pos); - switch (ch) { - case CharacterCodes.carriageReturn: - if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { - pos++; - } - case CharacterCodes.lineFeed: - pos++; - if (stopAfterLineBreak) { - return pos; - } - continue; - case CharacterCodes.tab: - case CharacterCodes.verticalTab: - case CharacterCodes.formFeed: - case CharacterCodes.space: - pos++; - continue; - case CharacterCodes.slash: - if (text.charCodeAt(pos + 1) === CharacterCodes.slash) { - pos += 2; - while (pos < text.length) { - if (isLineBreak(text.charCodeAt(pos))) { - break; - } - pos++; - } - continue; - } - if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) { - pos += 2; - while (pos < text.length) { - if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { - pos += 2; - break; - } - pos++; - } - continue; - } - break; - - case CharacterCodes.lessThan: - case CharacterCodes.equals: - case CharacterCodes.greaterThan: - if (isConflictMarkerTrivia(text, pos)) { - pos = scanConflictMarkerTrivia(text, pos); - continue; - } - break; - - default: - if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) { - pos++; - continue; - } - break; - } - return pos; - } - } - - // All conflict markers consist of the same character repeated seven times. If it is - // a <<<<<<< or >>>>>>> marker then it is also followd by a space. + } + + export function isLineBreak(ch: number): boolean { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + + return ch === CharacterCodes.lineFeed || + ch === CharacterCodes.carriageReturn || + ch === CharacterCodes.lineSeparator || + ch === CharacterCodes.paragraphSeparator; + } + + function isDigit(ch: number): boolean { + return ch >= CharacterCodes._0 && ch <= CharacterCodes._9; + } + + /* @internal */ + export function isOctalDigit(ch: number): boolean { + return ch >= CharacterCodes._0 && ch <= CharacterCodes._7; + } + + export function couldStartTrivia(text: string, pos: number): boolean { + // Keep in sync with skipTrivia + let ch = text.charCodeAt(pos); + switch (ch) { + case CharacterCodes.carriageReturn: + case CharacterCodes.lineFeed: + case CharacterCodes.tab: + case CharacterCodes.verticalTab: + case CharacterCodes.formFeed: + case CharacterCodes.space: + case CharacterCodes.slash: + // starts of normal trivia + case CharacterCodes.lessThan: + case CharacterCodes.equals: + case CharacterCodes.greaterThan: + // Starts of conflict marker trivia + return true; + default: + return ch > CharacterCodes.maxAsciiCharacter; + } + } + + /* @internal */ + export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number { + // Keep in sync with couldStartTrivia + while (true) { + let ch = text.charCodeAt(pos); + switch (ch) { + case CharacterCodes.carriageReturn: + if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { + pos++; + } + case CharacterCodes.lineFeed: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case CharacterCodes.tab: + case CharacterCodes.verticalTab: + case CharacterCodes.formFeed: + case CharacterCodes.space: + pos++; + continue; + case CharacterCodes.slash: + if (text.charCodeAt(pos + 1) === CharacterCodes.slash) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === CharacterCodes.asterisk) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + + case CharacterCodes.lessThan: + case CharacterCodes.equals: + case CharacterCodes.greaterThan: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + + default: + if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followd by a space. let mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text: string, pos: number) { @@ -528,12 +528,12 @@ namespace ts { return pos; } - // Extract comments from the given source text starting at the given position. If trailing is - // false, whitespace is skipped until the first line break and comments between that location - // and the next token are returned.If trailing is true, comments occurring between the given - // position and the next line break are returned.The return value is an array containing a - // TextRange for each comment. Single-line comment ranges include the beginning '//' characters - // but not the ending line break. Multi - line comment ranges include the beginning '/* and + // Extract comments from the given source text starting at the given position. If trailing is + // false, whitespace is skipped until the first line break and comments between that location + // and the next token are returned.If trailing is true, comments occurring between the given + // position and the next line break are returned.The return value is an array containing a + // TextRange for each 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[] { let result: CommentRange[]; @@ -629,9 +629,9 @@ namespace ts { ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ || ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion); } - - /* @internal */ - // Creates a scanner over a (possibly unspecified) range of a piece of text. + + /* @internal */ + // Creates a scanner over a (possibly unspecified) range of a piece of text. export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant = LanguageVariant.Standard, @@ -640,16 +640,16 @@ namespace ts { start?: number, length?: number): Scanner { // Current position (end position of text of current token) - let pos: number; + let pos: number; // end of text - let end: number; + let end: number; // Start position of whitespace before current token - let startPos: number; + let startPos: number; // Start position of text of current token - let tokenPos: number; + let tokenPos: number; let token: SyntaxKind; let tokenValue: string; @@ -735,7 +735,7 @@ namespace ts { } return +(text.substring(start, pos)); } - + /** * Scans the given number of hexadecimal digits in the text, * returning -1 if the given number is unavailable. @@ -743,7 +743,7 @@ namespace ts { function scanExactNumberOfHexDigits(count: number): number { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); } - + /** * Scans as many hexadecimal digits as are available in the text, * returning -1 if the given number of digits was unavailable. @@ -821,7 +821,7 @@ namespace ts { pos++; let start = pos; - let contents = "" + let contents = ""; let resultingToken: SyntaxKind; while (true) { @@ -916,13 +916,13 @@ namespace ts { pos++; return scanExtendedUnicodeEscape(); } - + // '\uDDDD' - return scanHexadecimalEscape(/*numDigits*/ 4) - + return scanHexadecimalEscape(/*numDigits*/ 4); + case CharacterCodes.x: // '\xDD' - return scanHexadecimalEscape(/*numDigits*/ 2) + return scanHexadecimalEscape(/*numDigits*/ 2); // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), // the line terminator is interpreted to be "the empty code unit sequence". @@ -934,31 +934,31 @@ namespace ts { case CharacterCodes.lineFeed: case CharacterCodes.lineSeparator: case CharacterCodes.paragraphSeparator: - return "" + return ""; default: return String.fromCharCode(ch); } } - + function scanHexadecimalEscape(numDigits: number): string { let escapedValue = scanExactNumberOfHexDigits(numDigits); - + if (escapedValue >= 0) { return String.fromCharCode(escapedValue); } else { error(Diagnostics.Hexadecimal_digit_expected); - return "" + return ""; } } - + function scanExtendedUnicodeEscape(): string { let escapedValue = scanMinimumNumberOfHexDigits(1); let isInvalidExtendedEscape = false; // Validate the value of the digit if (escapedValue < 0) { - error(Diagnostics.Hexadecimal_digit_expected) + error(Diagnostics.Hexadecimal_digit_expected); isInvalidExtendedEscape = true; } else if (escapedValue > 0x10FFFF) { @@ -985,18 +985,18 @@ namespace ts { return utf16EncodeAsString(escapedValue); } - + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. function utf16EncodeAsString(codePoint: number): string { Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); - + if (codePoint <= 65535) { return String.fromCharCode(codePoint); } - + let codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; let codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; - + return String.fromCharCode(codeUnit1, codeUnit2); } @@ -1058,7 +1058,7 @@ namespace ts { 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. - let numberOfDigits = 0; + let numberOfDigits = 0; while (true) { let ch = text.charCodeAt(pos); let valueOfCh = ch - CharacterCodes._0; @@ -1132,7 +1132,7 @@ namespace ts { tokenValue = scanString(); return token = SyntaxKind.StringLiteral; case CharacterCodes.backtick: - return token = scanTemplateAndSetTokenValue() + return token = scanTemplateAndSetTokenValue(); case CharacterCodes.percent: if (text.charCodeAt(pos + 1) === CharacterCodes.equals) { return pos += 2, token = SyntaxKind.PercentEqualsToken; @@ -1444,14 +1444,14 @@ namespace ts { // regex. Report error and return what we have so far. if (p >= end) { tokenIsUnterminated = true; - error(Diagnostics.Unterminated_regular_expression_literal) + error(Diagnostics.Unterminated_regular_expression_literal); break; } let ch = text.charCodeAt(p); if (isLineBreak(ch)) { tokenIsUnterminated = true; - error(Diagnostics.Unterminated_regular_expression_literal) + error(Diagnostics.Unterminated_regular_expression_literal); break; } @@ -1543,7 +1543,7 @@ namespace ts { let ch = text.charCodeAt(pos); if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch) : isIdentifierPart(ch))) { pos++; - } + } else { break; } @@ -1552,7 +1552,7 @@ namespace ts { } return token; } - + function speculationHelper(callback: () => T, isLookahead: boolean): T { let savePos = pos; let saveStartPos = startPos; diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index a47d6959ba81a..443c1c4789c8c 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -41,16 +41,16 @@ namespace ts { function getWScriptSystem(): System { - var fso = new ActiveXObject("Scripting.FileSystemObject"); + let fso = new ActiveXObject("Scripting.FileSystemObject"); - var fileStream = new ActiveXObject("ADODB.Stream"); + let fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; - var binaryStream = new ActiveXObject("ADODB.Stream"); + let binaryStream = new ActiveXObject("ADODB.Stream"); binaryStream.Type = 1 /*binary*/; - var args: string[] = []; - for (var i = 0; i < WScript.Arguments.length; i++) { + let args: string[] = []; + for (let i = 0; i < WScript.Arguments.length; i++) { args[i] = WScript.Arguments.Item(i); } @@ -68,7 +68,7 @@ namespace ts { // Load file and read the first two bytes into a string with no interpretation fileStream.Charset = "x-ansi"; fileStream.LoadFromFile(fileName); - var bom = fileStream.ReadText(2) || ""; + let bom = fileStream.ReadText(2) || ""; // Position must be at 0 before encoding can be changed fileStream.Position = 0; // [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8 @@ -114,28 +114,28 @@ namespace ts { } function getNames(collection: any): string[]{ - var result: string[] = []; - for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { + let result: string[] = []; + for (let e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { result.push(e.item().Name); } return result.sort(); } function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { - var result: string[] = []; + let result: string[] = []; exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { - var folder = fso.GetFolder(path || "."); - var files = getNames(folder.files); + let folder = fso.GetFolder(path || "."); + let files = getNames(folder.files); for (let current of files) { let name = combinePaths(path, current); if ((!extension || fileExtensionIs(name, extension)) && !contains(exclude, getCanonicalPath(name))) { result.push(name); } } - var subfolders = getNames(folder.subfolders); + let subfolders = getNames(folder.subfolders); for (let current of subfolders) { let name = combinePaths(path, current); if (!contains(exclude, getCanonicalPath(name))) { @@ -197,14 +197,14 @@ namespace ts { if (!_fs.existsSync(fileName)) { return undefined; } - var buffer = _fs.readFileSync(fileName); - var len = buffer.length; + let buffer = _fs.readFileSync(fileName); + let len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, // flip all byte pairs and treat as little endian. len &= ~1; - for (var i = 0; i < len; i += 2) { - var temp = buffer[i]; + for (let i = 0; i < len; i += 2) { + let temp = buffer[i]; buffer[i] = buffer[i + 1]; buffer[i + 1] = temp; } @@ -236,17 +236,17 @@ namespace ts { } function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { - var result: string[] = []; + let result: string[] = []; exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { - var files = _fs.readdirSync(path || ".").sort(); - var directories: string[] = []; + let files = _fs.readdirSync(path || ".").sort(); + let directories: string[] = []; for (let current of files) { - var name = combinePaths(path, current); + let name = combinePaths(path, current); if (!contains(exclude, getCanonicalPath(name))) { - var stat = _fs.statSync(name); + let stat = _fs.statSync(name); if (stat.isFile()) { if (!extension || fileExtensionIs(name, extension)) { result.push(name); @@ -331,4 +331,4 @@ namespace ts { return undefined; // Unsupported host } })(); -} \ No newline at end of file +} diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 2a01774fbcaaf..a657cc8c314b9 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -11,15 +11,15 @@ namespace ts { * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp')); return false; } - var language = matchResult[1]; - var territory = matchResult[3]; + let language = matchResult[1]; + let territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. if (!trySetLanguageAndTerritory(language, territory, errors) && @@ -33,10 +33,10 @@ namespace ts { } function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean { - var compilerFilePath = normalizePath(sys.getExecutingFilePath()); - var containingDirectoryPath = getDirectoryPath(compilerFilePath); + let compilerFilePath = normalizePath(sys.getExecutingFilePath()); + let containingDirectoryPath = getDirectoryPath(compilerFilePath); - var filePath = combinePaths(containingDirectoryPath, language); + let filePath = combinePaths(containingDirectoryPath, language); if (territory) { filePath = filePath + "-" + territory; @@ -49,8 +49,9 @@ namespace ts { } // TODO: Add codePage support for readFile? + let fileContents = ''; try { - var fileContents = sys.readFile(filePath); + fileContents = sys.readFile(filePath); } catch (e) { errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); @@ -68,7 +69,7 @@ namespace ts { } function countLines(program: Program): number { - var count = 0; + let count = 0; forEach(program.getSourceFiles(), file => { count += getLineStarts(file).length; }); @@ -76,27 +77,27 @@ namespace ts { } function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string { - var diagnostic = createCompilerDiagnostic.apply(undefined, arguments); + let diagnostic = createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } function reportDiagnostic(diagnostic: Diagnostic) { - var output = ""; - + let output = ""; + if (diagnostic.file) { - var loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `; } - var category = DiagnosticCategory[diagnostic.category].toLowerCase(); + let category = DiagnosticCategory[diagnostic.category].toLowerCase(); output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`; sys.write(output); } function reportDiagnostics(diagnostics: Diagnostic[]) { - for (var i = 0; i < diagnostics.length; i++) { + for (let i = 0; i < diagnostics.length; i++) { reportDiagnostic(diagnostics[i]); } } @@ -133,15 +134,15 @@ namespace ts { } export function executeCommandLine(args: string[]): void { - var commandLine = parseCommandLine(args); - var configFileName: string; // Configuration file name (if any) - var configFileWatcher: FileWatcher; // Configuration file watcher - var cachedProgram: Program; // Program cached from last compilation - var rootFileNames: string[]; // Root fileNames for compilation - var compilerOptions: CompilerOptions; // Compiler options for compilation - var compilerHost: CompilerHost; // Compiler host - var hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host - var timerHandle: number; // Handle for 0.25s wait timer + let commandLine = parseCommandLine(args); + let configFileName: string; // Configuration file name (if any) + let configFileWatcher: FileWatcher; // Configuration file watcher + let cachedProgram: Program; // Program cached from last compilation + let rootFileNames: string[]; // Root fileNames for compilation + let compilerOptions: CompilerOptions; // Compiler options for compilation + let compilerHost: CompilerHost; // Compiler host + let hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host + let timerHandle: number; // Handle for 0.25s wait timer if (commandLine.options.locale) { if (!isJSONSupported()) { @@ -181,7 +182,7 @@ namespace ts { } } else if (commandLine.fileNames.length === 0 && isJSONSupported()) { - var searchPath = normalizePath(sys.getCurrentDirectory()); + let searchPath = normalizePath(sys.getCurrentDirectory()); configFileName = findConfigFile(searchPath); } @@ -247,14 +248,14 @@ namespace ts { function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) { // Return existing SourceFile object if one is available if (cachedProgram) { - var sourceFile = cachedProgram.getSourceFile(fileName); + let sourceFile = cachedProgram.getSourceFile(fileName); // A modified source file has no watcher and should not be reused if (sourceFile && sourceFile.fileWatcher) { return sourceFile; } } // Use default host function - var sourceFile = hostGetSourceFile(fileName, languageVersion, onError); + let sourceFile = hostGetSourceFile(fileName, languageVersion, onError); if (sourceFile && compilerOptions.watch) { // Attach a file watcher sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, () => sourceFileChanged(sourceFile)); @@ -265,7 +266,7 @@ namespace ts { // Change cached program to the given program function setCachedProgram(program: Program) { if (cachedProgram) { - var newSourceFiles = program ? program.getSourceFiles() : undefined; + let newSourceFiles = program ? program.getSourceFiles() : undefined; forEach(cachedProgram.getSourceFiles(), sourceFile => { if (!(newSourceFiles && contains(newSourceFiles, sourceFile))) { if (sourceFile.fileWatcher) { @@ -316,8 +317,8 @@ namespace ts { checkTime = 0; emitTime = 0; - var program = createProgram(fileNames, compilerOptions, compilerHost); - var exitStatus = compileProgram(); + let program = createProgram(fileNames, compilerOptions, compilerHost); + let exitStatus = compileProgram(); if (compilerOptions.listFiles) { forEach(program.getSourceFiles(), file => { @@ -326,7 +327,7 @@ namespace ts { } if (compilerOptions.diagnostics) { - var memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; + let memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); reportCountStatistic("Nodes", program.getNodeCount()); @@ -354,18 +355,18 @@ namespace ts { return { program, exitStatus }; function compileProgram(): ExitStatus { - // First get any syntactic errors. - var diagnostics = program.getSyntacticDiagnostics(); + // First get any syntactic errors. + let diagnostics = program.getSyntacticDiagnostics(); reportDiagnostics(diagnostics); - // If we didn't have any syntactic errors, then also try getting the global and + // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === 0) { - var diagnostics = program.getGlobalDiagnostics(); + let diagnostics = program.getGlobalDiagnostics(); reportDiagnostics(diagnostics); if (diagnostics.length === 0) { - var diagnostics = program.getSemanticDiagnostics(); + let diagnostics = program.getSemanticDiagnostics(); reportDiagnostics(diagnostics); } } @@ -378,7 +379,7 @@ namespace ts { } // Otherwise, emit and report any errors we ran into. - var emitOutput = program.emit(); + let emitOutput = program.emit(); reportDiagnostics(emitOutput.diagnostics); // If the emitter didn't emit anything, then pass that value along. @@ -401,22 +402,22 @@ namespace ts { } function printHelp() { - var output = ""; + let output = ""; // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); + let syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; + let examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; + let marginLength = Math.max(syntaxLength, examplesLength); // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); + let syntax = makePadding(marginLength - syntaxLength); syntax += "tsc [" + getDiagnosticText(Diagnostics.options) + "] [" + getDiagnosticText(Diagnostics.file) + " ...]"; output += getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax); output += sys.newLine + sys.newLine; // Build up the list of examples. - var padding = makePadding(marginLength); + let padding = makePadding(marginLength); output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine; output += padding + "tsc --out file.js file.ts" + sys.newLine; output += padding + "tsc @args.txt" + sys.newLine; @@ -425,17 +426,17 @@ namespace ts { output += getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine; // Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch") - var optsList = filter(optionDeclarations.slice(), v => !v.experimental); + let optsList = filter(optionDeclarations.slice(), v => !v.experimental); optsList.sort((a, b) => compareValues(a.name.toLowerCase(), b.name.toLowerCase())); // We want our descriptions to align at the same column in our output, // so we keep track of the longest option usage string. - var marginLength = 0; - var usageColumn: string[] = []; // Things like "-d, --declaration" go in here. - var descriptionColumn: string[] = []; + marginLength = 0; + let usageColumn: string[] = []; // Things like "-d, --declaration" go in here. + let descriptionColumn: string[] = []; - for (var i = 0; i < optsList.length; i++) { - var option = optsList[i]; + for (let i = 0; i < optsList.length; i++) { + let option = optsList[i]; // If an option lacks a description, // it is not officially supported. @@ -443,7 +444,7 @@ namespace ts { continue; } - var usageText = " "; + let usageText = " "; if (option.shortName) { usageText += "-" + option.shortName; usageText += getParamType(option); @@ -461,15 +462,15 @@ namespace ts { } // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; + let usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; usageColumn.push(usageText); descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file)); marginLength = Math.max(usageText.length, marginLength); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; + for (let i = 0; i < usageColumn.length; i++) { + let usage = usageColumn[i]; + let description = descriptionColumn[i]; output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 6c2f72a1ab794..389eda4ccede0 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -273,7 +273,7 @@ namespace ts { // Module references ExternalModuleReference, - //JSX + // JSX JsxElement, JsxSelfClosingElement, JsxOpeningElement, @@ -405,10 +405,10 @@ namespace ts { // Context flags set directly by the parser. ParserGeneratedFlags = DisallowIn | Yield | Decorator | ThisNodeHasError | Await, - + // Exclude these flags when parsing a Type - TypeExcludesFlags = Yield | Await, - + TypeExcludesFlags = Yield | Await, + // Context flags computed by aggregating child flags upwards. // Used during incremental parsing to determine if this node or any of its children had an @@ -1055,7 +1055,7 @@ namespace ts { } export interface ModuleBlock extends Node, Statement { - statements: NodeArray + statements: NodeArray; } export interface ImportEqualsDeclaration extends Declaration, Statement { @@ -1171,7 +1171,7 @@ namespace ts { export interface JSDocTypeReference extends JSDocType { name: EntityName; - typeArguments: NodeArray + typeArguments: NodeArray; } export interface JSDocOptionalType extends JSDocType { @@ -1196,8 +1196,8 @@ namespace ts { } export interface JSDocRecordMember extends PropertyDeclaration { - name: Identifier | LiteralExpression, - type?: JSDocType + name: Identifier | LiteralExpression; + type?: JSDocType; } export interface JSDocComment extends Node { @@ -1294,7 +1294,7 @@ namespace ts { export interface CancellationToken { isCancellationRequested(): boolean; - + /** @throws OperationCanceledException if isCancellationRequested is true */ throwIfCancellationRequested(): void; } @@ -1323,7 +1323,7 @@ namespace ts { getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - /** + /** * Gets a type checker that can be used to semantically analyze source fils in the program. */ getTypeChecker(): TypeChecker; @@ -1344,15 +1344,15 @@ namespace ts { export interface SourceMapSpan { /** Line number in the .js file. */ - emittedLine: number; + emittedLine: number; /** Column number in the .js file. */ - emittedColumn: number; + emittedColumn: number; /** Line number in the .ts file. */ - sourceLine: number; + sourceLine: number; /** Column number in the .ts file. */ - sourceColumn: number; + sourceColumn: number; /** Optional name (index into names array) associated with this span. */ - nameIndex?: number; + nameIndex?: number; /** .ts file (index into sources array) associated with this span */ sourceIndex: number; } @@ -1506,7 +1506,7 @@ namespace ts { NotAccessible, CannotBeNamed } - + export interface TypePredicate { parameterName: string; parameterIndex: number; @@ -1526,7 +1526,7 @@ namespace ts { /* @internal */ export interface SymbolAccessiblityResult extends SymbolVisibilityResult { - errorModuleName?: string // If the symbol is not visible from module, module's name + errorModuleName?: string; // If the symbol is not visible from module, module's name } /* @internal */ @@ -1637,7 +1637,7 @@ namespace ts { Export = ExportNamespace | ExportType | ExportValue, /* @internal */ - // The set of things we consider semantically classifiable. Used to speed up the LS during + // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module, } @@ -1657,7 +1657,7 @@ namespace ts { /* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums } - /* @internal */ + /* @internal */ export interface SymbolLinks { target?: Symbol; // Resolved (non-alias) target of an alias type?: Type; // Type of value symbol @@ -1672,14 +1672,14 @@ namespace ts { isNestedRedeclaration?: boolean; // True if symbol is block scoped redeclaration } - /* @internal */ + /* @internal */ export interface TransientSymbol extends Symbol, SymbolLinks { } export interface SymbolTable { [index: string]: Symbol; } - /* @internal */ + /* @internal */ export const enum NodeCheckFlags { TypeChecked = 0x00000001, // Node has been type checked LexicalThis = 0x00000002, // Lexical 'this' reference @@ -1701,7 +1701,7 @@ namespace ts { LexicalModuleMergesWithClass= 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration. } - /* @internal */ + /* @internal */ export interface NodeLinks { resolvedType?: Type; // Cached type of type node resolvedAwaitedType?: Type; // Cached awaited type of type node @@ -1748,17 +1748,17 @@ namespace ts { ContainsObjectLiteral = 0x00200000, // Type is or contains object literal type ESSymbol = 0x00400000, // Type of symbol primitive introduced in ES6 - /* @internal */ + /* @internal */ Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null, - /* @internal */ + /* @internal */ Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum, StringLike = String | StringLiteral, NumberLike = Number | Enum, ObjectType = Class | Interface | Reference | Tuple | Anonymous, - UnionOrIntersection = Union | Intersection, + UnionOrIntersection = Union | Intersection, StructuredType = ObjectType | Union | Intersection, - /* @internal */ - RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral + /* @internal */ + RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral } // Properties common to all types @@ -1768,7 +1768,7 @@ namespace ts { symbol?: Symbol; // Symbol associated with type (if any) } - /* @internal */ + /* @internal */ // Intrinsic types (TypeFlags.Intrinsic) export interface IntrinsicType extends Type { intrinsicName: string; // Name of intrinsic type diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index e66e1925519ed..1750b7a524528 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3,9 +3,9 @@ /* @internal */ namespace ts { export interface ReferencePathMatchResult { - fileReference?: FileReference - diagnosticMessage?: DiagnosticMessage - isNoDefaultLib?: boolean + fileReference?: FileReference; + diagnosticMessage?: DiagnosticMessage; + isNoDefaultLib?: boolean; } export interface SynthesizedNode extends Node { @@ -70,7 +70,7 @@ namespace ts { } export function releaseStringWriter(writer: StringSymbolWriter) { - writer.clear() + writer.clear(); stringWriters.push(writer); } @@ -81,7 +81,7 @@ namespace ts { // Returns true if this node contains a parse error anywhere underneath it. export function containsParseError(node: Node): boolean { aggregateChildData(node); - return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0 + return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0; } function aggregateChildData(node: Node): void { @@ -92,7 +92,7 @@ namespace ts { let thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || forEachChild(node, containsParseError); - // If so, mark ourselves accordingly. + // If so, mark ourselves accordingly. if (thisNodeOrAnySubNodesHasError) { node.parserContextFlags |= ParserContextFlags.ThisNodeOrAnySubNodesHasError; } @@ -129,13 +129,13 @@ namespace ts { // Returns true if this node is missing from the actual source code. 'missing' is different // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes - // in the tree), it is definitel missing. HOwever, a node may be defined, but still be + // in the tree), it is definitel missing. HOwever, a node may be defined, but still be // missing. This happens whenever the parser knows it needs to parse something, but can't // get anything in the source code that it expects at that location. For example: // // let a: ; // - // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source // code). So the parser will attempt to parse out a type, and will create an actual node. // However, this node will be 'missing' in the sense that no actual source-code/tokens are // contained within it. @@ -166,7 +166,7 @@ namespace ts { return getTokenPosOfNode(node, sourceFile); } - return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); } export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia = false): string { @@ -211,7 +211,7 @@ namespace ts { isCatchClauseVariableDeclaration(declaration); } - // Gets the nearest enclosing block scope container that has the provided node + // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. export function getEnclosingBlockScopeContainer(node: Node): Node { let current = node.parent; @@ -307,7 +307,7 @@ namespace ts { } if (errorNode === undefined) { - // If we don't have a better node, then just set the error on the first token of + // If we don't have a better node, then just set the error on the first token of // construct. return getSpanOfTokenAtPosition(sourceFile, node.pos); } @@ -339,10 +339,10 @@ namespace ts { return node; } - // Returns the node flags for this node and all relevant parent nodes. This is done so that + // Returns the node flags for this node and all relevant parent nodes. This is done so that // nodes like variable declarations and binding elements can returned a view of their flags // that includes the modifiers from their container. i.e. flags like export/declare aren't - // stored on the variable declaration directly, but on the containing variable statement + // stored on the variable declaration directly, but on the containing variable statement // (if it has one). Similarly, flags for let/const are store on the variable declaration // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. @@ -406,7 +406,7 @@ namespace ts { } } - export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/ + export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; export function isTypeNode(node: Node): boolean { if (SyntaxKind.FirstTypeNode <= node.kind && node.kind <= SyntaxKind.LastTypeNode) { @@ -662,7 +662,7 @@ namespace ts { node = node.parent; break; case SyntaxKind.Decorator: - // Decorators are always applied outside of the body of a class or method. + // Decorators are always applied outside of the body of a class or method. if (node.parent.kind === SyntaxKind.Parameter && isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. @@ -717,7 +717,7 @@ namespace ts { node = node.parent; break; case SyntaxKind.Decorator: - // Decorators are always applied outside of the body of a class or method. + // Decorators are always applied outside of the body of a class or method. if (node.parent.kind === SyntaxKind.Parameter && isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. @@ -746,14 +746,14 @@ namespace ts { } } } - + export function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression { - if (node) { + if (node) { switch (node.kind) { case SyntaxKind.TypeReference: return (node).typeName; case SyntaxKind.ExpressionWithTypeArguments: - return (node).expression + return (node).expression; case SyntaxKind.Identifier: case SyntaxKind.QualifiedName: return (node); @@ -767,7 +767,7 @@ namespace ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { return (node).tag; } - + // Will either be a CallExpression, NewExpression, or Decorator. return (node).expression; } @@ -949,7 +949,7 @@ namespace ts { } export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) { - let moduleState = getModuleInstanceState(node) + let moduleState = getModuleInstanceState(node); return moduleState === ModuleInstanceState.Instantiated || (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); } @@ -1031,7 +1031,7 @@ namespace ts { export function getCorrespondingJSDocParameterTag(parameter: ParameterDeclaration): JSDocParameterTag { if (parameter.name && parameter.name.kind === SyntaxKind.Identifier) { - // If it's a parameter, see if the parent has a jsdoc comment with an @param + // If it's a parameter, see if the parent has a jsdoc comment with an @param // annotation. let parameterName = (parameter.name).text; @@ -1301,7 +1301,7 @@ namespace ts { if (isNoDefaultLibRegEx.exec(comment)) { return { isNoDefaultLib: true - } + }; } else { let matchResult = fullTripleSlashReferencePathRegEx.exec(comment); @@ -1417,7 +1417,7 @@ namespace ts { } return node; } - + export function nodeStartsNewLexicalEnvironment(n: Node): boolean { return isFunctionLike(n) || n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.SourceFile; } @@ -1433,7 +1433,7 @@ namespace ts { } export function createSynthesizedNodeArray(): NodeArray { - var array = >[]; + let array = >[]; array.pos = -1; array.end = -1; return array; @@ -1517,7 +1517,7 @@ namespace ts { } } } - + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in // the language service. These characters should be escaped when printing, and if any characters are added, @@ -1969,7 +1969,7 @@ namespace ts { return false; } } - + export function isRightSideOfQualifiedNameOrPropertyAccess(node: Node) { return (node.parent.kind === SyntaxKind.QualifiedName && (node.parent).right === node) || (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).name === node); @@ -1988,7 +1988,7 @@ namespace ts { } /** - * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. */ function getExpandedCharCodes(input: string): number[] { @@ -2031,7 +2031,7 @@ namespace ts { * Converts a string to a base-64 encoded ASCII string. */ export function convertToBase64(input: string): string { - var result = ""; + let result = ""; let charCodes = getExpandedCharCodes(input); let i = 0; let length = charCodes.length; @@ -2073,7 +2073,7 @@ namespace ts { return lineFeed; } else if (sys) { - return sys.newLine + return sys.newLine; } return carriageReturnLineFeed; } @@ -2085,11 +2085,11 @@ namespace ts { } export function textSpanEnd(span: TextSpan) { - return span.start + span.length + return span.start + span.length; } export function textSpanIsEmpty(span: TextSpan) { - return span.length === 0 + return span.length === 0; } export function textSpanContainsPosition(span: TextSpan, position: number) { @@ -2117,7 +2117,7 @@ namespace ts { } export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; } export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) { @@ -2178,10 +2178,10 @@ namespace ts { export let unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); /** - * Called to merge all the changes that occurred across several versions of a script snapshot + * Called to merge all the changes that occurred across several versions of a script snapshot * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * * This function will then merge those changes into a single change range valid between V1 and * Vn. */ @@ -2212,17 +2212,17 @@ namespace ts { // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------------------------------------------------- - // | / - // | /---- - // T1 | /---- - // | /---- - // | /---- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- // ------------------------------------------------------------------------------------------------------- - // | \ - // | \ - // T2 | \ - // | \ - // | \ + // | \ + // | \ + // T2 | \ + // | \ + // | \ // ------------------------------------------------------------------------------------------------------- // // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial @@ -2230,17 +2230,17 @@ namespace ts { // // 0 10 20 30 40 50 60 70 80 90 100 // ------------------------------------------------------------*------------------------------------------ - // | / - // | /---- - // T1 | /---- - // | /---- - // | /---- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- // ----------------------------------------$-------------------$------------------------------------------ - // . | \ - // . | \ - // T2 . | \ - // . | \ - // . | \ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ // ----------------------------------------------------------------------*-------------------------------- // // (Note the dots represent the newly inferrred start. @@ -2251,22 +2251,22 @@ namespace ts { // // 0 10 20 30 40 50 60 70 80 90 100 // --------------------------------------------------------------------------------*---------------------- - // | / - // | /---- - // T1 | /---- - // | /---- - // | /---- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- // ------------------------------------------------------------$------------------------------------------ - // . | \ - // . | \ - // T2 . | \ - // . | \ - // . | \ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ // ----------------------------------------------------------------------*-------------------------------- // // In other words (in this case), we're recognizing that the second edit happened after where the first edit // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started - // that's the same as if we started at char 80 instead of 60. + // that's the same as if we started at char 80 instead of 60. // // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter // than pusing the first edit forward to match the second, we'll push the second edit forward to match the @@ -2276,7 +2276,7 @@ namespace ts { // semantics: { { start: 10, length: 70 }, newLength: 60 } // // The math then works out as follows. - // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the // final result like so: // // { diff --git a/tslint.json b/tslint.json new file mode 100644 index 0000000000000..16a69b81f83e1 --- /dev/null +++ b/tslint.json @@ -0,0 +1,23 @@ +{ + "rules": { + "class-name": true, + "comment-format": [true, + "check-space" + ], + "indent": true, + "one-line": [true, + "check-open-brace" + ], + "no-unreachable": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "quotemark": true, + "semicolon": true, + "whitespace": [true, + "check-branch", + "check-operator", + "check-separator", + "check-type" + ] + } +}