diff --git a/.gitignore b/.gitignore index 05f981a0ace..db8e29d903a 100644 --- a/.gitignore +++ b/.gitignore @@ -28,9 +28,9 @@ build.json *.actual tests/webhost/*.d.ts tests/webhost/webtsc.js -tests/*.js -tests/*.js.map -tests/*.d.ts +tests/cases/**/*.js +tests/cases/**/*.js.map +tests/cases/**/*.d.ts *.config scripts/debug.bat scripts/run.bat diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1dba1281dd7..7a99bf318d2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,7 +13,7 @@ Issues that ask questions answered in the FAQ will be closed without elaboration ## 3. Do you have a question? The issue tracker is for **issues**, in other words, bugs and suggestions. -If you have a *question*, please use [http://stackoverflow.com/questions/tagged/typescript](Stack Overflow), [https://gitter.im/Microsoft/TypeScript](Gitter), your favorite search engine, or other resources. +If you have a *question*, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources. Due to increased traffic, we can no longer answer questions in the issue tracker. ## 4. Did you find a bug? diff --git a/Jakefile.js b/Jakefile.js index 7b85aacaa89..84248ca34d1 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -223,51 +223,59 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); * @param prereqs: prerequisite tasks to compiling the file * @param prefixes: a list of files to prepend to the target file * @param useBuiltCompiler: true to use the built compiler, false to use the LKG - * @param noOutFile: true to compile without using --out - * @param generateDeclarations: true to compile using --declaration - * @param outDir: true to compile using --outDir - * @param keepComments: false to compile using --removeComments + * @parap {Object} opts - property bag containing auxiliary options + * @param {boolean} opts.noOutFile: true to compile without using --out + * @param {boolean} opts.generateDeclarations: true to compile using --declaration + * @param {string} opts.outDir: value for '--outDir' command line option + * @param {boolean} opts.keepComments: false to compile using --removeComments + * @param {boolean} opts.preserveConstEnums: true if compiler should keep const enums in code + * @param {boolean} opts.noResolve: true if compiler should not include non-rooted files in compilation + * @param {boolean} opts.stripInternal: true if compiler should remove declarations marked as @internal + * @param {boolean} opts.noMapRoot: true if compiler omit mapRoot option * @param callback: a function to execute after the compilation process ends */ -function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) { +function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) { file(outFile, prereqs, function() { var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler; var options = "--noImplicitAny --noEmitOnError --pretty"; - + opts = opts || {}; // Keep comments when specifically requested // or when in debug mode. - if (!(keepComments || useDebugMode)) { + if (!(opts.keepComments || useDebugMode)) { options += " --removeComments"; } - if (generateDeclarations) { + if (opts.generateDeclarations) { options += " --declaration"; } - if (preserveConstEnums || useDebugMode) { + if (opts.preserveConstEnums || useDebugMode) { options += " --preserveConstEnums"; } - if (outDir) { - options += " --outDir " + outDir; + if (opts.outDir) { + options += " --outDir " + opts.outDir; } - if (!noOutFile) { + if (!opts.noOutFile) { options += " --out " + outFile; } else { options += " --module commonjs" } - if(noResolve) { + if(opts.noResolve) { options += " --noResolve"; } if (useDebugMode) { - options += " -sourcemap -mapRoot file:///" + path.resolve(path.dirname(outFile)); + options += " -sourcemap"; + if (!opts.noMapRoot) { + options += " -mapRoot file:///" + path.resolve(path.dirname(outFile)); + } } - if (stripInternal) { + if (opts.stripInternal) { options += " --stripInternal" } @@ -382,13 +390,7 @@ compileFile(/*outfile*/configureNightlyJs, /*prereqs*/ [configureNightlyTs], /*prefixes*/ [], /*useBuiltCompiler*/ false, - /*noOutFile*/ false, - /*generateDeclarations*/ false, - /*outDir*/ undefined, - /*preserveConstEnums*/ undefined, - /*keepComments*/ false, - /*noResolve*/ false, - /*stripInternal*/ false); + { noOutFile: false, generateDeclarations: false, keepComments: false, noResolve: false, stripInternal: false }); task("setDebugMode", function() { useDebugMode = true; @@ -438,6 +440,7 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename); compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false); var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js"); +var servicesFileInBrowserTest = path.join(builtLocalDirectory, "typescriptServicesInBrowserTest.js"); var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts"); var nodePackageFile = path.join(builtLocalDirectory, "typescript.js"); var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts"); @@ -446,13 +449,7 @@ var nodeStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescript_s compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, - /*noOutFile*/ false, - /*generateDeclarations*/ true, - /*outDir*/ undefined, - /*preserveConstEnums*/ true, - /*keepComments*/ true, - /*noResolve*/ false, - /*stripInternal*/ true, + { noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true }, /*callback*/ function () { jake.cpR(servicesFile, nodePackageFile, {silent: true}); @@ -475,6 +472,16 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca fs.writeFileSync(nodeStandaloneDefinitionsFile, nodeStandaloneDefinitionsFileContents); }); +compileFile(servicesFileInBrowserTest, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), + /*prefixes*/ [copyright], + /*useBuiltCompiler*/ true, + { noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true, noMapRoot: true }, + /*callback*/ function () { + var content = fs.readFileSync(servicesFileInBrowserTest).toString(); + var i = content.lastIndexOf("\n"); + fs.writeFileSync(servicesFileInBrowserTest, content.substring(0, i) + "\r\n//# sourceURL=../built/local/typeScriptServices.js" + content.substring(i)); + }); + var serverFile = path.join(builtLocalDirectory, "tsserver.js"); compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true); @@ -486,8 +493,7 @@ compileFile( [builtLocalDirectory, copyright].concat(languageServiceLibrarySources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, - /*noOutFile*/ false, - /*generateDeclarations*/ true); + { noOutFile: false, generateDeclarations: true }); // Local target to build the language service server library desc("Builds language service server library"); @@ -720,7 +726,7 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () { // Browser tests var nodeServerOutFile = 'tests/webTestServer.js' var nodeServerInFile = 'tests/webTestServer.ts' -compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, /*noOutFile*/ true); +compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true }); desc("Runs browserify on run.js to produce a file suitable for running tests in the browser"); task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() { @@ -729,7 +735,7 @@ task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() }, {async: true}); desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], port=, browser=[chrome|IE]"); -task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function() { +task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFileInBrowserTest], function() { cleanTestDirs(); host = "node" port = process.env.port || process.env.p || '8888'; @@ -881,7 +887,8 @@ var tslintRulesOutFiles = tslintRules.map(function(p) { desc("Compiles tslint rules to js"); task("build-rules", tslintRulesOutFiles); tslintRulesFiles.forEach(function(ruleFile, i) { - compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint")); + compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, + { noOutFile: true, generateDeclarations: false, outDir: path.join(builtLocalDirectory, "tslint")}); }); function getLinterOptions() { diff --git a/doc/README.md b/doc/README.md index 164fb69ee20..cfc97fedbe9 100644 --- a/doc/README.md +++ b/doc/README.md @@ -1,7 +1,9 @@ +# Read This! + This directory contains miscellaneous documentation such as the TypeScript language specification and logo. If you are looking for more introductory material, you might want to take a look at the [TypeScript Handbook](https://github.com/Microsoft/TypeScript-Handbook). # Spec Contributions The specification is first authored as a Microsoft Word (docx) file and then generated into Markdown and PDF formats. -Due to the binary format of docx files, and the merging difficulties that may come with it, it is preferred that any suggestions or problems found in the spec should be [filed as issues](https://github.com/Microsoft/TypeScript/issues/new) rather than sent as pull requests. \ No newline at end of file +Due to the binary format of docx files, and the merging difficulties that may come with it, it is preferred that **any suggestions or problems found in the spec should be [filed as issues](https://github.com/Microsoft/TypeScript/issues/new)** rather than sent as pull requests. diff --git a/doc/handbook/README.md b/doc/handbook/README.md new file mode 100644 index 00000000000..2d2e0e83a46 --- /dev/null +++ b/doc/handbook/README.md @@ -0,0 +1,4 @@ +# The TypeScript Handbook + +The contents of the TypeScript Handbook can be read from [its GitHub repository](https://github.com/Microsoft/TypeScript-Handbook). +Issues and pull requests should be directed there. \ No newline at end of file diff --git a/doc/wiki/README.md b/doc/wiki/README.md new file mode 100644 index 00000000000..19961197840 --- /dev/null +++ b/doc/wiki/README.md @@ -0,0 +1,6 @@ +# The TypeScript Wiki + +To read the wiki, [visit the wiki on GitHub](https://github.com/Microsoft/TypeScript/wiki). + +To contribute by filing an issue or sending a pull request, [visit the wiki repository](https://github.com/Microsoft/TypeScript-wiki). + diff --git a/lib/README.md b/lib/README.md index 583ddf91156..852d449f1e5 100644 --- a/lib/README.md +++ b/lib/README.md @@ -1,4 +1,5 @@ -# Read this! +# Read This! -These files are not meant to be edited by hand. -If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. Running `jake LKG` will then appropriately update the files in this directory. +**These files are not meant to be edited by hand.** +If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. +Running `jake LKG` will then appropriately update the files in this directory. diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 6c822845217..5e944c71126 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -12,7 +12,7 @@ namespace ts { } const enum Reachability { - Unintialized = 1 << 0, + Uninitialized = 1 << 0, Reachable = 1 << 1, Unreachable = 1 << 2, ReportedUnreachable = 1 << 3 @@ -393,7 +393,7 @@ namespace ts { // 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 children, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. const saveParent = parent; @@ -418,7 +418,7 @@ namespace ts { // Finally, if this is a block-container, then we clear out any existing .locals object // it may contain within it. This happens in incremental scenarios. Because we can be // reusing a node from a previous compilation, that node may have had 'locals' created - // for it. We must clear this so we don't accidently move any stale data forward from + // for it. We must clear this so we don't accidentally move any stale data forward from // a previous compilation. const containerFlags = getContainerFlags(node); if (containerFlags & ContainerFlags.IsContainer) { @@ -699,7 +699,7 @@ namespace ts { const hasDefault = forEach(n.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause); - // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case + // post switch state is unreachable if switch is exhaustive (has a default case ) and does not have fallthrough from the last case const postSwitchState = hasDefault && currentReachabilityState !== Reachability.Reachable ? Reachability.Unreachable : preSwitchState; popImplicitLabel(postSwitchLabel, postSwitchState); @@ -766,7 +766,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. Otherwise 'x' // would not appear to be a redeclaration of a block scoped local in the following // example: // @@ -956,7 +956,7 @@ namespace ts { const identifier = prop.name; - // ECMA-262 11.1.5 Object Initialiser + // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and // IsDataDescriptor(propId.descriptor) is true. @@ -1632,14 +1632,14 @@ namespace ts { if (hasProperty(labelIndexMap, name.text)) { return false; } - labelIndexMap[name.text] = labelStack.push(Reachability.Unintialized) - 1; + labelIndexMap[name.text] = labelStack.push(Reachability.Uninitialized) - 1; return true; } function pushImplicitLabel(): number { initializeReachabilityStateIfNecessary(); - const index = labelStack.push(Reachability.Unintialized) - 1; + const index = labelStack.push(Reachability.Uninitialized) - 1; implicitLabels.push(index); return index; } @@ -1669,7 +1669,7 @@ namespace ts { } function setCurrentStateAtLabel(innerMergedState: Reachability, outerState: Reachability, label: Identifier): void { - if (innerMergedState === Reachability.Unintialized) { + if (innerMergedState === Reachability.Uninitialized) { if (label && !options.allowUnusedLabels) { file.bindDiagnostics.push(createDiagnosticForNode(label, Diagnostics.Unused_label)); } @@ -1690,7 +1690,7 @@ namespace ts { return false; } const stateAtLabel = labelStack[index]; - labelStack[index] = stateAtLabel === Reachability.Unintialized ? outerState : or(stateAtLabel, outerState); + labelStack[index] = stateAtLabel === Reachability.Uninitialized ? outerState : or(stateAtLabel, outerState); return true; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b9343a2cdbe..d1b6dc5435e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -49,7 +49,7 @@ namespace ts { const compilerOptions = host.getCompilerOptions(); const languageVersion = compilerOptions.target || ScriptTarget.ES3; - const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const modulekind = getEmitModuleKind(compilerOptions); const allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ModuleKind.System; const emitResolver = createResolver(); @@ -131,8 +131,8 @@ namespace ts { const noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); - const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); @@ -467,10 +467,10 @@ namespace ts { * @return a tuple of two symbols */ function getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): [Symbol, Symbol] { - const constructoDeclaration = parameter.parent; + const constructorDeclaration = parameter.parent; const classDeclaration = parameter.parent.parent; - const parameterSymbol = getSymbol(constructoDeclaration.locals, parameterName, SymbolFlags.Value); + const parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, SymbolFlags.Value); const propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, SymbolFlags.Value); if (parameterSymbol && propertySymbol) { @@ -1460,7 +1460,7 @@ namespace ts { function isAccessible(symbolFromSymbolTable: Symbol, resolvedAliasSymbol?: Symbol) { if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolfrom symbolTable or alias resolution matches the symbol, + // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible return !forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); @@ -1531,7 +1531,7 @@ namespace ts { return qualify; } - function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult { + function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult { if (symbol && enclosingDeclaration && !(symbol.flags & SymbolFlags.TypeParameter)) { const initialSymbol = symbol; let meaningToLook = meaning; @@ -1541,7 +1541,7 @@ namespace ts { if (accessibleSymbolChain) { const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); if (!hasAccessibleDeclarations) { - return { + return { accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, SymbolFlags.Namespace) : undefined, @@ -1711,6 +1711,15 @@ namespace ts { return result; } + function typePredicateToString(typePredicate: TypePredicate, enclosingDeclaration?: Declaration, flags?: TypeFormatFlags): string { + const writer = getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + const result = writer.string(); + releaseStringWriter(writer); + + return result; + } + function getTypeAliasForTypeLiteral(type: Type): Symbol { if (type.symbol && type.symbol.flags & SymbolFlags.TypeLiteral) { let node = type.symbol.declarations[0].parent; @@ -1844,16 +1853,10 @@ namespace ts { function writeType(type: Type, flags: TypeFormatFlags) { // Write undefined/null type as any if (type.flags & TypeFlags.Intrinsic) { - if (type.flags & TypeFlags.PredicateType) { - buildTypePredicateDisplay(writer, (type as PredicateType).predicate); - buildTypeDisplay((type as PredicateType).predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - else { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike) && isTypeAny(type) - ? "any" - : (type).intrinsicName); - } + // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving + writer.writeKeyword(!(globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike) && isTypeAny(type) + ? "any" + : (type).intrinsicName); } else if (type.flags & TypeFlags.ThisType) { if (inObjectTypeLiteral) { @@ -2140,10 +2143,10 @@ namespace ts { } } - function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags) { + function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags) { const targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & SymbolFlags.Class || targetSymbol.flags & SymbolFlags.Interface || targetSymbol.flags & SymbolFlags.TypeAlias) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } @@ -2219,7 +2222,7 @@ namespace ts { writePunctuation(writer, SyntaxKind.CloseParenToken); } - function buildTypePredicateDisplay(writer: SymbolWriter, predicate: TypePredicate) { + function buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]): void { if (isIdentifierTypePredicate(predicate)) { writer.writeParameter(predicate.parameterName); } @@ -2229,6 +2232,7 @@ namespace ts { writeSpace(writer); writeKeyword(writer, SyntaxKind.IsKeyword); writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); } function buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { @@ -2241,8 +2245,13 @@ namespace ts { } writeSpace(writer); - const returnType = getReturnTypeOfSignature(signature); - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + if (signature.typePredicate) { + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + } + else { + const returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } } function buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind, symbolStack?: Symbol[]) { @@ -2261,6 +2270,7 @@ namespace ts { } buildDisplayForParametersAndDelimiters(signature.thisType, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } @@ -2268,6 +2278,7 @@ namespace ts { buildSymbolDisplay, buildTypeDisplay, buildTypeParameterDisplay, + buildTypePredicateDisplay, buildParameterDisplay, buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters, @@ -2619,7 +2630,7 @@ namespace ts { function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration: VariableLikeDeclaration): JSDocType { // First, see if this node has an @type annotation on it directly. const typeTag = getJSDocTypeTag(declaration); - if (typeTag) { + if (typeTag && typeTag.typeExpression) { return typeTag.typeExpression.type; } @@ -2629,7 +2640,7 @@ namespace ts { // @type annotation might have been on the variable statement, try that instead. const annotation = getJSDocTypeTag(declaration.parent.parent); - if (annotation) { + if (annotation && annotation.typeExpression) { return annotation.typeExpression.type; } } @@ -2808,9 +2819,6 @@ namespace ts { if (declaration.kind === SyntaxKind.PropertyAssignment) { return type; } - if (type.flags & TypeFlags.PredicateType && (declaration.kind === SyntaxKind.PropertyDeclaration || declaration.kind === SyntaxKind.PropertySignature)) { - return type; - } return getWidenedType(type); } @@ -3542,13 +3550,14 @@ namespace ts { } function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisType: Type, parameters: Symbol[], - resolvedReturnType: Type, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { + resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { const sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; sig.thisType = thisType; sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; sig.hasRestParameter = hasRestParameter; sig.hasStringLiterals = hasStringLiterals; @@ -3557,14 +3566,14 @@ namespace ts { function cloneSignature(sig: Signature): Signature { return createSignature(sig.declaration, sig.typeParameters, sig.thisType, sig.parameters, sig.resolvedReturnType, - sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } function getDefaultConstructSignatures(classType: InterfaceType): Signature[] { const baseConstructorType = getBaseConstructorTypeOfClass(classType); const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; } const baseTypeNode = getBaseTypeNodeOfClass(classType); const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); @@ -4098,6 +4107,7 @@ namespace ts { let hasThisParameter: boolean; const isJSConstructSignature = isJSDocConstructSignature(declaration); let returnType: Type = undefined; + let typePredicate: TypePredicate = undefined; // If this is a JSDoc construct signature, then skip the first parameter in the // parameter list. The first parameter represents the return type of the construct @@ -4162,6 +4172,9 @@ namespace ts { } else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === SyntaxKind.TypePredicate) { + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode); + } } else { if (declaration.flags & NodeFlags.JavaScriptFile) { @@ -4183,7 +4196,7 @@ namespace ts { } } - links.resolvedSignature = createSignature(declaration, typeParameters, thisType, parameters, returnType, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisType, parameters, returnType, typePredicate, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -4895,25 +4908,6 @@ namespace ts { return links.resolvedType; } - function getPredicateType(node: TypePredicateNode): Type { - return createPredicateType(getSymbolOfNode(node), createTypePredicateFromTypePredicateNode(node)); - } - - function createPredicateType(symbol: Symbol, predicate: ThisTypePredicate | IdentifierTypePredicate) { - const type = createType(TypeFlags.Boolean | TypeFlags.PredicateType) as PredicateType; - type.symbol = symbol; - type.predicate = predicate; - return type; - } - - function getTypeFromPredicateTypeNode(node: TypePredicateNode): Type { - const links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getPredicateType(node); - } - return links.resolvedType; - } - function getTypeFromTypeNode(node: TypeNode): Type { switch (node.kind) { case SyntaxKind.AnyKeyword: @@ -4938,7 +4932,7 @@ namespace ts { case SyntaxKind.JSDocTypeReference: return getTypeFromTypeReference(node); case SyntaxKind.TypePredicate: - return getTypeFromPredicateTypeNode(node); + return booleanType; case SyntaxKind.ExpressionWithTypeArguments: return getTypeFromTypeReference(node); case SyntaxKind.TypeQuery: @@ -5090,6 +5084,7 @@ namespace ts { function instantiateSignature(signature: Signature, mapper: TypeMapper, eraseTypeParameters?: boolean): Signature { let freshTypeParameters: TypeParameter[]; + let freshTypePredicate: TypePredicate; if (signature.typeParameters && !eraseTypeParameters) { // First create a fresh set of type parameters, then include a mapping from the old to the // new type parameters in the mapper function. Finally store this mapper in the new type @@ -5100,10 +5095,14 @@ namespace ts { tp.mapper = mapper; } } + if (signature.typePredicate) { + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); + } const result = createSignature(signature.declaration, freshTypeParameters, signature.thisType && instantiateType(signature.thisType, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), + freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); result.target = signature; result.mapper = mapper; @@ -5173,10 +5172,6 @@ namespace ts { if (type.flags & TypeFlags.Intersection) { return getIntersectionType(instantiateList((type).types, mapper, instantiateType)); } - if (type.flags & TypeFlags.PredicateType) { - const predicate = (type as PredicateType).predicate; - return createPredicateType(type.symbol, cloneTypePredicate(predicate, mapper)); - } } return type; } @@ -5343,21 +5338,58 @@ namespace ts { const sourceReturnType = getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (targetReturnType.flags & TypeFlags.PredicateType && (targetReturnType as PredicateType).predicate.kind === TypePredicateKind.Identifier) { - if (!(sourceReturnType.flags & TypeFlags.PredicateType)) { + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (isIdentifierTypePredicate(target.typePredicate)) { if (reportErrors) { errorReporter(Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); } return Ternary.False; } } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } - result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); } return result; } + function compareTypePredicateRelatedTo(source: TypePredicate, + target: TypePredicate, + reportErrors: boolean, + errorReporter: (d: DiagnosticMessage, arg0?: string, arg1?: string) => void, + compareTypes: (s: Type, t: Type, reportErrors?: boolean) => Ternary): Ternary { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return Ternary.False; + } + + if (source.kind === TypePredicateKind.Identifier) { + const sourceIdentifierPredicate = source as IdentifierTypePredicate; + const targetIdentifierPredicate = target as IdentifierTypePredicate; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return Ternary.False; + } + } + + const related = compareTypes(source.type, target.type, reportErrors); + if (related === Ternary.False && reportErrors) { + errorReporter(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation: Signature, overload: Signature): boolean { const erasedSource = getErasedSignature(implementation); const erasedTarget = getErasedSignature(overload); @@ -5484,33 +5516,6 @@ namespace ts { if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True; } if (source.flags & TypeFlags.Boolean && target.flags & TypeFlags.Boolean) { - if (source.flags & TypeFlags.PredicateType && target.flags & TypeFlags.PredicateType) { - const sourcePredicate = source as PredicateType; - const targetPredicate = target as PredicateType; - if (sourcePredicate.predicate.kind !== targetPredicate.predicate.kind) { - if (reportErrors) { - reportError(Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); - reportError(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); - } - return Ternary.False; - } - if (sourcePredicate.predicate.kind === TypePredicateKind.Identifier) { - const sourceIdentifierPredicate = sourcePredicate.predicate as IdentifierTypePredicate; - const targetIdentifierPredicate = targetPredicate.predicate as IdentifierTypePredicate; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { - if (reportErrors) { - reportError(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); - reportError(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); - } - return Ternary.False; - } - } - const related = isRelatedTo(sourcePredicate.predicate.type, targetPredicate.predicate.type, reportErrors, headMessage); - if (related === Ternary.False && reportErrors) { - reportError(Diagnostics.Type_predicate_0_is_not_assignable_to_1, typeToString(source), typeToString(target)); - } - return related; - } return Ternary.True; } @@ -5646,7 +5651,7 @@ namespace ts { } function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { - if (!(target.flags & TypeFlags.ObjectLiteralPatternWithComputedProperties) && someConstituentTypeHasKind(target, TypeFlags.ObjectType)) { + if (!(target.flags & TypeFlags.ObjectLiteralPatternWithComputedProperties) && maybeTypeOfKind(target, TypeFlags.ObjectType)) { for (const prop of getPropertiesOfObjectType(source)) { if (!isKnownProperty(target, prop.name)) { if (reportErrors) { @@ -5947,7 +5952,7 @@ namespace ts { if (kind === SignatureKind.Construct && sourceSignatures.length && targetSignatures.length && isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { // An abstract constructor type is not assignable to a non-abstract constructor type - // as it would otherwise be possible to new an abstract class. Note that the assignablity + // as it would otherwise be possible to new an abstract class. Note that the assignability // check we perform for an extends clause excludes construct signatures from the target, // so this check never proceeds. if (reportErrors) { @@ -6366,9 +6371,6 @@ namespace ts { if (type.flags & (TypeFlags.Undefined | TypeFlags.Null)) { return anyType; } - if (type.flags & TypeFlags.PredicateType) { - return booleanType; - } if (type.flags & TypeFlags.ObjectLiteral) { return getWidenedTypeOfObjectLiteral(type); } @@ -6590,11 +6592,6 @@ namespace ts { inferFromTypes(sourceTypes[i], targetTypes[i]); } } - else if (source.flags & TypeFlags.PredicateType && target.flags & TypeFlags.PredicateType) { - if ((source as PredicateType).predicate.kind === (target as PredicateType).predicate.kind) { - inferFromTypes((source as PredicateType).predicate.type, (target as PredicateType).predicate.type); - } - } else if (source.flags & TypeFlags.Tuple && target.flags & TypeFlags.Tuple && (source).elementTypes.length === (target).elementTypes.length) { // If source and target are tuples of the same size, infer from element types const sourceTypes = (source).elementTypes; @@ -6628,7 +6625,7 @@ namespace ts { } } else if (source.flags & TypeFlags.UnionOrIntersection) { - // Source is a union or intersection type, infer from each consituent type + // Source is a union or intersection type, infer from each constituent type const sourceTypes = (source).types; for (const sourceType of sourceTypes) { inferFromTypes(sourceType, target); @@ -6690,7 +6687,13 @@ namespace ts { function inferFromSignature(source: Signature, target: Signature) { forEachMatchingParameterType(source, target, inferFromTypes); - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } } function inferFromIndexTypes(source: Type, target: Type, sourceKind: IndexKind, targetKind: IndexKind) { @@ -7116,46 +7119,33 @@ namespace ts { return originalType; } - function narrowTypeByTypePredicate(type: Type, expr: CallExpression, assumeTrue: boolean): Type { + function narrowTypeByTypePredicate(type: Type, callExpression: CallExpression, assumeTrue: boolean): Type { if (type.flags & TypeFlags.Any) { return type; } - const signature = getResolvedSignature(expr); - const predicateType = getReturnTypeOfSignature(signature); + const signature = getResolvedSignature(callExpression); - if (!predicateType || !(predicateType.flags & TypeFlags.PredicateType)) { + const predicate = signature.typePredicate; + if (!predicate) { return type; } - const predicate = (predicateType as PredicateType).predicate; + if (isIdentifierTypePredicate(predicate)) { - const callExpression = expr as CallExpression; if (callExpression.arguments[predicate.parameterIndex] && getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { return getNarrowedType(type, predicate.type, assumeTrue); } } else { - const expression = skipParenthesizedNodes(expr.expression); - return narrowTypeByThisTypePredicate(type, predicate, expression, assumeTrue); + const invokedExpression = skipParenthesizedNodes(callExpression.expression); + return narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue); } return type; } - function narrowTypeByTypePredicateMember(type: Type, expr: ElementAccessExpression | PropertyAccessExpression, assumeTrue: boolean): Type { - if (type.flags & TypeFlags.Any) { - return type; - } - const memberType = getTypeOfExpression(expr); - if (!(memberType.flags & TypeFlags.PredicateType)) { - return type; - } - - return narrowTypeByThisTypePredicate(type, (memberType as PredicateType).predicate as ThisTypePredicate, expr, assumeTrue); - } - - function narrowTypeByThisTypePredicate(type: Type, predicate: ThisTypePredicate, expression: Expression, assumeTrue: boolean): Type { - if (expression.kind === SyntaxKind.ElementAccessExpression || expression.kind === SyntaxKind.PropertyAccessExpression) { - const accessExpression = expression as ElementAccessExpression | PropertyAccessExpression; + function narrowTypeByThisTypePredicate(type: Type, predicate: ThisTypePredicate, invokedExpression: Expression, assumeTrue: boolean): Type { + if (invokedExpression.kind === SyntaxKind.ElementAccessExpression || invokedExpression.kind === SyntaxKind.PropertyAccessExpression) { + const accessExpression = invokedExpression as ElementAccessExpression | PropertyAccessExpression; const possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); if (possibleIdentifier.kind === SyntaxKind.Identifier && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { return getNarrowedType(type, predicate.type, assumeTrue); @@ -7169,8 +7159,7 @@ namespace ts { switch (expr.kind) { case SyntaxKind.Identifier: case SyntaxKind.PropertyAccessExpression: - case SyntaxKind.QualifiedName: - return getSymbolOfEntityNameOrPropertyAccessExpression(expr as Node as (EntityName | PropertyAccessExpression)); + return getSymbolOfEntityNameOrPropertyAccessExpression(expr as (Identifier | PropertyAccessExpression)); } } @@ -7202,9 +7191,6 @@ namespace ts { return narrowType(type, (expr).operand, !assumeTrue); } break; - case SyntaxKind.ElementAccessExpression: - case SyntaxKind.PropertyAccessExpression: - return narrowTypeByTypePredicateMember(type, expr as (ElementAccessExpression | PropertyAccessExpression), assumeTrue); } return type; } @@ -7313,6 +7299,15 @@ namespace ts { // mark iteration statement as containing block-scoped binding captured in some function getNodeLinks(current).flags |= NodeCheckFlags.LoopWithCapturedBlockScopedBinding; } + + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === SyntaxKind.ForStatement && + getAncestor(symbol.valueDeclaration, SyntaxKind.VariableDeclarationList).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.NeedsLoopOutParameter; + } + // set 'declared inside loop' bit on the block-scoped binding getNodeLinks(symbol.valueDeclaration).flags |= NodeCheckFlags.BlockScopedBindingInLoop; } @@ -7322,6 +7317,41 @@ namespace ts { } } + function isAssignedInBodyOfForStatement(node: Identifier, container: ForStatement): boolean { + let current: Node = node; + // skip parenthesized nodes + while (current.parent.kind === SyntaxKind.ParenthesizedExpression) { + current = current.parent; + } + + // check if node is used as LHS in some assignment expression + let isAssigned = false; + if (current.parent.kind === SyntaxKind.BinaryExpression) { + isAssigned = (current.parent).left === current && isAssignmentOperator((current.parent).operatorToken.kind); + } + + if ((current.parent.kind === SyntaxKind.PrefixUnaryExpression || current.parent.kind === SyntaxKind.PostfixUnaryExpression)) { + const expr = current.parent; + isAssigned = expr.operator === SyntaxKind.PlusPlusToken || expr.operator === SyntaxKind.MinusMinusToken; + } + + if (!isAssigned) { + return false; + } + + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; + } + function captureLexicalThis(node: Node, container: Node): void { getNodeLinks(node).flags |= NodeCheckFlags.LexicalThis; if (container.kind === SyntaxKind.PropertyDeclaration || container.kind === SyntaxKind.Constructor) { @@ -7333,6 +7363,46 @@ namespace ts { } } + function findFirstSuperCall(n: Node): Node { + if (isSuperCallExpression(n)) { + return n; + } + else if (isFunctionLike(n)) { + return undefined; + } + return forEachChild(n, findFirstSuperCall); + } + + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor: ConstructorDeclaration): ExpressionStatement { + const links = getNodeLinks(constructor); + + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl: ClassDeclaration): boolean { + const classSymbol = getSymbolOfNode(classDecl); + const classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + const baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + + return baseConstructorType === nullType; + } + function checkThisExpression(node: Node): Type { // Stop at the first arrow function so that we can // tell whether 'this' needs to be captured. @@ -7340,10 +7410,25 @@ namespace ts { let needToCaptureLexicalThis = false; if (container.kind === SyntaxKind.Constructor) { - const baseTypeNode = getClassExtendsHeritageClauseElement(container.parent); - if (baseTypeNode && !(getNodeCheckFlags(container) & NodeCheckFlags.HasSeenSuperCall)) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + const containingClassDecl = container.parent; + const baseTypeNode = getClassExtendsHeritageClauseElement(containingClassDecl); + + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + const superCall = getSuperCallInConstructor(container); + + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } } } @@ -7428,7 +7513,7 @@ namespace ts { function getTypeForThisExpressionFromJSDoc(node: Node) { const typeTag = getJSDocTypeTag(node); - if (typeTag && typeTag.typeExpression.type.kind === SyntaxKind.JSDocFunctionType) { + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === SyntaxKind.JSDocFunctionType) { const jsDocFunctionType = typeTag.typeExpression.type; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === SyntaxKind.JSDocThisType) { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); @@ -7947,7 +8032,7 @@ namespace ts { * Otherwise this may not be very useful. * * In cases where you *are* working on this function, you should understand - * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContetxualType'. + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. * * - Use 'getContextualType' when you are simply going to propagate the result to the expression. * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. @@ -8205,7 +8290,7 @@ namespace ts { } function isTypeAnyOrAllConstituentTypesHaveKind(type: Type, kind: TypeFlags): boolean { - return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + return isTypeAny(type) || isTypeOfKind(type, kind); } function isNumericLiteralName(name: string) { @@ -8392,7 +8477,7 @@ namespace ts { checkJsxOpeningLikeElement(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work - getJsxElementTagSymbol(node.closingElement); + getJsxTagSymbol(node.closingElement); // Check children for (const child of node.children) { @@ -8502,77 +8587,52 @@ namespace ts { return jsxTypes[name]; } - /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if - /// this is an intrinsic tag. This might be a named - /// property of the IntrinsicElements interface, or its string indexer. - /// If this is a class-based tag (otherwise returns undefined), returns the symbol of the class - /// type or factory function. - /// Otherwise, returns unknownSymbol. - function getJsxElementTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { + function getJsxTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicTagSymbol(node); + } + else { + return checkExpression(node.tagName).symbol; + } + } + + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - links.resolvedSymbol = lookupIntrinsicTag(node); - } - else { - links.resolvedSymbol = lookupClassTag(node); - } - } - return links.resolvedSymbol; - - function lookupIntrinsicTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case const intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); if (intrinsicProp) { links.jsxFlags |= JsxFlags.IntrinsicNamedElement; - return intrinsicProp; + return links.resolvedSymbol = intrinsicProp; } // Intrinsic string indexer case const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); if (indexSignatureType) { links.jsxFlags |= JsxFlags.IntrinsicIndexedElement; - return intrinsicElementsType.symbol; + return links.resolvedSymbol = intrinsicElementsType.symbol; } // Wasn't found error(node, Diagnostics.Property_0_does_not_exist_on_type_1, (node.tagName).text, "JSX." + JsxNames.IntrinsicElements); - return unknownSymbol; + return links.resolvedSymbol = unknownSymbol; } else { if (compilerOptions.noImplicitAny) { error(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } - return unknownSymbol; - } - } - - function lookupClassTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - const valueSymbol: Symbol = resolveJsxTagName(node); - - // Look up the value in the current scope - if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= JsxFlags.ValueElement; - if (valueSymbol.flags & SymbolFlags.Alias) { - markAliasSymbolAsReferenced(valueSymbol); - } - } - - return valueSymbol || unknownSymbol; - } - - function resolveJsxTagName(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - if (node.tagName.kind === SyntaxKind.Identifier) { - const tag = node.tagName; - const sym = getResolvedSymbol(tag); - return sym.exportSymbol || sym; - } - else { - return checkQualifiedName(node.tagName).symbol; + return links.resolvedSymbol = unknownSymbol; } } + return links.resolvedSymbol; } /** @@ -8581,17 +8641,8 @@ namespace ts { * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node: JsxOpeningLikeElement) { - // There is no such thing as an instance type for a non-class element. This - // line shouldn't be hit. - Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ValueElement), "Should not call getJsxElementInstanceType on non-class Element"); + const valueType = checkExpression(node.tagName); - const classSymbol = getJsxElementTagSymbol(node); - if (classSymbol === unknownSymbol) { - // Couldn't find the class instance type. Error has already been issued - return anyType; - } - - const valueType = getTypeOfSymbol(classSymbol); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -8614,10 +8665,10 @@ namespace ts { } /// e.g. "props" for React.d.ts, - /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), /// or '' if it has 0 properties (which means every - /// non-instrinsic elements' attributes type is the element instance type) + /// non-intrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX const jsxNamespace = getGlobalSymbol(JsxNames.JSX, SymbolFlags.Namespace, /*diagnosticMessage*/undefined); @@ -8625,7 +8676,7 @@ namespace ts { const attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, SymbolFlags.Type); // JSX.ElementAttributesProperty [type] const attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); - // The properites of JSX.ElementAttributesProperty + // The properties of JSX.ElementAttributesProperty const attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { @@ -8657,9 +8708,16 @@ namespace ts { function getJsxElementAttributesType(node: JsxOpeningLikeElement): Type { const links = getNodeLinks(node); if (!links.resolvedJsxType) { - const sym = getJsxElementTagSymbol(node); - - if (links.jsxFlags & JsxFlags.ValueElement) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + const symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & JsxFlags.IntrinsicNamedElement) { + return links.resolvedJsxType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) { + return links.resolvedJsxType = getIndexInfoOfSymbol(symbol, IndexKind.String).type; + } + } + else { // Get the element instance type (the result of newing or invoking this tag) const elemInstanceType = getJsxElementInstanceType(node); @@ -8668,7 +8726,7 @@ namespace ts { if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { // Is this is a stateless function component? See if its single signature's return type is // assignable to the JSX Element Type - const elemType = getTypeOfSymbol(sym); + const elemType = checkExpression(node.tagName); const callSignatures = elemType && getSignaturesOfType(elemType, SignatureKind.Call); const callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); @@ -8742,16 +8800,8 @@ namespace ts { } } } - else if (links.jsxFlags & JsxFlags.IntrinsicNamedElement) { - return links.resolvedJsxType = getTypeOfSymbol(sym); - } - else if (links.jsxFlags & JsxFlags.IntrinsicIndexedElement) { - return links.resolvedJsxType = getIndexInfoOfSymbol(sym, IndexKind.String).type; - } - else { - // Resolution failed, so we don't know - return links.resolvedJsxType = anyType; - } + + return links.resolvedJsxType = unknownType; } return links.resolvedJsxType; @@ -9743,7 +9793,7 @@ namespace ts { case SyntaxKind.ComputedPropertyName: const nameType = checkComputedPropertyName(element.name); - if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { + if (isTypeOfKind(nameType, TypeFlags.ESSymbol)) { return nameType; } else { @@ -9769,7 +9819,7 @@ namespace ts { */ function getEffectiveDecoratorThirdArgumentType(node: Node) { // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a paramter decorator + // or its `parameterIndex` for a parameter decorator if (node.kind === SyntaxKind.ClassDeclaration) { Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; @@ -10137,7 +10187,7 @@ namespace ts { // We exclude union types because we may have a union of function types that happen to have // no common signatures. if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & TypeFlags.Union) && isTypeAssignableTo(funcType, globalFunctionType))) { - // The unknownType indicates that an error already occured (and was reported). No + // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== unknownType && node.typeArguments) { error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); @@ -10349,14 +10399,11 @@ namespace ts { checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); const signature = getResolvedSignature(node); - if (node.expression.kind === SyntaxKind.SuperKeyword) { - const containgFunction = getContainingFunction(node.expression); - if (containgFunction && containgFunction.kind === SyntaxKind.Constructor) { - getNodeLinks(containgFunction).flags |= NodeCheckFlags.HasSeenSuperCall; - } + if (node.expression.kind === SyntaxKind.SuperKeyword) { return voidType; } + if (node.kind === SyntaxKind.NewExpression) { const declaration = signature.declaration; @@ -10399,9 +10446,8 @@ namespace ts { const widenedType = getWidenedType(exprType); // Permit 'number[] | "foo"' to be asserted to 'string'. - const bothAreStringLike = - someConstituentTypeHasKind(targetType, TypeFlags.StringLike) && - someConstituentTypeHasKind(widenedType, TypeFlags.StringLike); + const bothAreStringLike = maybeTypeOfKind(targetType, TypeFlags.StringLike) && + maybeTypeOfKind(widenedType, TypeFlags.StringLike); if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } @@ -10642,12 +10688,13 @@ namespace ts { return aggregatedTypes; } - /* - *TypeScript Specification 1.0 (6.3) - July 2014 - * An explicitly typed function whose return type isn't the Void type, - * the Any type, or a union type containing the Void or Any type as a constituent - * must have at least one return statement somewhere in its body. - * An exception to this rule is if the function implementation consists of a single 'throw' statement. + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * * @param returnType - return type of the function, can be undefined if return type is not explicitly specified */ function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration, returnType: Type): void { @@ -10656,7 +10703,7 @@ namespace ts { } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType === voidType || isTypeAny(returnType) || (returnType && (returnType.flags & TypeFlags.Union) && someConstituentTypeHasKind(returnType, TypeFlags.Any | TypeFlags.Void))) { + if (returnType && maybeTypeOfKind(returnType, TypeFlags.Any | TypeFlags.Void)) { return; } @@ -10912,7 +10959,7 @@ namespace ts { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.TildeToken: - if (someConstituentTypeHasKind(operandType, TypeFlags.ESSymbol)) { + if (maybeTypeOfKind(operandType, TypeFlags.ESSymbol)) { error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); } return numberType; @@ -10944,38 +10991,47 @@ namespace ts { return numberType; } - // Just like isTypeOfKind below, except that it returns true if *any* constituent - // has this kind. - function someConstituentTypeHasKind(type: Type, kind: TypeFlags): boolean { + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type: Type, kind: TypeFlags): boolean { if (type.flags & kind) { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { const types = (type).types; - for (const current of types) { - if (current.flags & kind) { + for (const t of types) { + if (maybeTypeOfKind(t, kind)) { return true; } } - return false; } return false; } - // Return true if type has the given flags, or is a union or intersection type composed of types that all have those flags. - function allConstituentTypesHaveKind(type: Type, kind: TypeFlags): boolean { + // Return true if type is of the given kind. A union type is of a given kind if all constituent types + // are of the given kind. An intersection type is of a given kind if at least one constituent type is + // of the given kind. + function isTypeOfKind(type: Type, kind: TypeFlags): boolean { if (type.flags & kind) { return true; } - if (type.flags & TypeFlags.UnionOrIntersection) { + if (type.flags & TypeFlags.Union) { const types = (type).types; - for (const current of types) { - if (!(current.flags & kind)) { + for (const t of types) { + if (!isTypeOfKind(t, kind)) { return false; } } return true; } + if (type.flags & TypeFlags.Intersection) { + const types = (type).types; + for (const t of types) { + if (isTypeOfKind(t, kind)) { + return true; + } + } + } return false; } @@ -10993,7 +11049,7 @@ namespace ts { // and the right operand to be of type Any or a subtype of the 'Function' interface type. // The result is always of the Boolean primitive type. // NOTE: do not raise error if leftType is unknown as related error was already reported - if (allConstituentTypesHaveKind(leftType, TypeFlags.Primitive)) { + if (isTypeOfKind(leftType, TypeFlags.Primitive)) { error(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } // NOTE: do not raise error if right is unknown as related error was already reported @@ -11208,13 +11264,13 @@ namespace ts { if (rightType.flags & (TypeFlags.Undefined | TypeFlags.Null)) rightType = leftType; let resultType: Type; - if (allConstituentTypesHaveKind(leftType, TypeFlags.NumberLike) && allConstituentTypesHaveKind(rightType, TypeFlags.NumberLike)) { + if (isTypeOfKind(leftType, TypeFlags.NumberLike) && isTypeOfKind(rightType, TypeFlags.NumberLike)) { // Operands of an enum type are treated as having the primitive type Number. // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } else { - if (allConstituentTypesHaveKind(leftType, TypeFlags.StringLike) || allConstituentTypesHaveKind(rightType, TypeFlags.StringLike)) { + if (isTypeOfKind(leftType, TypeFlags.StringLike) || isTypeOfKind(rightType, TypeFlags.StringLike)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; } @@ -11252,7 +11308,7 @@ namespace ts { case SyntaxKind.EqualsEqualsEqualsToken: case SyntaxKind.ExclamationEqualsEqualsToken: // Permit 'number[] | "foo"' to be asserted to 'string'. - if (someConstituentTypeHasKind(leftType, TypeFlags.StringLike) && someConstituentTypeHasKind(rightType, TypeFlags.StringLike)) { + if (maybeTypeOfKind(leftType, TypeFlags.StringLike) && maybeTypeOfKind(rightType, TypeFlags.StringLike)) { return booleanType; } if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { @@ -11277,8 +11333,8 @@ namespace ts { // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { const offendingSymbolOperand = - someConstituentTypeHasKind(leftType, TypeFlags.ESSymbol) ? left : - someConstituentTypeHasKind(rightType, TypeFlags.ESSymbol) ? right : + maybeTypeOfKind(leftType, TypeFlags.ESSymbol) ? left : + maybeTypeOfKind(rightType, TypeFlags.ESSymbol) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator)); @@ -11671,21 +11727,24 @@ namespace ts { return -1; } - function checkTypePredicate(node: TypePredicateNode) { + function checkTypePredicate(node: TypePredicateNode): void { const parent = getTypePredicateParent(node); if (!parent) { + // The parent must not be valid. + error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - const returnType = getReturnTypeOfSignature(getSignatureFromDeclaration(parent)); - if (!returnType || !(returnType.flags & TypeFlags.PredicateType)) { + + const typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { return; } + const { parameterName } = node; - if (parameterName.kind === SyntaxKind.ThisType) { + if (isThisTypePredicate(typePredicate)) { getTypeFromThisTypeNode(parameterName as ThisTypeNode); } else { - const typePredicate = (returnType).predicate; if (typePredicate.parameterIndex >= 0) { if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { error(parameterName, @@ -11700,12 +11759,8 @@ namespace ts { else if (parameterName) { let hasReportedError = false; for (const { name } of parent.parameters) { - if ((name.kind === SyntaxKind.ObjectBindingPattern || - name.kind === SyntaxKind.ArrayBindingPattern) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern( - name, - parameterName, - typePredicate.parameterName)) { + if (isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -11773,8 +11828,9 @@ namespace ts { forEach(node.parameters, checkParameter); - checkSourceElement(node.type); - + if (node.type) { + checkSourceElement(node.type); + } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); @@ -11882,7 +11938,7 @@ namespace ts { function checkConstructorDeclaration(node: ConstructorDeclaration) { // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. checkSignatureDeclaration(node); - // Grammar check for checking only related to constructoDeclaration + // Grammar check for checking only related to constructorDeclaration checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); @@ -11904,10 +11960,6 @@ namespace ts { return; } - function isSuperCallExpression(n: Node): boolean { - return n.kind === SyntaxKind.CallExpression && (n).expression.kind === SyntaxKind.SuperKeyword; - } - function containsSuperCallAsComputedPropertyName(n: Declaration): boolean { return n.name && containsSuperCall(n.name); } @@ -11945,13 +11997,11 @@ namespace ts { // constructors of derived classes must contain at least one super call somewhere in their function body. const containingClassDecl = node.parent; if (getClassExtendsHeritageClauseElement(containingClassDecl)) { - const containingClassSymbol = getSymbolOfNode(containingClassDecl); - const containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - const baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); - - if (containsSuperCall(node.body)) { - if (baseConstructorType === nullType) { - error(node, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + const classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + const superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } // The first statement in the body of a constructor (excluding prologue directives) must be a super call @@ -11968,6 +12018,7 @@ namespace ts { if (superCallShouldBeFirst) { const statements = (node.body).statements; let superCallStatement: ExpressionStatement; + for (const statement of statements) { if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((statement).expression)) { superCallStatement = statement; @@ -11982,7 +12033,7 @@ namespace ts { } } } - else if (baseConstructorType !== nullType) { + else if (!classExtendsNull) { error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -12398,7 +12449,7 @@ namespace ts { } } - // Spaces for anyting not declared a 'default export'. + // Spaces for anything not declared a 'default export'. const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; @@ -12409,7 +12460,7 @@ namespace ts { for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); - // Only error on the declarations that conributed to the intersecting spaces. + // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name)); } @@ -12841,7 +12892,7 @@ namespace ts { } if (!compilerOptions.experimentalDecorators) { - error(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning); + error(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); } if (compilerOptions.emitDecoratorMetadata) { @@ -13625,7 +13676,7 @@ namespace ts { * This function does the following steps: * 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents. * 2. Take the element types of the array constituents. - * 3. Return the union of the element types, and string if there was a string constitutent. + * 3. Return the union of the element types, and string if there was a string constituent. * * For example: * string -> string @@ -13699,7 +13750,7 @@ namespace ts { // TODO: Check that target label is valid } - function isGetAccessorWithAnnotatatedSetAccessor(node: FunctionLikeDeclaration) { + function isGetAccessorWithAnnotatedSetAccessor(node: FunctionLikeDeclaration) { return !!(node.kind === SyntaxKind.GetAccessor && getSetAccessorTypeAnnotationNode(getDeclarationOfKind(node.symbol, SyntaxKind.SetAccessor))); } @@ -13735,7 +13786,7 @@ namespace ts { error(node.expression, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || returnType.flags & TypeFlags.PredicateType) { + else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { if (isAsyncFunctionLike(func)) { const promisedType = getPromisedType(returnType); const awaitedType = checkAwaitedType(exprType, node.expression, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); @@ -13774,7 +13825,7 @@ namespace ts { let hasDuplicateDefaultClause = false; const expressionType = checkExpression(node.expression); - const expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, TypeFlags.StringLike); + const expressionTypeIsStringLike = maybeTypeOfKind(expressionType, TypeFlags.StringLike); forEach(node.caseBlock.clauses, clause => { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause if (clause.kind === SyntaxKind.DefaultClause && !hasDuplicateDefaultClause) { @@ -13798,7 +13849,7 @@ namespace ts { const expressionTypeIsAssignableToCaseType = // Permit 'number[] | "foo"' to be asserted to 'string'. - (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, TypeFlags.StringLike)) || + (expressionTypeIsStringLike && maybeTypeOfKind(caseType, TypeFlags.StringLike)) || isTypeAssignableTo(expressionType, caseType); if (!expressionTypeIsAssignableToCaseType) { @@ -14138,7 +14189,7 @@ namespace ts { Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { - // In order to resolve whether the inherited method was overriden in the base class or not, + // In order to resolve whether the inherited method was overridden 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) { @@ -15040,7 +15091,7 @@ namespace ts { const kind = node.kind; if (cancellationToken) { - // Only bother checking on a few construct kinds. We don't want to be excessivly + // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { case SyntaxKind.ModuleDeclaration: @@ -15497,7 +15548,8 @@ namespace ts { else if ((entityName.parent.kind === SyntaxKind.JsxOpeningElement) || (entityName.parent.kind === SyntaxKind.JsxSelfClosingElement) || (entityName.parent.kind === SyntaxKind.JsxClosingElement)) { - return getJsxElementTagSymbol(entityName.parent); + + return getJsxTagSymbol(entityName.parent); } else if (isExpression(entityName)) { if (nodeIsMissing(entityName)) { @@ -15821,13 +15873,13 @@ namespace ts { function isSymbolOfDeclarationWithCollidingName(symbol: Symbol): boolean { if (symbol.flags & SymbolFlags.BlockScoped) { const links = getSymbolLinks(symbol); - if (links.isDeclaratonWithCollidingName === undefined) { + if (links.isDeclarationWithCollidingName === undefined) { const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (isStatementWithLocals(container)) { const nodeLinks = getNodeLinks(symbol.valueDeclaration); if (!!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { // redeclaration - always should be renamed - links.isDeclaratonWithCollidingName = true; + links.isDeclarationWithCollidingName = true; } else if (nodeLinks.flags & NodeCheckFlags.CapturedBlockScopedBinding) { // binding is captured in the function @@ -15842,21 +15894,21 @@ namespace ts { // console.log(b()); // should print '100' // OR // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body - // * variables from initializer are passed to rewritted loop body as parameters so they are not captured directly + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything const isDeclaredInLoop = nodeLinks.flags & NodeCheckFlags.BlockScopedBindingInLoop; const inLoopInitializer = isIterationStatement(container, /*lookInLabeledStatements*/ false); const inLoopBodyBlock = container.kind === SyntaxKind.Block && isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); - links.isDeclaratonWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { - links.isDeclaratonWithCollidingName = false; + links.isDeclarationWithCollidingName = false; } } } - return links.isDeclaratonWithCollidingName; + return links.isDeclarationWithCollidingName; } return false; } @@ -15907,7 +15959,7 @@ namespace ts { if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } - // const enums and modules that contain only const enums are not considered values from the emit perespective + // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true return target !== unknownSymbol && target && @@ -16004,22 +16056,22 @@ namespace ts { else if (type.flags & TypeFlags.Any) { return TypeReferenceSerializationKind.ObjectType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.Void)) { + else if (isTypeOfKind(type, TypeFlags.Void)) { return TypeReferenceSerializationKind.VoidType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.Boolean)) { + else if (isTypeOfKind(type, TypeFlags.Boolean)) { return TypeReferenceSerializationKind.BooleanType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.NumberLike)) { + else if (isTypeOfKind(type, TypeFlags.NumberLike)) { return TypeReferenceSerializationKind.NumberLikeType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.StringLike)) { + else if (isTypeOfKind(type, TypeFlags.StringLike)) { return TypeReferenceSerializationKind.StringLikeType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.Tuple)) { + else if (isTypeOfKind(type, TypeFlags.Tuple)) { return TypeReferenceSerializationKind.ArrayLikeType; } - else if (allConstituentTypesHaveKind(type, TypeFlags.ESSymbol)) { + else if (isTypeOfKind(type, TypeFlags.ESSymbol)) { return TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -16328,7 +16380,7 @@ namespace ts { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { - return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & NodeFlags.Abstract) { if (modifier.kind === SyntaxKind.PrivateKeyword) { @@ -16352,7 +16404,7 @@ namespace ts { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { - return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } else if (node.kind === SyntaxKind.Parameter) { return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); @@ -16767,8 +16819,8 @@ namespace ts { const seen: Map = {}; const Property = 1; const GetAccessor = 2; - const SetAccesor = 4; - const GetOrSetAccessor = GetAccessor | SetAccesor; + const SetAccessor = 4; + const GetOrSetAccessor = GetAccessor | SetAccessor; for (const prop of node.properties) { const name = prop.name; @@ -16792,7 +16844,7 @@ namespace ts { } }); - // ECMA-262 11.1.5 Object Initialiser + // ECMA-262 11.1.5 Object Initializer // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true // a.This production is contained in strict code and IsDataDescriptor(previous) is true and // IsDataDescriptor(propId.descriptor) is true. @@ -16802,7 +16854,7 @@ namespace ts { // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields let currentKind: number; if (prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment) { - // Grammar checking for computedPropertName and shorthandPropertyAssignment + // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop, (prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === SyntaxKind.NumericLiteral) { checkGrammarNumericLiteral(name); @@ -16816,7 +16868,7 @@ namespace ts { currentKind = GetAccessor; } else if (prop.kind === SyntaxKind.SetAccessor) { - currentKind = SetAccesor; + currentKind = SetAccessor; } else { Debug.fail("Unexpected syntax kind:" + prop.kind); @@ -17288,7 +17340,7 @@ namespace ts { // We are either parented by another statement, or some sort of block. // If we're in a block, we only want to really report an error once - // to prevent noisyness. So use a bit on the block to indicate if + // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // if (node.parent.kind === SyntaxKind.Block || node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 3eb42292fb1..ebbfc5fcf8b 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -78,6 +78,7 @@ namespace ts { name: "module", shortName: "m", type: { + "none": ModuleKind.None, "commonjs": ModuleKind.CommonJS, "amd": ModuleKind.AMD, "system": ModuleKind.System, @@ -87,7 +88,7 @@ namespace ts { }, description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: Diagnostics.KIND, - error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015 + error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none }, { name: "newLine", @@ -324,6 +325,11 @@ namespace ts { name: "allowSyntheticDefaultImports", type: "boolean", description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output } ]; @@ -550,7 +556,21 @@ namespace ts { } else { const filesSeen: Map = {}; - const exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; + + let exclude: string[] = []; + if (json["exclude"] instanceof Array) { + exclude = json["exclude"]; + } + else { + // by default exclude node_modules, and any specificied output directory + exclude = ["node_modules"]; + const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); + } + } + exclude = map(exclude, normalizeSlashes); + const supportedExtensions = getSupportedExtensions(options); Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); @@ -564,6 +584,11 @@ namespace ts { continue; } + // Skip over any minified JavaScript files (ending in ".min.js") + if (/\.min\.js$/.test(fileName)) { + continue; + } + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation if (extension === ".d.ts" || (options.allowJs && contains(supportedJavascriptExtensions, extension))) { @@ -587,7 +612,6 @@ namespace ts { const errors: Diagnostic[] = []; if (configFileName && getBaseFileName(configFileName) === "jsconfig.json") { - options.module = ModuleKind.CommonJS; options.allowJs = true; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 21536da36ff..702ded96a3f 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -667,7 +667,7 @@ namespace ts { } function getNormalizedPathComponentsOfUrl(url: string) { - // Get root length of http://www.website.com/folder1/foler2/ + // Get root length of http://www.website.com/folder1/folder2/ // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] @@ -695,7 +695,7 @@ namespace ts { const indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components afetr the root normally like any other folder components + // and get components after the root normally like any other folder components rootLength = indexOfNextSlash + 1; return normalizedPathComponents(url, rootLength); } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index ab0b16947fc..d8bdd2fb52f 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -18,7 +18,7 @@ namespace ts { referencePathsOutput: string; } - type GetSymbolAccessibilityDiagnostic = (symbolAccesibilityResult: SymbolAccessiblityResult) => SymbolAccessibilityDiagnostic; + type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic; interface EmitTextWriterWithSymbolWriter extends EmitTextWriter, SymbolWriter { getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic; @@ -51,7 +51,9 @@ namespace ts { let decreaseIndent: () => void; let writeTextOfNode: (text: string, node: Node) => void; - let writer = createAndSetNewTextWriterWithSymbolWriter(); + let writer: EmitTextWriterWithSymbolWriter; + + createAndSetNewTextWriterWithSymbolWriter(); let enclosingDeclaration: Node; let resultHasExternalModuleIndicator: boolean; @@ -174,7 +176,7 @@ namespace ts { } } - function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter { + function createAndSetNewTextWriterWithSymbolWriter(): void { const writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; @@ -186,7 +188,6 @@ namespace ts { writer.writeParameter = writer.write; writer.writeSymbol = writer.write; setWriter(writer); - return writer; } function setWriter(newWriter: EmitTextWriterWithSymbolWriter) { @@ -252,30 +253,30 @@ namespace ts { setWriter(oldWriter); } - function handleSymbolAccessibilityError(symbolAccesibilityResult: SymbolAccessiblityResult) { - if (symbolAccesibilityResult.accessibility === SymbolAccessibility.Accessible) { + function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) { // write the aliases - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); } } else { // Report error reportedDeclarationError = true; - const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { - emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, + emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, getTextOfNodeFromSourceText(currentText, errorInfo.typeName), - symbolAccesibilityResult.errorSymbolName, - symbolAccesibilityResult.errorModuleName)); + symbolAccessibilityResult.errorSymbolName, + symbolAccessibilityResult.errorModuleName)); } else { - emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, + emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, - symbolAccesibilityResult.errorSymbolName, - symbolAccesibilityResult.errorModuleName)); + symbolAccessibilityResult.errorSymbolName, + symbolAccessibilityResult.errorModuleName)); } } } @@ -548,7 +549,7 @@ namespace ts { writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, errorNode: node @@ -677,7 +678,7 @@ namespace ts { } writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getImportEntityNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, @@ -698,10 +699,6 @@ 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 - return; - } emitJsDocComments(node); if (node.flags & NodeFlags.Export) { write("export "); @@ -737,7 +734,7 @@ namespace ts { function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration) { // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered - // external modules since they are indistingushable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' + // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' // so compiler will treat them as external modules. resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration; let moduleSpecifier: Node; @@ -854,7 +851,7 @@ namespace ts { writeLine(); enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { return { diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, errorNode: node.type, @@ -921,7 +918,7 @@ namespace ts { } } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { // Type parameter constraints are named by user so we should always be able to name it let diagnosticMessage: DiagnosticMessage; switch (node.parent.kind) { @@ -991,7 +988,7 @@ namespace ts { write("null"); } - function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getHeritageClauseVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { @@ -1108,10 +1105,10 @@ namespace ts { } } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult) { + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { if (node.kind === SyntaxKind.VariableDeclaration) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; @@ -1120,30 +1117,30 @@ namespace ts { else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) { // TODO(jfreeman): Deal with computed properties in error reporting. if (node.flags & NodeFlags.Static) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; } else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; } } } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1167,8 +1164,8 @@ namespace ts { } function emitBindingElement(bindingElement: BindingElement) { - function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getBindingElementTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: bindingElement, @@ -1259,17 +1256,17 @@ namespace ts { } } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) { // Setters have to have type named and cannot infer it so, the type should always be named if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; } @@ -1282,15 +1279,15 @@ namespace ts { } else { if (accessorWithTypeAnnotation.flags & NodeFlags.Static) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; } else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; @@ -1389,26 +1386,26 @@ namespace ts { writeLine(); } - function getReturnTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { + function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; switch (node.kind) { case SyntaxKind.ConstructSignature: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; break; case SyntaxKind.CallSignature: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; break; case SyntaxKind.IndexSignature: // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; break; @@ -1416,30 +1413,30 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: if (node.flags & NodeFlags.Static) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; } else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; } else { // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; case SyntaxKind.FunctionDeclaration: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; @@ -1485,8 +1482,8 @@ namespace ts { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1494,53 +1491,53 @@ namespace ts { } : undefined; } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult): DiagnosticMessage { + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult): DiagnosticMessage { switch (node.parent.kind) { case SyntaxKind.Constructor: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; case SyntaxKind.ConstructSignature: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; case SyntaxKind.CallSignature: // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: if (node.parent.flags & NodeFlags.Static) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; } else { // Interfaces cannot have parameter types that cannot be named - return symbolAccesibilityResult.errorModuleName ? + return symbolAccessibilityResult.errorModuleName ? Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } case SyntaxKind.FunctionDeclaration: - return symbolAccesibilityResult.errorModuleName ? - symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 116270d0c4d..b9ffeb15e67 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1,4 +1,4 @@ - { +{ "Unterminated string literal.": { "category": "Error", "code": 1002 @@ -123,7 +123,7 @@ "category": "Error", "code": 1043 }, - "'{0}' modifier cannot appear on a module element.": { + "'{0}' modifier cannot appear on a module or namespace element.": { "category": "Error", "code": 1044 }, @@ -447,7 +447,7 @@ "category": "Error", "code": 1147 }, - "Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": { + "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": { "category": "Error", "code": 1148 }, @@ -687,7 +687,7 @@ "category": "Error", "code": 1218 }, - "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": { + "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.": { "category": "Error", "code": 1219 }, @@ -723,6 +723,10 @@ "category": "Error", "code": 1227 }, + "A type predicate is only allowed in return type position for functions and methods.": { + "category": "Error", + "code": 1228 + }, "A type predicate cannot reference a rest parameter.": { "category": "Error", "code": 1229 @@ -1279,10 +1283,6 @@ "category": "Error", "code": 2417 }, - "Type name '{0}' in extends clause does not reference constructor function for '{0}'.": { - "category": "Error", - "code": 2419 - }, "Class '{0}' incorrectly implements interface '{1}'.": { "category": "Error", "code": 2420 @@ -2203,6 +2203,7 @@ "category": "Error", "code": 5062 }, + "Concatenate and emit output to single file.": { "category": "Message", "code": 6001 @@ -2247,10 +2248,10 @@ "category": "Message", "code": 6011 }, - "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": { - "category": "Message", - "code": 6015 - }, + "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": { + "category": "Message", + "code": 6015 + }, "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'": { "category": "Message", "code": 6016 @@ -2335,7 +2336,7 @@ "category": "Error", "code": 6045 }, - "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'.": { + "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'.": { "category": "Error", "code": 6046 }, @@ -2587,6 +2588,11 @@ "category": "Message", "code": 6111 }, + "Do not emit 'use strict' directives in module output.": { + "category": "Message", + "code": 6112 + }, + "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", "code": 7005 @@ -2739,11 +2745,6 @@ "category": "Error", "code": 8016 }, - "'decorators' can only be used in a .ts file.": { - "category": "Error", - "code": 8017 - }, - "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": { "category": "Error", "code": 9002 @@ -2773,23 +2774,23 @@ "code": 17004 }, "A constructor cannot contain a 'super' call when its class extends 'null'": { - "category": "Error", - "code": 17005 + "category": "Error", + "code": 17005 }, "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": { - "category": "Error", - "code": 17006 + "category": "Error", + "code": 17006 }, "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": { - "category": "Error", - "code": 17007 + "category": "Error", + "code": 17007 }, "JSX element '{0}' has no corresponding closing tag.": { - "category": "Error", - "code": 17008 + "category": "Error", + "code": 17008 }, "'super' must be called before accessing 'this' in the constructor of a derived class.": { - "category": "Error", - "code": 17009 + "category": "Error", + "code": 17009 } -} +} \ No newline at end of file diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 835086ae2ee..f2b2021ee33 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -287,6 +287,54 @@ namespace ts { _i = 0x10000000, // Use/preference flag for '_i' } + const enum CopyDirection { + ToOriginal, + ToOutParameter + } + + /** + * If loop contains block scoped binding captured in some function then loop body is converted to a function. + * Lexical bindings declared in loop initializer will be passed into the loop body function as parameters, + * however if this binding is modified inside the body - this new value should be propagated back to the original binding. + * This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body. + * On every iteration this variable is initialized with value of corresponding binding. + * At every point where control flow leaves the loop either explicitly (break/continue) or implicitly (at the end of loop body) + * we copy the value inside the loop to the out parameter holder. + * + * for (let x;;) { + * let a = 1; + * let b = () => a; + * x++ + * if (...) break; + * ... + * } + * + * will be converted to + * + * var out_x; + * var loop = function(x) { + * var a = 1; + * var b = function() { return a; } + * x++; + * if (...) return out_x = x, "break"; + * ... + * out_x = x; + * } + * for (var x;;) { + * out_x = x; + * var state = loop(x); + * x = out_x; + * if (state === "break") break; + * } + * + * NOTE: values to out parameters are not copies if loop is abrupted with 'return' - in this case this will end the entire enclosing function + * so nobody can observe this new value. + */ + interface LoopOutParameter { + originalName: Identifier; + outParamName: string; + } + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult { // emit output for the __extends helper function @@ -359,14 +407,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge interface ConvertedLoopState { /* - * set of labels that occured inside the converted loop + * set of labels that occurred inside the converted loop * used to determine if labeled jump can be emitted as is or it should be dispatched to calling code */ labels?: Map; /* * collection of labeled jumps that transfer control outside the converted loop. * maps store association 'label -> labelMarker' where - * - label - value of label as it apprear in code + * - label - value of label as it appear in code * - label marker - return value that should be interpreted by calling code as 'jump to