diff --git a/Gulpfile.ts b/Gulpfile.ts
index e025ce6eaa8..022606e133b 100644
--- a/Gulpfile.ts
+++ b/Gulpfile.ts
@@ -2,6 +2,7 @@
import * as cp from "child_process";
import * as path from "path";
import * as fs from "fs";
+import child_process = require("child_process");
import originalGulp = require("gulp");
import helpMaker = require("gulp-help");
import runSequence = require("run-sequence");
@@ -749,7 +750,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo
const originalMap = file.sourceMap;
const prebundledContent = file.contents.toString();
// Make paths absolute to help sorcery deal with all the terrible paths being thrown around
- originalMap.sources = originalMap.sources.map(s => path.resolve(s));
+ originalMap.sources = originalMap.sources.map(s => path.resolve(path.join("src/harness", s)));
// intoStream (below) makes browserify think the input file is named this, so this is what it puts in the sourcemap
originalMap.file = "built/local/_stream_0.js";
@@ -1019,40 +1020,16 @@ function spawnLintWorker(files: {path: string}[], callback: (failures: number) =
}
gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => {
- const fileMatcher = RegExp(cmdLineOptions["files"]);
if (fold.isTravis()) console.log(fold.start("lint"));
-
- let files: {stat: fs.Stats, path: string}[] = [];
- return gulp.src(lintTargets, { read: false })
- .pipe(through2.obj((chunk, enc, cb) => {
- files.push(chunk);
- cb();
- }, (cb) => {
- files = files.filter(file => fileMatcher.test(file.path)).sort((filea, fileb) => filea.stat.size - fileb.stat.size);
- const workerCount = cmdLineOptions["workers"];
- for (let i = 0; i < workerCount; i++) {
- spawnLintWorker(files, finished);
- }
-
- let completed = 0;
- let failures = 0;
- function finished(fails) {
- completed++;
- failures += fails;
- if (completed === workerCount) {
- if (fold.isTravis()) console.log(fold.end("lint"));
- if (failures > 0) {
- throw new Error(`Linter errors: ${failures}`);
- }
- else {
- cb();
- }
- }
- }
- }));
+ const fileMatcher = cmdLineOptions["files"];
+ const files = fileMatcher
+ ? `src/**/${fileMatcher}`
+ : "Gulpfile.ts 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
+ const cmd = `node node_modules/tslint/bin/tslint ${files} --format stylish`;
+ console.log("Linting: " + cmd);
+ child_process.execSync(cmd, { stdio: [0, 1, 2] });
});
-
gulp.task("default", "Runs 'local'", ["local"]);
gulp.task("watch", "Watches the src/ directory for changes and executes runtests-parallel.", [], () => {
diff --git a/Jakefile.js b/Jakefile.js
index 595875dfc32..c9390f560ae 100644
--- a/Jakefile.js
+++ b/Jakefile.js
@@ -11,11 +11,7 @@ var ts = require("./lib/typescript");
// Variables
var compilerDirectory = "src/compiler/";
-var servicesDirectory = "src/services/";
var serverDirectory = "src/server/";
-var typingsInstallerDirectory = "src/server/typingsInstaller";
-var cancellationTokenDirectory = "src/server/cancellationToken";
-var watchGuardDirectory = "src/server/watchGuard";
var harnessDirectory = "src/harness/";
var libraryDirectory = "src/lib/";
var scriptsDirectory = "scripts/";
@@ -33,7 +29,8 @@ var thirdParty = "ThirdPartyNoticeText.txt";
var nodeModulesPathPrefix = path.resolve("./node_modules/.bin/") + path.delimiter;
if (process.env.path !== undefined) {
process.env.path = nodeModulesPathPrefix + process.env.path;
-} else if (process.env.PATH !== undefined) {
+}
+else if (process.env.PATH !== undefined) {
process.env.PATH = nodeModulesPathPrefix + process.env.PATH;
}
@@ -131,6 +128,7 @@ var harnessSources = harnessCoreSources.concat([
"matchFiles.ts",
"initializeTSConfig.ts",
"printer.ts",
+ "textChanges.ts",
"transform.ts",
"customTransforms.ts",
].map(function (f) {
@@ -315,13 +313,15 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
if (useDebugMode) {
if (opts.inlineSourceMap) {
options += " --inlineSourceMap --inlineSources";
- } else {
+ }
+ else {
options += " -sourcemap";
if (!opts.noMapRoot) {
options += " -mapRoot file:///" + path.resolve(path.dirname(outFile));
}
}
- } else {
+ }
+ else {
options += " --newLine LF";
}
@@ -333,7 +333,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
options += " --lib " + opts.lib
}
else {
- options += " --lib es5,scripthost"
+ options += " --lib es5"
}
options += " --noUnusedLocals --noUnusedParameters";
@@ -587,13 +587,13 @@ var cancellationTokenFile = path.join(builtLocalDirectory, "cancellationToken.js
compileFile(cancellationTokenFile, cancellationTokenSources, [builtLocalDirectory].concat(cancellationTokenSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"], outDir: builtLocalDirectory, noOutFile: true, lib: "es6" });
var typingsInstallerFile = path.join(builtLocalDirectory, "typingsInstaller.js");
-compileFile(typingsInstallerFile, typingsInstallerSources, [builtLocalDirectory].concat(typingsInstallerSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"], outDir: builtLocalDirectory, noOutFile: false, lib: "es6,scripthost" });
+compileFile(typingsInstallerFile, typingsInstallerSources, [builtLocalDirectory].concat(typingsInstallerSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"], outDir: builtLocalDirectory, noOutFile: false, lib: "es6" });
var watchGuardFile = path.join(builtLocalDirectory, "watchGuard.js");
compileFile(watchGuardFile, watchGuardSources, [builtLocalDirectory].concat(watchGuardSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"], outDir: builtLocalDirectory, noOutFile: false, lib: "es6" });
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
-compileFile(serverFile, serverSources, [builtLocalDirectory, copyright, cancellationTokenFile, typingsInstallerFile, watchGuardFile].concat(serverSources).concat(servicesSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"], preserveConstEnums: true, lib: "es6,scripthost" });
+compileFile(serverFile, serverSources, [builtLocalDirectory, copyright, cancellationTokenFile, typingsInstallerFile, watchGuardFile].concat(serverSources).concat(servicesSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"], preserveConstEnums: true, lib: "es6" });
var tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js");
var tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
compileFile(
@@ -717,7 +717,7 @@ compileFile(
/*prereqs*/[builtLocalDirectory, tscFile].concat(libraryTargets).concat(servicesSources).concat(harnessSources),
/*prefixes*/[],
/*useBuiltCompiler:*/ true,
- /*opts*/ { inlineSourceMap: true, types: ["node", "mocha", "chai"], lib: "es6,scripthost" });
+ /*opts*/ { inlineSourceMap: true, types: ["node", "mocha", "chai"], lib: "es6" });
var internalTests = "internal/";
@@ -751,7 +751,8 @@ function exec(cmd, completeHandler, errorHandler) {
ex.addListener("error", function (e, status) {
if (errorHandler) {
errorHandler(e, status);
- } else {
+ }
+ else {
fail("Process exited with code " + status);
}
});
@@ -945,7 +946,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, lib: "es6" });
desc("Runs browserify on run.js to produce a file suitable for running tests in the browser");
task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() {
@@ -1009,21 +1010,32 @@ task("baseline-accept", function () {
function acceptBaseline(sourceFolder, targetFolder) {
console.log('Accept baselines from ' + sourceFolder + ' to ' + targetFolder);
- var files = fs.readdirSync(sourceFolder);
var deleteEnding = '.delete';
- for (var i in files) {
- var filename = files[i];
- var fullLocalPath = path.join(sourceFolder, filename);
- if (fs.statSync(fullLocalPath).isFile()) {
- if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) {
- filename = filename.substr(0, filename.length - deleteEnding.length);
- fs.unlinkSync(path.join(targetFolder, filename));
- } else {
- var target = path.join(targetFolder, filename);
- if (fs.existsSync(target)) {
- fs.unlinkSync(target);
+
+ acceptBaselineFolder(sourceFolder, targetFolder);
+
+ function acceptBaselineFolder(sourceFolder, targetFolder) {
+ var files = fs.readdirSync(sourceFolder);
+
+ for (var i in files) {
+ var filename = files[i];
+ var fullLocalPath = path.join(sourceFolder, filename);
+ var stat = fs.statSync(fullLocalPath);
+ if (stat.isFile()) {
+ if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) {
+ filename = filename.substr(0, filename.length - deleteEnding.length);
+ fs.unlinkSync(path.join(targetFolder, filename));
}
- fs.renameSync(path.join(sourceFolder, filename), target);
+ else {
+ var target = path.join(targetFolder, filename);
+ if (fs.existsSync(target)) {
+ fs.unlinkSync(target);
+ }
+ fs.renameSync(path.join(sourceFolder, filename), target);
+ }
+ }
+ else if (stat.isDirectory()) {
+ acceptBaselineFolder(fullLocalPath, path.join(targetFolder, filename));
}
}
}
@@ -1180,43 +1192,16 @@ function spawnLintWorker(files, callback) {
}
desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex");
-task("lint", ["build-rules"], function () {
+task("lint", ["build-rules"], () => {
if (fold.isTravis()) console.log(fold.start("lint"));
- var startTime = mark();
- var failed = 0;
- var fileMatcher = RegExp(process.env.f || process.env.file || process.env.files || "");
- var done = {};
- for (var i in lintTargets) {
- var target = lintTargets[i];
- if (!done[target] && fileMatcher.test(target)) {
- done[target] = fs.statSync(target).size;
- }
- }
-
- var workerCount = (process.env.workerCount && +process.env.workerCount) || os.cpus().length;
-
- var names = Object.keys(done).sort(function (namea, nameb) {
- return done[namea] - done[nameb];
+ const fileMatcher = process.env.f || process.env.file || process.env.files;
+ const files = fileMatcher
+ ? `src/**/${fileMatcher}`
+ : "Gulpfile.ts 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
+ const cmd = `node node_modules/tslint/bin/tslint ${files} --format stylish`;
+ console.log("Linting: " + cmd);
+ jake.exec([cmd], { interactive: true }, () => {
+ if (fold.isTravis()) console.log(fold.end("lint"));
+ complete();
});
-
- for (var i = 0; i < workerCount; i++) {
- spawnLintWorker(names, finished);
- }
-
- var completed = 0;
- var failures = 0;
- function finished(fails) {
- completed++;
- failures += fails;
- if (completed === workerCount) {
- measure(startTime);
- if (fold.isTravis()) console.log(fold.end("lint"));
- if (failures > 0) {
- fail('Linter errors.', failed);
- }
- else {
- complete();
- }
- }
- }
-}, { async: true });
+});
diff --git a/README.md b/README.md
index 2f631439eb0..d21e558360c 100644
--- a/README.md
+++ b/README.md
@@ -39,8 +39,8 @@ with any additional questions or comments.
## Documentation
-* [Quick tutorial](http://www.typescriptlang.org/Tutorial)
-* [Programming handbook](http://www.typescriptlang.org/Handbook)
+* [Quick tutorial](http://www.typescriptlang.org/docs/tutorial.html)
+* [Programming handbook](http://www.typescriptlang.org/docs/handbook/basic-types.html)
* [Language specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md)
* [Homepage](http://www.typescriptlang.org/)
@@ -95,4 +95,4 @@ node built/local/tsc.js hello.ts
## Roadmap
-For details on our planned features and future direction please refer to our [roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap).
\ No newline at end of file
+For details on our planned features and future direction please refer to our [roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap).
diff --git a/doc/logo.svg b/doc/logo.svg
index fc7e0fadd66..2c0dd017a1b 100644
--- a/doc/logo.svg
+++ b/doc/logo.svg
@@ -1,15 +1,10 @@
-
-
+
\ No newline at end of file
diff --git a/issue_template.md b/issue_template.md
index 4d397a0afd6..29190e79763 100644
--- a/issue_template.md
+++ b/issue_template.md
@@ -2,7 +2,7 @@
-**TypeScript Version:** 2.1.1 / nightly (2.2.0-dev.201xxxxx)
+**TypeScript Version:** 2.2.1 / nightly (2.2.0-dev.201xxxxx)
**Code**
diff --git a/lib/tsc.js b/lib/tsc.js
index be8abfb4a0d..f7231fcafd8 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -53977,7 +53977,7 @@ var ts;
var padding = makePadding(marginLength);
output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine);
output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine);
- output.push(padding + "tsc @args.txt" + ts.sys.newLine);
+ output.push(padding + "tsc --project tsconfig.json" + ts.sys.newLine);
output.push(ts.sys.newLine);
output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine);
var optsList = ts.filter(ts.optionDeclarations.slice(), function (v) { return !v.experimental; });
diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts
index e7ba874d3d2..e9c128f530c 100644
--- a/src/compiler/binder.ts
+++ b/src/compiler/binder.ts
@@ -259,7 +259,7 @@ namespace ts {
case SyntaxKind.ExportAssignment:
return (node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
- switch (getSpecialPropertyAssignmentKind(node)) {
+ switch (getSpecialPropertyAssignmentKind(node as BinaryExpression)) {
case SpecialPropertyAssignmentKind.ModuleExports:
// module.exports = ...
return "export=";
@@ -2017,30 +2017,28 @@ namespace ts {
}
break;
case SyntaxKind.BinaryExpression:
- if (isInJavaScriptFile(node)) {
- const specialKind = getSpecialPropertyAssignmentKind(node);
- switch (specialKind) {
- case SpecialPropertyAssignmentKind.ExportsProperty:
- bindExportsPropertyAssignment(node);
- break;
- case SpecialPropertyAssignmentKind.ModuleExports:
- bindModuleExportsAssignment(node);
- break;
- case SpecialPropertyAssignmentKind.PrototypeProperty:
- bindPrototypePropertyAssignment(node);
- break;
- case SpecialPropertyAssignmentKind.ThisProperty:
- bindThisPropertyAssignment(node);
- break;
- case SpecialPropertyAssignmentKind.Property:
- bindStaticPropertyAssignment(node);
- break;
- case SpecialPropertyAssignmentKind.None:
- // Nothing to do
- break;
- default:
- Debug.fail("Unknown special property assignment kind");
- }
+ const specialKind = getSpecialPropertyAssignmentKind(node as BinaryExpression);
+ switch (specialKind) {
+ case SpecialPropertyAssignmentKind.ExportsProperty:
+ bindExportsPropertyAssignment(node);
+ break;
+ case SpecialPropertyAssignmentKind.ModuleExports:
+ bindModuleExportsAssignment(node);
+ break;
+ case SpecialPropertyAssignmentKind.PrototypeProperty:
+ bindPrototypePropertyAssignment(node);
+ break;
+ case SpecialPropertyAssignmentKind.ThisProperty:
+ bindThisPropertyAssignment(node);
+ break;
+ case SpecialPropertyAssignmentKind.Property:
+ bindStaticPropertyAssignment(node);
+ break;
+ case SpecialPropertyAssignmentKind.None:
+ // Nothing to do
+ break;
+ default:
+ Debug.fail("Unknown special property assignment kind");
}
return checkStrictModeBinaryExpression(node);
case SyntaxKind.CatchClause:
@@ -2332,6 +2330,7 @@ namespace ts {
function bindThisPropertyAssignment(node: BinaryExpression) {
Debug.assert(isInJavaScriptFile(node));
+ const container = getThisContainer(node, /*includeArrowFunctions*/false);
switch (container.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
@@ -2342,6 +2341,7 @@ namespace ts {
break;
case SyntaxKind.Constructor:
+ case SyntaxKind.PropertyDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts
index 6d10998ffc5..12152e4507a 100644
--- a/src/compiler/checker.ts
+++ b/src/compiler/checker.ts
@@ -61,6 +61,7 @@ namespace ts {
const noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis;
const emitResolver = createResolver();
+ const nodeBuilder = createNodeBuilder();
const undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined");
undefinedSymbol.declarations = [];
@@ -106,6 +107,9 @@ namespace ts {
getParameterType: getTypeAtPosition,
getReturnTypeOfSignature,
getNonNullableType,
+ typeToTypeNode: nodeBuilder.typeToTypeNode,
+ indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
+ signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
getSymbolsInScope: (location, meaning) => {
location = getParseTreeNode(location);
return location ? getSymbolsInScope(location, meaning) : [];
@@ -284,6 +288,8 @@ namespace ts {
let deferredGlobalAsyncIterableIteratorType: GenericType;
let deferredGlobalTemplateStringsArrayType: ObjectType;
let deferredJsxElementClassType: Type;
+ let deferredJsxElementType: Type;
+ let deferredJsxStatelessElementType: Type;
let deferredNodes: Node[];
let deferredUnusedIdentifierNodes: Node[];
@@ -404,7 +410,6 @@ namespace ts {
});
const typeofType = createTypeofType();
- let jsxElementType: Type;
let _jsxNamespace: string;
let _jsxFactoryEntity: EntityName;
@@ -1068,9 +1073,10 @@ namespace ts {
// block-scoped variable and namespace module. However, only when we
// try to resolve name in /*1*/ which is used in variable position,
// we want to check for block-scoped
- if (meaning & SymbolFlags.BlockScopedVariable) {
+ if (meaning & SymbolFlags.BlockScopedVariable ||
+ ((meaning & SymbolFlags.Class || meaning & SymbolFlags.Enum) && (meaning & SymbolFlags.Value) === SymbolFlags.Value)) {
const exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
- if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable) {
+ if (exportOrLocalSymbol.flags & SymbolFlags.BlockScopedVariable || exportOrLocalSymbol.flags & SymbolFlags.Class || exportOrLocalSymbol.flags & SymbolFlags.Enum) {
checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
}
}
@@ -1183,14 +1189,22 @@ namespace ts {
}
function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void {
- Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0);
+ Debug.assert(!!(result.flags & SymbolFlags.BlockScopedVariable || result.flags & SymbolFlags.Class || result.flags & SymbolFlags.Enum));
// Block-scoped variables cannot be used before their definition
- const declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined);
+ const declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) || isClassLike(d) || (d.kind === SyntaxKind.EnumDeclaration) ? d : undefined);
- Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined");
+ Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined");
if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
- error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name));
+ if (result.flags & SymbolFlags.BlockScopedVariable) {
+ error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name));
+ }
+ else if (result.flags & SymbolFlags.Class) {
+ error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(declaration.name));
+ }
+ else if (result.flags & SymbolFlags.Enum) {
+ error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(declaration.name));
+ }
}
}
@@ -2188,6 +2202,584 @@ namespace ts {
return result;
}
+ function createNodeBuilder() {
+ let context: NodeBuilderContext;
+
+ return {
+ typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => {
+ context = createNodeBuilderContext(enclosingDeclaration, flags);
+ const resultingNode = typeToTypeNodeHelper(type);
+ const result = context.encounteredError ? undefined : resultingNode;
+ return result;
+ },
+ indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => {
+ context = createNodeBuilderContext(enclosingDeclaration, flags);
+ const resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind);
+ const result = context.encounteredError ? undefined : resultingNode;
+ return result;
+ },
+ signatureToSignatureDeclaration: (signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => {
+ context = createNodeBuilderContext(enclosingDeclaration, flags);
+ const resultingNode = signatureToSignatureDeclarationHelper(signature, kind);
+ const result = context.encounteredError ? undefined : resultingNode;
+ return result;
+ }
+ };
+
+ interface NodeBuilderContext {
+ readonly enclosingDeclaration: Node | undefined;
+ readonly flags: NodeBuilderFlags | undefined;
+ encounteredError: boolean;
+ inObjectTypeLiteral: boolean;
+ checkAlias: boolean;
+ symbolStack: Symbol[] | undefined;
+ }
+
+ function createNodeBuilderContext(enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeBuilderContext {
+ return {
+ enclosingDeclaration,
+ flags,
+ encounteredError: false,
+ inObjectTypeLiteral: false,
+ checkAlias: true,
+ symbolStack: undefined
+ };
+ }
+
+ function typeToTypeNodeHelper(type: Type): TypeNode {
+ if (!type) {
+ context.encounteredError = true;
+ // TODO(aozgaa): should we return implict any (undefined) or explicit any (keywordtypenode)?
+ return undefined;
+ }
+
+ if (type.flags & TypeFlags.Any) {
+ return createKeywordTypeNode(SyntaxKind.AnyKeyword);
+ }
+ if (type.flags & TypeFlags.String) {
+ return createKeywordTypeNode(SyntaxKind.StringKeyword);
+ }
+ if (type.flags & TypeFlags.Number) {
+ return createKeywordTypeNode(SyntaxKind.NumberKeyword);
+ }
+ if (type.flags & TypeFlags.Boolean) {
+ return createKeywordTypeNode(SyntaxKind.BooleanKeyword);
+ }
+ if (type.flags & TypeFlags.Enum) {
+ const name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ return createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (type.flags & (TypeFlags.StringLiteral)) {
+ return createLiteralTypeNode((createLiteral((type).text)));
+ }
+ if (type.flags & (TypeFlags.NumberLiteral)) {
+ return createLiteralTypeNode((createNumericLiteral((type).text)));
+ }
+ if (type.flags & TypeFlags.BooleanLiteral) {
+ return (type).intrinsicName === "true" ? createTrue() : createFalse();
+ }
+ if (type.flags & TypeFlags.EnumLiteral) {
+ const name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ return createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (type.flags & TypeFlags.Void) {
+ return createKeywordTypeNode(SyntaxKind.VoidKeyword);
+ }
+ if (type.flags & TypeFlags.Undefined) {
+ return createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
+ }
+ if (type.flags & TypeFlags.Null) {
+ return createKeywordTypeNode(SyntaxKind.NullKeyword);
+ }
+ if (type.flags & TypeFlags.Never) {
+ return createKeywordTypeNode(SyntaxKind.NeverKeyword);
+ }
+ if (type.flags & TypeFlags.ESSymbol) {
+ return createKeywordTypeNode(SyntaxKind.SymbolKeyword);
+ }
+ if (type.flags & TypeFlags.NonPrimitive) {
+ return createKeywordTypeNode(SyntaxKind.ObjectKeyword);
+ }
+ if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) {
+ if (context.inObjectTypeLiteral) {
+ if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowThisInObjectLiteral)) {
+ context.encounteredError = true;
+ }
+ }
+ return createThis();
+ }
+
+ const objectFlags = getObjectFlags(type);
+
+ if (objectFlags & ObjectFlags.Reference) {
+ Debug.assert(!!(type.flags & TypeFlags.Object));
+ return typeReferenceToTypeNode(type);
+ }
+ if (objectFlags & ObjectFlags.ClassOrInterface) {
+ Debug.assert(!!(type.flags & TypeFlags.Object));
+ const name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ // TODO(aozgaa): handle type arguments.
+ return createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+ if (type.flags & TypeFlags.TypeParameter) {
+ const name = symbolToName(type.symbol, /*expectsIdentifier*/ false);
+ // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
+ return createTypeReferenceNode(name, /*typeArguments*/ undefined);
+ }
+
+ if (context.checkAlias && type.aliasSymbol) {
+ const name = symbolToName(type.aliasSymbol, /*expectsIdentifier*/ false);
+ const typeArgumentNodes = type.aliasTypeArguments && mapToTypeNodeArray(type.aliasTypeArguments);
+ return createTypeReferenceNode(name, typeArgumentNodes);
+ }
+ context.checkAlias = false;
+
+ if (type.flags & TypeFlags.Union) {
+ const formattedUnionTypes = formatUnionTypes((type).types);
+ const unionTypeNodes = formattedUnionTypes && mapToTypeNodeArray(formattedUnionTypes);
+ if (unionTypeNodes && unionTypeNodes.length > 0) {
+ return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, unionTypeNodes);
+ }
+ else {
+ if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyUnionOrIntersection)) {
+ context.encounteredError = true;
+ }
+ return undefined;
+ }
+ }
+
+ if (type.flags & TypeFlags.Intersection) {
+ return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, mapToTypeNodeArray((type as UnionType).types));
+ }
+
+ if (objectFlags & (ObjectFlags.Anonymous | ObjectFlags.Mapped)) {
+ Debug.assert(!!(type.flags & TypeFlags.Object));
+ // The type is an object literal type.
+ return createAnonymousTypeNode(type);
+ }
+
+ if (type.flags & TypeFlags.Index) {
+ const indexedType = (type).type;
+ const indexTypeNode = typeToTypeNodeHelper(indexedType);
+ return createTypeOperatorNode(indexTypeNode);
+ }
+ if (type.flags & TypeFlags.IndexedAccess) {
+ const objectTypeNode = typeToTypeNodeHelper((type).objectType);
+ const indexTypeNode = typeToTypeNodeHelper((type).indexType);
+ return createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
+ }
+
+ Debug.fail("Should be unreachable.");
+
+ function mapToTypeNodeArray(types: Type[]): TypeNode[] {
+ const result = [];
+ for (const type of types) {
+ const typeNode = typeToTypeNodeHelper(type);
+ if (typeNode) {
+ result.push(typeNode);
+ }
+ }
+ return result;
+ }
+
+ function createMappedTypeNodeFromType(type: MappedType) {
+ Debug.assert(!!(type.flags & TypeFlags.Object));
+ const typeParameter = getTypeParameterFromMappedType(type);
+ const typeParameterNode = typeParameterToDeclaration(typeParameter);
+
+ const templateType = getTemplateTypeFromMappedType(type);
+ const templateTypeNode = typeToTypeNodeHelper(templateType);
+ const readonlyToken = type.declaration && type.declaration.readonlyToken ? createToken(SyntaxKind.ReadonlyKeyword) : undefined;
+ const questionToken = type.declaration && type.declaration.questionToken ? createToken(SyntaxKind.QuestionToken) : undefined;
+
+ return createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
+ }
+
+ function createAnonymousTypeNode(type: ObjectType): TypeNode {
+ const symbol = type.symbol;
+ if (symbol) {
+ // Always use 'typeof T' for type of class, enum, and module objects
+ if (symbol.flags & SymbolFlags.Class && !getBaseTypeVariableOfClass(symbol) ||
+ symbol.flags & (SymbolFlags.Enum | SymbolFlags.ValueModule) ||
+ shouldWriteTypeOfFunctionSymbol()) {
+ return createTypeQueryNodeFromSymbol(symbol);
+ }
+ else if (contains(context.symbolStack, symbol)) {
+ // If type is an anonymous type literal in a type alias declaration, use type alias name
+ const typeAlias = getTypeAliasForTypeLiteral(type);
+ if (typeAlias) {
+ // The specified symbol flags need to be reinterpreted as type flags
+ const entityName = symbolToName(typeAlias, /*expectsIdentifier*/ false);
+ return createTypeReferenceNode(entityName, /*typeArguments*/ undefined);
+ }
+ else {
+ return createKeywordTypeNode(SyntaxKind.AnyKeyword);
+ }
+ }
+ else {
+ // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
+ // of types allows us to catch circular references to instantiations of the same anonymous type
+ if (!context.symbolStack) {
+ context.symbolStack = [];
+ }
+ context.symbolStack.push(symbol);
+ const result = createTypeNodeFromObjectType(type);
+ context.symbolStack.pop();
+ return result;
+ }
+ }
+ else {
+ // Anonymous types without a symbol are never circular.
+ return createTypeNodeFromObjectType(type);
+ }
+
+ function shouldWriteTypeOfFunctionSymbol() {
+ const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method
+ forEach(symbol.declarations, declaration => getModifierFlags(declaration) & ModifierFlags.Static));
+ const isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) &&
+ (symbol.parent || // is exported function symbol
+ forEach(symbol.declarations, declaration =>
+ declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock));
+ if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
+ // typeof is allowed only for static/non local functions
+ return contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively
+ }
+ }
+ }
+
+ function createTypeNodeFromObjectType(type: ObjectType): TypeNode {
+ if (type.objectFlags & ObjectFlags.Mapped) {
+ if (getConstraintTypeFromMappedType(type).flags & (TypeFlags.TypeParameter | TypeFlags.Index)) {
+ return createMappedTypeNodeFromType(type);
+ }
+ }
+
+ const resolved = resolveStructuredTypeMembers(type);
+ if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
+ if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
+ return createTypeLiteralNode(/*members*/ undefined);
+ }
+
+ if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
+ const signature = resolved.callSignatures[0];
+ return signatureToSignatureDeclarationHelper(signature, SyntaxKind.FunctionType);
+ }
+ if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
+ const signature = resolved.constructSignatures[0];
+ return signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructorType);
+ }
+ }
+
+ const saveInObjectTypeLiteral = context.inObjectTypeLiteral;
+ context.inObjectTypeLiteral = true;
+ const members = createTypeNodesFromResolvedType(resolved);
+ context.inObjectTypeLiteral = saveInObjectTypeLiteral;
+ return createTypeLiteralNode(members);
+ }
+
+ function createTypeQueryNodeFromSymbol(symbol: Symbol) {
+ const entityName = symbolToName(symbol, /*expectsIdentifier*/ false);
+ return createTypeQueryNode(entityName);
+ }
+
+ function typeReferenceToTypeNode(type: TypeReference) {
+ const typeArguments: Type[] = type.typeArguments || emptyArray;
+ if (type.target === globalArrayType) {
+ const elementType = typeToTypeNodeHelper(typeArguments[0]);
+ return createArrayTypeNode(elementType);
+ }
+ else if (type.target.objectFlags & ObjectFlags.Tuple) {
+ if (typeArguments.length > 0) {
+ const tupleConstituentNodes = mapToTypeNodeArray(typeArguments.slice(0, getTypeReferenceArity(type)));
+ if (tupleConstituentNodes && tupleConstituentNodes.length > 0) {
+ return createTupleTypeNode(tupleConstituentNodes);
+ }
+ }
+ if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowEmptyTuple)) {
+ context.encounteredError = true;
+ }
+ return undefined;
+ }
+ else {
+ const outerTypeParameters = type.target.outerTypeParameters;
+ let i = 0;
+ let qualifiedName: QualifiedName | undefined = undefined;
+ if (outerTypeParameters) {
+ const length = outerTypeParameters.length;
+ while (i < length) {
+ // Find group of type arguments for type parameters with the same declaring container.
+ const start = i;
+ const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
+ do {
+ i++;
+ } while (i < length && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
+ // When type parameters are their own type arguments for the whole group (i.e. we have
+ // the default outer type arguments), we don't show the group.
+ if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) {
+ const qualifiedNamePart = symbolToName(parent, /*expectsIdentifier*/ true);
+ if (!qualifiedName) {
+ qualifiedName = createQualifiedName(qualifiedNamePart, /*right*/ undefined);
+ }
+ else {
+ Debug.assert(!qualifiedName.right);
+ qualifiedName.right = qualifiedNamePart;
+ qualifiedName = createQualifiedName(qualifiedName, /*right*/ undefined);
+ }
+ }
+ }
+ }
+ let entityName: EntityName = undefined;
+ const nameIdentifier = symbolToName(type.symbol, /*expectsIdentifier*/ true);
+ if (qualifiedName) {
+ Debug.assert(!qualifiedName.right);
+ qualifiedName.right = nameIdentifier;
+ entityName = qualifiedName;
+ }
+ else {
+ entityName = nameIdentifier;
+ }
+ const typeParameterCount = (type.target.typeParameters || emptyArray).length;
+ const typeArgumentNodes = some(typeArguments) ? mapToTypeNodeArray(typeArguments.slice(i, typeParameterCount - i)) : undefined;
+ return createTypeReferenceNode(entityName, typeArgumentNodes);
+ }
+ }
+
+ function createTypeNodesFromResolvedType(resolvedType: ResolvedType): TypeElement[] {
+ const typeElements: TypeElement[] = [];
+ for (const signature of resolvedType.callSignatures) {
+ typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.CallSignature));
+ }
+ for (const signature of resolvedType.constructSignatures) {
+ typeElements.push(signatureToSignatureDeclarationHelper(signature, SyntaxKind.ConstructSignature));
+ }
+ if (resolvedType.stringIndexInfo) {
+ typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, IndexKind.String));
+ }
+ if (resolvedType.numberIndexInfo) {
+ typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, IndexKind.Number));
+ }
+
+ const properties = resolvedType.properties;
+ if (!properties) {
+ return typeElements;
+ }
+
+ for (const propertySymbol of properties) {
+ const propertyType = getTypeOfSymbol(propertySymbol);
+ const oldDeclaration = propertySymbol.declarations && propertySymbol.declarations[0] as TypeElement;
+ if (!oldDeclaration) {
+ return;
+ }
+ const propertyName = oldDeclaration.name;
+ const optionalToken = propertySymbol.flags & SymbolFlags.Optional ? createToken(SyntaxKind.QuestionToken) : undefined;
+ if (propertySymbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(propertyType).length) {
+ const signatures = getSignaturesOfType(propertyType, SignatureKind.Call);
+ for (const signature of signatures) {
+ const methodDeclaration = signatureToSignatureDeclarationHelper(signature, SyntaxKind.MethodSignature);
+ methodDeclaration.name = propertyName;
+ methodDeclaration.questionToken = optionalToken;
+ typeElements.push(methodDeclaration);
+ }
+ }
+ else {
+
+ // TODO(aozgaa): should we create a node with explicit or implict any?
+ const propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType) : createKeywordTypeNode(SyntaxKind.AnyKeyword);
+ typeElements.push(createPropertySignature(
+ propertyName,
+ optionalToken,
+ propertyTypeNode,
+ /*initializer*/undefined));
+ }
+ }
+ return typeElements.length ? typeElements : undefined;
+ }
+ }
+
+ function indexInfoToIndexSignatureDeclarationHelper(indexInfo: IndexInfo, kind: IndexKind): IndexSignatureDeclaration {
+ const indexerTypeNode = createKeywordTypeNode(kind === IndexKind.String ? SyntaxKind.StringKeyword : SyntaxKind.NumberKeyword);
+ const name = getNameFromIndexInfo(indexInfo);
+
+ const indexingParameter = createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined,
+ name,
+ /*questionToken*/ undefined,
+ indexerTypeNode,
+ /*initializer*/ undefined);
+ const typeNode = typeToTypeNodeHelper(indexInfo.type);
+ return createIndexSignatureDeclaration(
+ /*decorators*/ undefined,
+ indexInfo.isReadonly ? [createToken(SyntaxKind.ReadonlyKeyword)] : undefined,
+ [indexingParameter],
+ typeNode);
+ }
+
+ function signatureToSignatureDeclarationHelper(signature: Signature, kind: SyntaxKind): SignatureDeclaration {
+
+ const typeParameters = signature.typeParameters && signature.typeParameters.map(parameter => typeParameterToDeclaration(parameter));
+ const parameters = signature.parameters.map(parameter => symbolToParameterDeclaration(parameter));
+ let returnTypeNode: TypeNode | TypePredicate;
+ if (signature.typePredicate) {
+ const typePredicate = signature.typePredicate;
+ const parameterName = typePredicate.kind === TypePredicateKind.Identifier ? createIdentifier((typePredicate).parameterName) : createThisTypeNode();
+ const typeNode = typeToTypeNodeHelper(typePredicate.type);
+ returnTypeNode = createTypePredicateNode(parameterName, typeNode);
+ }
+ else {
+ const returnType = getReturnTypeOfSignature(signature);
+ returnTypeNode = returnType && typeToTypeNodeHelper(returnType);
+ }
+ const returnTypeNodeExceptAny = returnTypeNode && returnTypeNode.kind !== SyntaxKind.AnyKeyword ? returnTypeNode : undefined;
+
+ return createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNodeExceptAny);
+ }
+
+ function typeParameterToDeclaration(type: TypeParameter): TypeParameterDeclaration {
+ const constraint = getConstraintFromTypeParameter(type);
+ const constraintNode = constraint && typeToTypeNodeHelper(constraint);
+ const defaultParameter = getDefaultFromTypeParameter(type);
+ const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter);
+ const name = symbolToName(type.symbol, /*expectsIdentifier*/ true);
+ return createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
+ }
+
+ function symbolToParameterDeclaration(parameterSymbol: Symbol): ParameterDeclaration {
+ const parameterDeclaration = getDeclarationOfKind(parameterSymbol, SyntaxKind.Parameter);
+ const parameterType = getTypeOfSymbol(parameterSymbol);
+ const parameterTypeNode = typeToTypeNodeHelper(parameterType);
+ // TODO(aozgaa): In the future, check initializer accessibility.
+ const parameterNode = createParameter(
+ parameterDeclaration.decorators,
+ parameterDeclaration.modifiers,
+ parameterDeclaration.dotDotDotToken && createToken(SyntaxKind.DotDotDotToken),
+ // Clone name to remove trivia.
+ getSynthesizedClone(parameterDeclaration.name),
+ parameterDeclaration.questionToken && createToken(SyntaxKind.QuestionToken),
+ parameterTypeNode,
+ parameterDeclaration.initializer);
+ return parameterNode;
+ }
+
+ function symbolToName(symbol: Symbol, expectsIdentifier: true): Identifier;
+ function symbolToName(symbol: Symbol, expectsIdentifier: false): EntityName;
+ function symbolToName(symbol: Symbol, expectsIdentifier: boolean): EntityName {
+
+ // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
+ let chain: Symbol[];
+ const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter;
+ if (!isTypeParameter && context.enclosingDeclaration) {
+ chain = getSymbolChain(symbol, SymbolFlags.None, /*endOfChain*/ true);
+ Debug.assert(chain && chain.length > 0);
+ }
+ else {
+ chain = [symbol];
+ }
+
+ if (expectsIdentifier && chain.length !== 1
+ && !context.encounteredError
+ && !(context.flags & NodeBuilderFlags.allowQualifedNameInPlaceOfIdentifier)) {
+ context.encounteredError = true;
+ }
+ return createEntityNameFromSymbolChain(chain, chain.length - 1);
+
+ function createEntityNameFromSymbolChain(chain: Symbol[], index: number): EntityName {
+ Debug.assert(chain && 0 <= index && index < chain.length);
+ // const parentIndex = index - 1;
+ const symbol = chain[index];
+ let typeParameterString = "";
+ if (index > 0) {
+
+ const parentSymbol = chain[index - 1];
+ let typeParameters: TypeParameter[];
+ if (getCheckFlags(symbol) & CheckFlags.Instantiated) {
+ typeParameters = getTypeParametersOfClassOrInterface(parentSymbol);
+ }
+ else {
+ const targetSymbol = getTargetSymbol(parentSymbol);
+ if (targetSymbol.flags & (SymbolFlags.Class | SymbolFlags.Interface | SymbolFlags.TypeAlias)) {
+ typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
+ }
+ }
+ if (typeParameters && typeParameters.length > 0) {
+ if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowTypeParameterInQualifiedName)) {
+ context.encounteredError = true;
+ }
+ const writer = getSingleLineStringWriter();
+ const displayBuilder = getSymbolDisplayBuilder();
+ displayBuilder.buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, context.enclosingDeclaration, 0);
+ typeParameterString = writer.string();
+ releaseStringWriter(writer);
+
+ }
+ }
+ const symbolName = getNameOfSymbol(symbol);
+ const symbolNameWithTypeParameters = typeParameterString.length > 0 ? `${symbolName}<${typeParameterString}>` : symbolName;
+ const identifier = createIdentifier(symbolNameWithTypeParameters);
+
+ return index > 0 ? createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
+ }
+
+ /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
+ function getSymbolChain(symbol: Symbol, meaning: SymbolFlags, endOfChain: boolean): Symbol[] | undefined {
+ let accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/false);
+ let parentSymbol: Symbol;
+
+ if (!accessibleSymbolChain ||
+ needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
+
+ // Go up and add our parent.
+ const parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
+ if (parent) {
+ const parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
+ if (parentChain) {
+ parentSymbol = parent;
+ accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]);
+ }
+ }
+ }
+
+ if (accessibleSymbolChain) {
+ return accessibleSymbolChain;
+ }
+ if (
+ // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
+ endOfChain ||
+ // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
+ !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) &&
+ // If a parent symbol is an anonymous type, don't write it.
+ !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral))) {
+
+ return [symbol];
+ }
+ }
+
+ function getNameOfSymbol(symbol: Symbol): string {
+ const declaration = firstOrUndefined(symbol.declarations);
+ if (declaration) {
+ if (declaration.name) {
+ return declarationNameToString(declaration.name);
+ }
+ if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) {
+ return declarationNameToString((declaration.parent).name);
+ }
+ if (!context.encounteredError && !(context.flags & NodeBuilderFlags.allowAnonymousIdentifier)) {
+ context.encounteredError = true;
+ }
+ switch (declaration.kind) {
+ case SyntaxKind.ClassExpression:
+ return "(Anonymous class)";
+ case SyntaxKind.FunctionExpression:
+ case SyntaxKind.ArrowFunction:
+ return "(Anonymous function)";
+ }
+ }
+ return symbol.name;
+ }
+ }
+ }
+
function typePredicateToString(typePredicate: TypePredicate, enclosingDeclaration?: Declaration, flags?: TypeFormatFlags): string {
const writer = getSingleLineStringWriter();
getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags);
@@ -2456,6 +3048,7 @@ namespace ts {
}
}
+
function writeTypeList(types: Type[], delimiter: SyntaxKind) {
for (let i = 0; i < types.length; i++) {
if (i > 0) {
@@ -3983,14 +4576,15 @@ namespace ts {
return getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration);
}
- function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: TypeNode[]): Signature[] {
+ function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: TypeNode[], location: Node): Signature[] {
const typeArgCount = length(typeArgumentNodes);
+ const isJavaScript = isInJavaScriptFile(location);
return filter(getSignaturesOfType(type, SignatureKind.Construct),
- sig => typeArgCount >= getMinTypeArgumentCount(sig.typeParameters) && typeArgCount <= length(sig.typeParameters));
+ sig => (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters));
}
- function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: TypeNode[]): Signature[] {
- let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes);
+ function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: TypeNode[], location: Node): Signature[] {
+ let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
if (typeArgumentNodes) {
const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode);
signatures = map(signatures, sig => getSignatureInstantiation(sig, typeArguments));
@@ -4073,7 +4667,7 @@ namespace ts {
// The class derives from a "class-like" constructor function, check that we have at least one construct signature
// with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
// we check that all instantiated signatures return the same type.
- const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments);
+ const constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
if (!constructors.length) {
error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
return;
@@ -4583,14 +5177,15 @@ namespace ts {
return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)];
}
const baseTypeNode = getBaseTypeNodeOfClass(classType);
+ const isJavaScript = isInJavaScriptFile(baseTypeNode);
const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode);
const typeArgCount = length(typeArguments);
const result: Signature[] = [];
for (const baseSig of baseSignatures) {
const minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
const typeParamCount = length(baseSig.typeParameters);
- if (typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
- const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount)) : cloneSignature(baseSig);
+ if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) {
+ const sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig);
sig.typeParameters = classType.localTypeParameters;
sig.resolvedReturnType = classType;
result.push(sig);
@@ -5129,7 +5724,8 @@ namespace ts {
const excludeModifiers = isUnion ? ModifierFlags.NonPublicAccessibilityModifier : 0;
// Flags we want to propagate to the result if they exist in all source symbols
let commonFlags = isUnion ? SymbolFlags.None : SymbolFlags.Optional;
- let checkFlags = CheckFlags.SyntheticProperty;
+ let syntheticFlag = CheckFlags.SyntheticMethod;
+ let checkFlags = 0;
for (const current of types) {
const type = getApparentType(current);
if (type !== unknownType) {
@@ -5148,6 +5744,9 @@ namespace ts {
(modifiers & ModifierFlags.Protected ? CheckFlags.ContainsProtected : 0) |
(modifiers & ModifierFlags.Private ? CheckFlags.ContainsPrivate : 0) |
(modifiers & ModifierFlags.Static ? CheckFlags.ContainsStatic : 0);
+ if (!isMethodLike(prop)) {
+ syntheticFlag = CheckFlags.SyntheticProperty;
+ }
}
else if (isUnion) {
checkFlags |= CheckFlags.Partial;
@@ -5177,7 +5776,7 @@ namespace ts {
propTypes.push(type);
}
const result = createSymbol(SymbolFlags.Property | commonFlags, name);
- result.checkFlags = checkFlags;
+ result.checkFlags = syntheticFlag | checkFlags;
result.containingType = containingType;
result.declarations = declarations;
result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
@@ -5419,11 +6018,12 @@ namespace ts {
* @param typeParameters The requested type parameters.
* @param minTypeArgumentCount The minimum number of required type arguments.
*/
- function fillMissingTypeArguments(typeArguments: Type[] | undefined, typeParameters: TypeParameter[] | undefined, minTypeArgumentCount: number) {
+ function fillMissingTypeArguments(typeArguments: Type[] | undefined, typeParameters: TypeParameter[] | undefined, minTypeArgumentCount: number, location?: Node) {
const numTypeParameters = length(typeParameters);
if (numTypeParameters) {
const numTypeArguments = length(typeArguments);
- if (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters) {
+ const isJavaScript = isInJavaScriptFile(location);
+ if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) {
if (!typeArguments) {
typeArguments = [];
}
@@ -5432,12 +6032,12 @@ namespace ts {
// If a type parameter does not have a default type, or if the default type
// is a forward reference, the empty object type is used.
for (let i = numTypeArguments; i < numTypeParameters; i++) {
- typeArguments[i] = emptyObjectType;
+ typeArguments[i] = isJavaScript ? anyType : emptyObjectType;
}
for (let i = numTypeArguments; i < numTypeParameters; i++) {
const mapper = createTypeMapper(typeParameters, typeArguments);
const defaultType = getDefaultFromTypeParameter(typeParameters[i]);
- typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : emptyObjectType;
+ typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType;
}
}
}
@@ -5811,7 +6411,7 @@ namespace ts {
if (typeParameters) {
const numTypeArguments = length(node.typeArguments);
const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
- if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
+ if (!isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
error(node,
minTypeArgumentCount === typeParameters.length
? Diagnostics.Generic_type_0_requires_1_type_argument_s
@@ -5824,7 +6424,7 @@ namespace ts {
// In a type reference, the outer type parameters of the referenced class or interface are automatically
// supplied as type arguments and the type reference only specifies arguments for the local type parameters
// of the class or interface.
- const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount));
+ const typeArguments = concatenate(type.outerTypeParameters, fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, minTypeArgumentCount, node));
return createTypeReference(type, typeArguments);
}
if (node.typeArguments) {
@@ -7934,16 +8534,9 @@ namespace ts {
}
}
else if (target.flags & TypeFlags.IndexedAccess) {
- // if we have indexed access types with identical index types, see if relationship holds for
- // the two object types.
- if (source.flags & TypeFlags.IndexedAccess && (source).indexType === (target).indexType) {
- if (result = isRelatedTo((source).objectType, (target).objectType, reportErrors)) {
- return result;
- }
- }
// A type S is related to a type T[K] if S is related to A[K], where K is string-like and
// A is the apparent type of S.
- const constraint = getBaseConstraintOfType(target);
+ const constraint = getConstraintOfType(target);
if (constraint) {
if (result = isRelatedTo(source, constraint, reportErrors)) {
errorInfo = saveErrorInfo;
@@ -7990,6 +8583,13 @@ namespace ts {
return result;
}
}
+ else if (target.flags & TypeFlags.IndexedAccess && (source).indexType === (target).indexType) {
+ // if we have indexed access types with identical index types, see if relationship holds for
+ // the two object types.
+ if (result = isRelatedTo((source).objectType, (target).objectType, reportErrors)) {
+ return result;
+ }
+ }
}
else {
if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) {
@@ -8269,8 +8869,8 @@ namespace ts {
maybeStack[depth].set(id, RelationComparisonResult.Succeeded);
depth++;
const saveExpandingFlags = expandingFlags;
- if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) expandingFlags |= 1;
- if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2;
+ if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) expandingFlags |= 1;
+ if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= 2;
let result: Ternary;
if (expandingFlags === 3) {
result = Ternary.Maybe;
@@ -8636,7 +9236,7 @@ namespace ts {
// Invoke the callback for each underlying property symbol of the given symbol and return the first
// value that isn't undefined.
function forEachProperty(prop: Symbol, callback: (p: Symbol) => T): T {
- if (getCheckFlags(prop) & CheckFlags.SyntheticProperty) {
+ if (getCheckFlags(prop) & CheckFlags.Synthetic) {
for (const t of (prop).containingType.types) {
const p = getPropertyOfType(t, prop.name);
const result = p && forEachProperty(p, callback);
@@ -8690,21 +9290,23 @@ namespace ts {
return false;
}
- // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case
- // when structural type comparisons have been started for 10 or more instantiations of the same generic type. It is possible,
- // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely expanding.
- // Effectively, we will generate a false positive when two types are structurally equal to at least 10 levels, but unequal at
- // some level beyond that.
- function isDeeplyNestedGeneric(type: Type, stack: Type[], depth: number): boolean {
- // We track type references (created by createTypeReference) and instantiated types (created by instantiateType)
- if (getObjectFlags(type) & (ObjectFlags.Reference | ObjectFlags.Instantiated) && depth >= 5) {
+ // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
+ // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
+ // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
+ // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
+ // levels, but unequal at some level beyond that.
+ function isDeeplyNestedType(type: Type, stack: Type[], depth: number): boolean {
+ // We track all object types that have an associated symbol (representing the origin of the type)
+ if (depth >= 5 && type.flags & TypeFlags.Object) {
const symbol = type.symbol;
- let count = 0;
- for (let i = 0; i < depth; i++) {
- const t = stack[i];
- if (getObjectFlags(t) & (ObjectFlags.Reference | ObjectFlags.Instantiated) && t.symbol === symbol) {
- count++;
- if (count >= 5) return true;
+ if (symbol) {
+ let count = 0;
+ for (let i = 0; i < depth; i++) {
+ const t = stack[i];
+ if (t.flags & TypeFlags.Object && t.symbol === symbol) {
+ count++;
+ if (count >= 5) return true;
+ }
}
}
}
@@ -9447,7 +10049,7 @@ namespace ts {
if (isInProcess(source, target)) {
return;
}
- if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) {
+ if (isDeeplyNestedType(source, sourceStack, depth) && isDeeplyNestedType(target, targetStack, depth)) {
return;
}
const key = source.id + "," + target.id;
@@ -11336,8 +11938,8 @@ namespace ts {
// If this is a function in a JS file, it might be a class method. Check if it's the RHS
// of a x.prototype.y = function [name]() { .... }
if (container.kind === SyntaxKind.FunctionExpression &&
- isInJavaScriptFile(container.parent) &&
- getSpecialPropertyAssignmentKind(container.parent) === SpecialPropertyAssignmentKind.PrototypeProperty) {
+ container.parent.kind === SyntaxKind.BinaryExpression &&
+ getSpecialPropertyAssignmentKind(container.parent as BinaryExpression) === SpecialPropertyAssignmentKind.PrototypeProperty) {
// Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container')
const className = (((container.parent as BinaryExpression) // x.prototype.y = f
.left as PropertyAccessExpression) // x.prototype.y
@@ -12455,12 +13057,12 @@ namespace ts {
type.flags & TypeFlags.UnionOrIntersection && !forEach((type).types, t => !isValidSpreadType(t)));
}
- function checkJsxSelfClosingElement(node: JsxSelfClosingElement) {
+ function checkJsxSelfClosingElement(node: JsxSelfClosingElement): Type {
checkJsxOpeningLikeElement(node);
- return jsxElementType || anyType;
+ return getJsxGlobalElementType() || anyType;
}
- function checkJsxElement(node: JsxElement) {
+ function checkJsxElement(node: JsxElement): Type {
// Check attributes
checkJsxOpeningLikeElement(node.openingElement);
@@ -12487,7 +13089,7 @@ namespace ts {
}
}
- return jsxElementType || anyType;
+ return getJsxGlobalElementType() || anyType;
}
/**
@@ -12728,13 +13330,14 @@ namespace ts {
function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type {
Debug.assert(!(elementType.flags & TypeFlags.Union));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
- if (jsxElementType) {
+ const jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ if (jsxStatelessElementType) {
// We don't call getResolvedSignature here because we have already resolve the type of JSX Element.
const callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined);
if (callSignature !== unknownSignature) {
const callReturnType = callSignature && getReturnTypeOfSignature(callSignature);
let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0]));
- if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) {
+ if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
// Intersect in JSX.IntrinsicAttributes if it exists
const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes);
if (intrinsicAttributes !== unknownType) {
@@ -12762,7 +13365,8 @@ namespace ts {
Debug.assert(!(elementType.flags & TypeFlags.Union));
if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) {
// Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type
- if (jsxElementType) {
+ const jsxStatelessElementType = getJsxGlobalStatelessElementType();
+ if (jsxStatelessElementType) {
// We don't call getResolvedSignature because here we have already resolve the type of JSX Element.
const candidatesOutArray: Signature[] = [];
getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray);
@@ -12771,7 +13375,7 @@ namespace ts {
for (const candidate of candidatesOutArray) {
const callReturnType = getReturnTypeOfSignature(candidate);
const paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0]));
- if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) {
+ if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) {
let shouldBeCandidate = true;
for (const attribute of openingLikeElement.attributes.properties) {
if (isJsxAttribute(attribute) &&
@@ -13015,6 +13619,23 @@ namespace ts {
return deferredJsxElementClassType;
}
+ function getJsxGlobalElementType(): Type {
+ if (!deferredJsxElementType) {
+ deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element);
+ }
+ return deferredJsxElementType;
+ }
+
+ function getJsxGlobalStatelessElementType(): Type {
+ if (!deferredJsxStatelessElementType) {
+ const jsxElementType = getJsxGlobalElementType();
+ if (jsxElementType) {
+ deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]);
+ }
+ }
+ return deferredJsxStatelessElementType;
+ }
+
/**
* Returns all the properties of the Jsx.IntrinsicElements interface
*/
@@ -13029,7 +13650,7 @@ namespace ts {
error(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
}
- if (jsxElementType === undefined) {
+ if (getJsxGlobalElementType() === undefined) {
if (noImplicitAny) {
error(errorNode, Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
}
@@ -13118,7 +13739,7 @@ namespace ts {
const flags = getCombinedModifierFlags(s.valueDeclaration);
return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier;
}
- if (getCheckFlags(s) & CheckFlags.SyntheticProperty) {
+ if (getCheckFlags(s) & CheckFlags.Synthetic) {
const checkFlags = (s).checkFlags;
const accessModifier = checkFlags & CheckFlags.ContainsPrivate ? ModifierFlags.Private :
checkFlags & CheckFlags.ContainsPublic ? ModifierFlags.Public :
@@ -13136,6 +13757,10 @@ namespace ts {
return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0;
}
+ function isMethodLike(symbol: Symbol) {
+ return !!(symbol.flags & SymbolFlags.Method || getCheckFlags(symbol) & CheckFlags.SyntheticMethod);
+ }
+
/**
* Check whether the requested property access is valid.
* Returns true if node is a valid property access, and false otherwise.
@@ -13165,11 +13790,11 @@ namespace ts {
// where this references the constructor function object of a derived class,
// a super property access is permitted and must specify a public static member function of the base class.
if (languageVersion < ScriptTarget.ES2015) {
- const propKind = getDeclarationKindFromSymbol(prop);
- if (propKind !== SyntaxKind.MethodDeclaration && propKind !== SyntaxKind.MethodSignature) {
- // `prop` refers to a *property* declared in the super class
- // rather than a *method*, so it does not satisfy the above criteria.
-
+ const hasNonMethodDeclaration = forEachProperty(prop, p => {
+ const propKind = getDeclarationKindFromSymbol(p);
+ return propKind !== SyntaxKind.MethodDeclaration && propKind !== SyntaxKind.MethodSignature;
+ });
+ if (hasNonMethodDeclaration) {
error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
return false;
}
@@ -13320,10 +13945,17 @@ namespace ts {
}
return unknownType;
}
- if (prop.valueDeclaration &&
- isInPropertyInitializer(node) &&
- !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) {
- error(right, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text);
+ if (prop.valueDeclaration) {
+ if (isInPropertyInitializer(node) &&
+ !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) {
+ error(right, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text);
+ }
+ if (prop.valueDeclaration.kind === SyntaxKind.ClassDeclaration &&
+ node.parent && node.parent.kind !== SyntaxKind.TypeReference &&
+ !isInAmbientContext(prop.valueDeclaration) &&
+ !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) {
+ error(right, Diagnostics.Class_0_used_before_its_declaration, right.text);
+ }
}
markPropertyAsReferenced(prop);
@@ -14443,7 +15075,7 @@ namespace ts {
// with the type arguments specified in the extends clause.
const baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node));
if (baseTypeNode) {
- const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments);
+ const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
return resolveCall(node, baseConstructors, candidatesOutArray);
}
}
@@ -15138,8 +15770,8 @@ namespace ts {
else {
let types: Type[];
if (functionFlags & FunctionFlags.Generator) { // Generator or AsyncGenerator function
- types = checkAndAggregateYieldOperandTypes(func, checkMode);
- if (types.length === 0) {
+ types = concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode));
+ if (!types || types.length === 0) {
const iterableIteratorAny = functionFlags & FunctionFlags.Async
? createAsyncIterableIteratorType(anyType) // AsyncGenerator function
: createIterableIteratorType(anyType); // Generator function
@@ -18783,7 +19415,7 @@ namespace ts {
// unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
// in this case error about missing name is already reported - do not report extra one
- if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.Object | TypeFlags.TypeVariable)) {
+ if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.Object | TypeFlags.TypeVariable | TypeFlags.NonPrimitive)) {
error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter);
}
@@ -19552,7 +20184,7 @@ namespace ts {
}
function checkClassLikeDeclaration(node: ClassLikeDeclaration) {
- checkGrammarClassDeclarationHeritageClauses(node);
+ checkGrammarClassLikeDeclaration(node);
checkDecorators(node);
if (node.name) {
checkTypeNameIsReserved(node.name, Diagnostics.Class_name_cannot_be_0);
@@ -19590,7 +20222,7 @@ namespace ts {
checkSourceElement(baseTypeNode.expression);
if (baseTypeNode.typeArguments) {
forEach(baseTypeNode.typeArguments, checkSourceElement);
- for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments)) {
+ for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) {
if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) {
break;
}
@@ -19603,20 +20235,12 @@ namespace ts {
error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
}
- if (baseType.symbol && baseType.symbol.valueDeclaration &&
- !isInAmbientContext(baseType.symbol.valueDeclaration) &&
- baseType.symbol.valueDeclaration.kind === SyntaxKind.ClassDeclaration) {
- if (!isBlockScopedNameDeclaredBeforeUse(baseType.symbol.valueDeclaration, node)) {
- error(baseTypeNode, Diagnostics.A_class_must_be_declared_after_its_base_class);
- }
- }
-
if (!(staticBaseType.symbol && staticBaseType.symbol.flags & SymbolFlags.Class) && !(baseConstructorType.flags & TypeFlags.TypeVariable)) {
// When the static base type is a "class-like" constructor function (but not actually a class), we verify
// that all instantiated base constructor signatures return the same type. We can simply compare the type
// references (as opposed to checking the structure of the types) because elsewhere we have already checked
// that the base type is a class or interface type (and not, for example, an anonymous object type).
- const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments);
+ const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
if (forEach(constructors, sig => getReturnTypeOfSignature(sig) !== baseType)) {
error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type);
}
@@ -19736,7 +20360,7 @@ namespace ts {
else {
// derived overrides base.
const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived);
- if ((baseDeclarationFlags & ModifierFlags.Private) || (derivedDeclarationFlags & ModifierFlags.Private)) {
+ if (baseDeclarationFlags & ModifierFlags.Private || derivedDeclarationFlags & ModifierFlags.Private) {
// either base or derived property is private - not override, skip it
continue;
}
@@ -19746,28 +20370,24 @@ namespace ts {
continue;
}
- if ((base.flags & derived.flags & SymbolFlags.Method) || ((base.flags & SymbolFlags.PropertyOrAccessor) && (derived.flags & SymbolFlags.PropertyOrAccessor))) {
+ if (isMethodLike(base) && isMethodLike(derived) || base.flags & SymbolFlags.PropertyOrAccessor && derived.flags & SymbolFlags.PropertyOrAccessor) {
// method is overridden with method or property/accessor is overridden with property/accessor - correct case
continue;
}
let errorMessage: DiagnosticMessage;
- if (base.flags & SymbolFlags.Method) {
+ if (isMethodLike(base)) {
if (derived.flags & SymbolFlags.Accessor) {
errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
}
else {
- Debug.assert((derived.flags & SymbolFlags.Property) !== 0);
errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property;
}
}
else if (base.flags & SymbolFlags.Property) {
- Debug.assert((derived.flags & SymbolFlags.Method) !== 0);
errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
}
else {
- Debug.assert((base.flags & SymbolFlags.Accessor) !== 0);
- Debug.assert((derived.flags & SymbolFlags.Method) !== 0);
errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
}
@@ -21063,7 +21683,7 @@ namespace ts {
}
function getSpecialPropertyAssignmentSymbolFromEntityName(entityName: EntityName | PropertyAccessExpression) {
- const specialPropertyAssignmentKind = getSpecialPropertyAssignmentKind(entityName.parent.parent);
+ const specialPropertyAssignmentKind = getSpecialPropertyAssignmentKind(entityName.parent.parent as BinaryExpression);
switch (specialPropertyAssignmentKind) {
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.PrototypeProperty:
@@ -21426,7 +22046,7 @@ namespace ts {
}
function getRootSymbols(symbol: Symbol): Symbol[] {
- if (getCheckFlags(symbol) & CheckFlags.SyntheticProperty) {
+ if (getCheckFlags(symbol) & CheckFlags.Synthetic) {
const symbols: Symbol[] = [];
const name = symbol.name;
forEach(getSymbolLinks(symbol).containingType.types, t => {
@@ -22107,7 +22727,6 @@ namespace ts {
globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
- jsxElementType = getExportedTypeFromNamespace("JSX", JsxNames.Element);
anyArrayType = createArrayType(anyType);
autoArrayType = createArrayType(autoType);
@@ -22526,6 +23145,11 @@ namespace ts {
checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file);
}
+ function checkGrammarClassLikeDeclaration(node: ClassLikeDeclaration): boolean {
+ const file = getSourceFileOfNode(node);
+ return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
+ }
+
function checkGrammarArrowFunction(node: FunctionLikeDeclaration, file: SourceFile): boolean {
if (node.kind === SyntaxKind.ArrowFunction) {
const arrowFunction = node;
diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts
index 6c88af845ee..d84bdb5c405 100644
--- a/src/compiler/commandLineParser.ts
+++ b/src/compiler/commandLineParser.ts
@@ -9,40 +9,13 @@ namespace ts {
export const compileOnSaveCommandLineOption: CommandLineOption = { name: "compileOnSave", type: "boolean" };
/* @internal */
export const optionDeclarations: CommandLineOption[] = [
- {
- name: "charset",
- type: "string",
- },
- compileOnSaveCommandLineOption,
- {
- name: "declaration",
- shortName: "d",
- type: "boolean",
- description: Diagnostics.Generates_corresponding_d_ts_file,
- },
- {
- name: "declarationDir",
- type: "string",
- isFilePath: true,
- paramType: Diagnostics.DIRECTORY,
- },
- {
- name: "diagnostics",
- type: "boolean",
- },
- {
- name: "extendedDiagnostics",
- type: "boolean",
- experimental: true
- },
- {
- name: "emitBOM",
- type: "boolean"
- },
+ // CommandLine only options
{
name: "help",
shortName: "h",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
description: Diagnostics.Print_this_message,
},
{
@@ -50,53 +23,71 @@ namespace ts {
shortName: "?",
type: "boolean"
},
+ {
+ name: "all",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
+ description: Diagnostics.Show_all_compiler_options,
+ },
+ {
+ name: "version",
+ shortName: "v",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
+ description: Diagnostics.Print_the_compiler_s_version,
+ },
{
name: "init",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
},
{
- name: "inlineSourceMap",
- type: "boolean",
- },
- {
- name: "inlineSources",
- type: "boolean",
- },
- {
- name: "jsx",
- type: createMapFromTemplate({
- "preserve": JsxEmit.Preserve,
- "react-native": JsxEmit.ReactNative,
- "react": JsxEmit.React
- }),
- paramType: Diagnostics.KIND,
- description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
- },
- {
- name: "reactNamespace",
- type: "string",
- description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
- },
- {
- name: "jsxFactory",
- type: "string",
- description: Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
- },
- {
- name: "listFiles",
- type: "boolean",
- },
- {
- name: "locale",
- type: "string",
- },
- {
- name: "mapRoot",
+ name: "project",
+ shortName: "p",
type: "string",
isFilePath: true,
- description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
- paramType: Diagnostics.LOCATION,
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
+ paramType: Diagnostics.FILE_OR_DIRECTORY,
+ description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
+ },
+ {
+ name: "pretty",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
+ description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
+ },
+ {
+ name: "watch",
+ shortName: "w",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Command_line_Options,
+ description: Diagnostics.Watch_input_files,
+ },
+
+ // Basic
+ {
+ name: "target",
+ shortName: "t",
+ type: createMapFromTemplate({
+ "es3": ScriptTarget.ES3,
+ "es5": ScriptTarget.ES5,
+ "es6": ScriptTarget.ES2015,
+ "es2015": ScriptTarget.ES2015,
+ "es2016": ScriptTarget.ES2016,
+ "es2017": ScriptTarget.ES2017,
+ "esnext": ScriptTarget.ESNext,
+ }),
+ paramType: Diagnostics.VERSION,
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT,
},
{
name: "module",
@@ -111,305 +102,10 @@ namespace ts {
"es2015": ModuleKind.ES2015,
"es2018": ModuleKind.ES2018
}),
- description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_es2015_or_es2018,
paramType: Diagnostics.KIND,
- },
- {
- name: "newLine",
- type: createMapFromTemplate({
- "crlf": NewLineKind.CarriageReturnLineFeed,
- "lf": NewLineKind.LineFeed
- }),
- description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
- paramType: Diagnostics.NEWLINE,
- },
- {
- name: "noEmit",
- type: "boolean",
- description: Diagnostics.Do_not_emit_outputs,
- },
- {
- name: "noEmitHelpers",
- type: "boolean"
- },
- {
- name: "noEmitOnError",
- type: "boolean",
- description: Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
- },
- {
- name: "noErrorTruncation",
- type: "boolean"
- },
- {
- name: "noImplicitAny",
- type: "boolean",
- description: Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
- },
- {
- name: "noImplicitThis",
- type: "boolean",
- description: Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
- },
- {
- name: "noUnusedLocals",
- type: "boolean",
- description: Diagnostics.Report_errors_on_unused_locals,
- },
- {
- name: "noUnusedParameters",
- type: "boolean",
- description: Diagnostics.Report_errors_on_unused_parameters,
- },
- {
- name: "noLib",
- type: "boolean",
- },
- {
- name: "noResolve",
- type: "boolean",
- },
- {
- name: "skipDefaultLibCheck",
- type: "boolean",
- },
- {
- name: "skipLibCheck",
- type: "boolean",
- description: Diagnostics.Skip_type_checking_of_declaration_files,
- },
- {
- name: "out",
- type: "string",
- isFilePath: false, // This is intentionally broken to support compatability with existing tsconfig files
- // for correct behaviour, please use outFile
- paramType: Diagnostics.FILE,
- },
- {
- name: "outFile",
- type: "string",
- isFilePath: true,
- description: Diagnostics.Concatenate_and_emit_output_to_single_file,
- paramType: Diagnostics.FILE,
- },
- {
- name: "outDir",
- type: "string",
- isFilePath: true,
- description: Diagnostics.Redirect_output_structure_to_the_directory,
- paramType: Diagnostics.DIRECTORY,
- },
- {
- name: "preserveConstEnums",
- type: "boolean",
- description: Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
- },
- {
- name: "pretty",
- description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental,
- type: "boolean"
- },
- {
- name: "project",
- shortName: "p",
- type: "string",
- isFilePath: true,
- description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
- paramType: Diagnostics.FILE_OR_DIRECTORY
- },
- {
- name: "removeComments",
- type: "boolean",
- description: Diagnostics.Do_not_emit_comments_to_output,
- },
- {
- name: "rootDir",
- type: "string",
- isFilePath: true,
- paramType: Diagnostics.LOCATION,
- description: Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
- },
- {
- name: "isolatedModules",
- type: "boolean",
- },
- {
- name: "sourceMap",
- type: "boolean",
- description: Diagnostics.Generates_corresponding_map_file,
- },
- {
- name: "sourceRoot",
- type: "string",
- isFilePath: true,
- description: Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
- paramType: Diagnostics.LOCATION,
- },
- {
- name: "suppressExcessPropertyErrors",
- type: "boolean",
- description: Diagnostics.Suppress_excess_property_checks_for_object_literals,
- experimental: true
- },
- {
- name: "suppressImplicitAnyIndexErrors",
- type: "boolean",
- description: Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
- },
- {
- name: "stripInternal",
- type: "boolean",
- description: Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
- experimental: true
- },
- {
- name: "target",
- shortName: "t",
- type: createMapFromTemplate({
- "es3": ScriptTarget.ES3,
- "es5": ScriptTarget.ES5,
- "es6": ScriptTarget.ES2015,
- "es2015": ScriptTarget.ES2015,
- "es2016": ScriptTarget.ES2016,
- "es2017": ScriptTarget.ES2017,
- "esnext": ScriptTarget.ESNext,
- }),
- description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT,
- paramType: Diagnostics.VERSION,
- },
- {
- name: "version",
- shortName: "v",
- type: "boolean",
- description: Diagnostics.Print_the_compiler_s_version,
- },
- {
- name: "watch",
- shortName: "w",
- type: "boolean",
- description: Diagnostics.Watch_input_files,
- },
- {
- name: "experimentalDecorators",
- type: "boolean",
- description: Diagnostics.Enables_experimental_support_for_ES7_decorators
- },
- {
- name: "emitDecoratorMetadata",
- type: "boolean",
- experimental: true,
- description: Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
- },
- {
- name: "moduleResolution",
- type: createMapFromTemplate({
- "node": ModuleResolutionKind.NodeJs,
- "classic": ModuleResolutionKind.Classic,
- }),
- description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
- paramType: Diagnostics.STRATEGY,
- },
- {
- name: "allowUnusedLabels",
- type: "boolean",
- description: Diagnostics.Do_not_report_errors_on_unused_labels
- },
- {
- name: "noImplicitReturns",
- type: "boolean",
- description: Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
- },
- {
- name: "noFallthroughCasesInSwitch",
- type: "boolean",
- description: Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
- },
- {
- name: "allowUnreachableCode",
- type: "boolean",
- description: Diagnostics.Do_not_report_errors_on_unreachable_code
- },
- {
- name: "forceConsistentCasingInFileNames",
- type: "boolean",
- description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
- },
- {
- name: "downlevelIteration",
- type: "boolean",
- description: Diagnostics.Use_full_down_level_iteration_for_iterables_and_arrays_for_for_of_spread_and_destructuring_in_ES5_Slash3
- },
- {
- name: "baseUrl",
- type: "string",
- isFilePath: true,
- description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names
- },
- {
- // this option can only be specified in tsconfig.json
- // use type = object to copy the value as-is
- name: "paths",
- type: "object",
- isTSConfigOnly: true
- },
- {
- // this option can only be specified in tsconfig.json
- // use type = object to copy the value as-is
- name: "rootDirs",
- type: "list",
- isTSConfigOnly: true,
- element: {
- name: "rootDirs",
- type: "string",
- isFilePath: true
- }
- },
- {
- name: "typeRoots",
- type: "list",
- element: {
- name: "typeRoots",
- type: "string",
- isFilePath: true
- }
- },
- {
- name: "types",
- type: "list",
- element: {
- name: "types",
- type: "string"
- },
- description: Diagnostics.Type_declaration_files_to_be_included_in_compilation
- },
- {
- name: "traceResolution",
- type: "boolean",
- description: Diagnostics.Enable_tracing_of_the_name_resolution_process
- },
- {
- name: "allowJs",
- type: "boolean",
- description: Diagnostics.Allow_javascript_files_to_be_compiled
- },
- {
- 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
- },
- {
- name: "maxNodeModuleJsDepth",
- type: "number",
- description: Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
- },
- {
- name: "listEmittedFiles",
- type: "boolean"
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_es2015_or_es2018,
},
{
name: "lib",
@@ -447,31 +143,481 @@ namespace ts {
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
}),
},
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
},
{
- name: "disableSizeLimit",
- type: "boolean"
+ name: "allowJs",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Allow_javascript_files_to_be_compiled
},
{
- name: "strictNullChecks",
+ name: "checkJs",
type: "boolean",
- description: Diagnostics.Enable_strict_null_checks
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Report_errors_in_js_files
+ },
+ {
+ name: "jsx",
+ type: createMapFromTemplate({
+ "preserve": JsxEmit.Preserve,
+ "react-native": JsxEmit.ReactNative,
+ "react": JsxEmit.React
+ }),
+ paramType: Diagnostics.KIND,
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
+ },
+ {
+ name: "declaration",
+ shortName: "d",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Generates_corresponding_d_ts_file,
+ },
+ {
+ name: "sourceMap",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Generates_corresponding_map_file,
+ },
+ {
+ name: "outFile",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.FILE,
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Concatenate_and_emit_output_to_single_file,
+ },
+ {
+ name: "outDir",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.DIRECTORY,
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Redirect_output_structure_to_the_directory,
+ },
+ {
+ name: "rootDir",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.LOCATION,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
+ },
+ {
+ name: "removeComments",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Do_not_emit_comments_to_output,
+ },
+ {
+ name: "noEmit",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Do_not_emit_outputs,
},
{
name: "importHelpers",
type: "boolean",
+ category: Diagnostics.Basic_Options,
description: Diagnostics.Import_emit_helpers_from_tslib
},
+ {
+ name: "downlevelIteration",
+ type: "boolean",
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
+ },
+ {
+ name: "isolatedModules",
+ type: "boolean",
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule
+ },
+
+ // Strict Type Checks
+ {
+ name: "strict",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Strict_Type_Checking_Options,
+ description: Diagnostics.Enable_all_strict_type_checking_options
+ },
+ {
+ name: "noImplicitAny",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Strict_Type_Checking_Options,
+ description: Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
+ },
+ {
+ name: "strictNullChecks",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Strict_Type_Checking_Options,
+ description: Diagnostics.Enable_strict_null_checks
+ },
+ {
+ name: "noImplicitThis",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Strict_Type_Checking_Options,
+ description: Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
+ },
{
name: "alwaysStrict",
type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Strict_Type_Checking_Options,
description: Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
},
+
+ // Additional Checks
{
- name: "strict",
+ name: "noUnusedLocals",
type: "boolean",
- description: Diagnostics.Enable_all_strict_type_checks
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Additional_Checks,
+ description: Diagnostics.Report_errors_on_unused_locals,
+ },
+ {
+ name: "noUnusedParameters",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Additional_Checks,
+ description: Diagnostics.Report_errors_on_unused_parameters,
+ },
+ {
+ name: "noImplicitReturns",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Additional_Checks,
+ description: Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
+ },
+ {
+ name: "noFallthroughCasesInSwitch",
+ type: "boolean",
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Additional_Checks,
+ description: Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
+ },
+
+ // Module Resolution
+ {
+ name: "moduleResolution",
+ type: createMapFromTemplate({
+ "node": ModuleResolutionKind.NodeJs,
+ "classic": ModuleResolutionKind.Classic,
+ }),
+ paramType: Diagnostics.STRATEGY,
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
+ },
+ {
+ name: "baseUrl",
+ type: "string",
+ isFilePath: true,
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names
+ },
+ {
+ // this option can only be specified in tsconfig.json
+ // use type = object to copy the value as-is
+ name: "paths",
+ type: "object",
+ isTSConfigOnly: true,
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl
+
+ },
+ {
+ // this option can only be specified in tsconfig.json
+ // use type = object to copy the value as-is
+ name: "rootDirs",
+ type: "list",
+ isTSConfigOnly: true,
+ element: {
+ name: "rootDirs",
+ type: "string",
+ isFilePath: true
+ },
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime
+ },
+ {
+ name: "typeRoots",
+ type: "list",
+ element: {
+ name: "typeRoots",
+ type: "string",
+ isFilePath: true
+ },
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.List_of_folders_to_include_type_definitions_from
+ },
+ {
+ name: "types",
+ type: "list",
+ element: {
+ name: "types",
+ type: "string"
+ },
+ showInSimplifiedHelpView: true,
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.Type_declaration_files_to_be_included_in_compilation
+ },
+ {
+ name: "allowSyntheticDefaultImports",
+ type: "boolean",
+ category: Diagnostics.Module_Resolution_Options,
+ description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
+ },
+
+ // Source Maps
+ {
+ name: "sourceRoot",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.LOCATION,
+ category: Diagnostics.Source_Map_Options,
+ description: Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
+ },
+ {
+ name: "mapRoot",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.LOCATION,
+ category: Diagnostics.Source_Map_Options,
+ description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
+ },
+ {
+ name: "inlineSourceMap",
+ type: "boolean",
+ category: Diagnostics.Source_Map_Options,
+ description: Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
+ },
+ {
+ name: "inlineSources",
+ type: "boolean",
+ category: Diagnostics.Source_Map_Options,
+ description: Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
+ },
+
+ // Experimental
+ {
+ name: "experimentalDecorators",
+ type: "boolean",
+ category: Diagnostics.Experimental_Options,
+ description: Diagnostics.Enables_experimental_support_for_ES7_decorators
+ },
+ {
+ name: "emitDecoratorMetadata",
+ type: "boolean",
+ category: Diagnostics.Experimental_Options,
+ description: Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
+ },
+
+ // Advanced
+ {
+ name: "jsxFactory",
+ type: "string",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
+ },
+ {
+ name: "diagnostics",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Show_diagnostic_information
+ },
+ {
+ name: "extendedDiagnostics",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Show_verbose_diagnostic_information
+ },
+ {
+ name: "traceResolution",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Enable_tracing_of_the_name_resolution_process
+ },
+ {
+ name: "listFiles",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Print_names_of_files_part_of_the_compilation
+ },
+ {
+ name: "listEmittedFiles",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation
+ },
+
+ {
+ name: "out",
+ type: "string",
+ isFilePath: false, // This is intentionally broken to support compatability with existing tsconfig files
+ // for correct behaviour, please use outFile
+ category: Diagnostics.Advanced_Options,
+ paramType: Diagnostics.FILE,
+ description: Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
+ },
+ {
+ name: "reactNamespace",
+ type: "string",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
+ },
+ {
+ name: "skipDefaultLibCheck",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
+ },
+ {
+ name: "charset",
+ type: "string",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.The_character_set_of_the_input_files
+ },
+ {
+ name: "emitBOM",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
+ },
+ {
+ name: "locale",
+ type: "string",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
+ },
+ {
+ name: "newLine",
+ type: createMapFromTemplate({
+ "crlf": NewLineKind.CarriageReturnLineFeed,
+ "lf": NewLineKind.LineFeed
+ }),
+ paramType: Diagnostics.NEWLINE,
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
+ },
+ {
+ name: "noErrorTruncation",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_truncate_error_messages
+ },
+ {
+ name: "noLib",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_include_the_default_library_file_lib_d_ts
+ },
+ {
+ name: "noResolve",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files
+ },
+ {
+ name: "stripInternal",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
+ },
+ {
+ name: "disableSizeLimit",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Disable_size_limitations_on_JavaScript_projects
+ },
+ {
+ name: "noImplicitUseStrict",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
+ },
+ {
+ name: "noEmitHelpers",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
+ },
+ {
+ name: "noEmitOnError",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
+ },
+ {
+ name: "preserveConstEnums",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
+ },
+ {
+ name: "declarationDir",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.DIRECTORY,
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Output_directory_for_generated_declaration_files
+ },
+ {
+ name: "skipLibCheck",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Skip_type_checking_of_declaration_files,
+ },
+ {
+ name: "allowUnusedLabels",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_report_errors_on_unused_labels
+ },
+ {
+ name: "allowUnreachableCode",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Do_not_report_errors_on_unreachable_code
+ },
+ {
+ name: "suppressExcessPropertyErrors",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Suppress_excess_property_checks_for_object_literals,
+ },
+ {
+ name: "suppressImplicitAnyIndexErrors",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
+ },
+ {
+ name: "forceConsistentCasingInFileNames",
+ type: "boolean",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
+ },
+ {
+ name: "maxNodeModuleJsDepth",
+ type: "number",
+ category: Diagnostics.Advanced_Options,
+ description: Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
},
{
// A list of plugins to load in the language service
@@ -481,7 +627,8 @@ namespace ts {
element: {
name: "plugin",
type: "object"
- }
+ },
+ description: Diagnostics.List_of_language_service_plugins
}
];
@@ -526,8 +673,7 @@ namespace ts {
export const defaultInitCompilerOptions: CompilerOptions = {
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
- strict: true,
- sourceMap: false,
+ strict: true
};
let optionNameMapCache: OptionNameMap;
@@ -750,9 +896,9 @@ namespace ts {
* @param fileNames array of filenames to be generated into tsconfig.json
*/
/* @internal */
- export function generateTSConfig(options: CompilerOptions, fileNames: string[]): { compilerOptions: MapLike } {
+ export function generateTSConfig(options: CompilerOptions, fileNames: string[]): string {
const compilerOptions = extend(options, defaultInitCompilerOptions);
- const configurations: any = {
+ const configurations: { compilerOptions: MapLike; files?: string[] } = {
compilerOptions: serializeCompilerOptions(compilerOptions)
};
if (fileNames && fileNames.length) {
@@ -760,7 +906,8 @@ namespace ts {
configurations.files = fileNames;
}
- return configurations;
+
+ return writeConfigurations();
function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined {
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
@@ -792,43 +939,123 @@ namespace ts {
if (hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
- switch (name) {
- case "init":
- case "watch":
- case "version":
- case "help":
- case "project":
- break;
- default:
- const value = options[name];
- const optionDefinition = optionsNameMap.get(name.toLowerCase());
- if (optionDefinition) {
- const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
- if (!customTypeMap) {
- // There is no map associated with this compiler option then use the value as-is
- // This is the case if the value is expect to be string, number, boolean or list of string
- result[name] = value;
- }
- else {
- if (optionDefinition.type === "list") {
- const convertedValue: string[] = [];
- for (const element of value as (string | number)[]) {
- convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
- }
- result[name] = convertedValue;
- }
- else {
- // There is a typeMap associated with this command-line option so use it to map value back to its name
- result[name] = getNameOfCompilerOptionValue(value, customTypeMap);
- }
+ if (optionsNameMap.has(name) && optionsNameMap.get(name).category === Diagnostics.Command_line_Options) {
+ continue;
+ }
+ const value = options[name];
+ const optionDefinition = optionsNameMap.get(name.toLowerCase());
+ if (optionDefinition) {
+ const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
+ if (!customTypeMap) {
+ // There is no map associated with this compiler option then use the value as-is
+ // This is the case if the value is expect to be string, number, boolean or list of string
+ result[name] = value;
+ }
+ else {
+ if (optionDefinition.type === "list") {
+ const convertedValue: string[] = [];
+ for (const element of value as (string | number)[]) {
+ convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
}
+ result[name] = convertedValue;
}
- break;
+ else {
+ // There is a typeMap associated with this command-line option so use it to map value back to its name
+ result[name] = getNameOfCompilerOptionValue(value, customTypeMap);
+ }
+ }
}
}
}
return result;
}
+
+ function getDefaultValueForOption(option: CommandLineOption) {
+ switch (option.type) {
+ case "number":
+ return 1;
+ case "boolean":
+ return true;
+ case "string":
+ return option.isFilePath ? "./" : "";
+ case "list":
+ return [];
+ case "object":
+ return {};
+ default:
+ return arrayFrom((option).type.keys())[0];
+ }
+ }
+
+ function makePadding(paddingLength: number): string {
+ return Array(paddingLength + 1).join(" ");
+ }
+
+ function writeConfigurations() {
+ // Filter applicable options to place in the file
+ const categorizedOptions = reduceLeft(
+ filter(optionDeclarations, o => o.category !== Diagnostics.Command_line_Options && o.category !== Diagnostics.Advanced_Options),
+ (memo, value) => {
+ if (value.category) {
+ const name = getLocaleSpecificMessage(value.category);
+ (memo[name] || (memo[name] = [])).push(value);
+ }
+ return memo;
+ }, >{});
+
+ // Serialize all options and thier descriptions
+ let marginLength = 0;
+ let seenKnownKeys = 0;
+ const nameColumn: string[] = [];
+ const descriptionColumn: string[] = [];
+ const knownKesyCount = getOwnKeys(configurations.compilerOptions).length;
+ for (const category in categorizedOptions) {
+ if (nameColumn.length !== 0) {
+ nameColumn.push("");
+ descriptionColumn.push("");
+ }
+ nameColumn.push(`/* ${category} */`);
+ descriptionColumn.push("");
+ for (const option of categorizedOptions[category]) {
+ let optionName;
+ if (hasProperty(configurations.compilerOptions, option.name)) {
+ optionName = `"${option.name}": ${JSON.stringify(configurations.compilerOptions[option.name])}${(seenKnownKeys += 1) === knownKesyCount ? "" : ","}`;
+ }
+ else {
+ optionName = `// "${option.name}": ${JSON.stringify(getDefaultValueForOption(option))},`;
+ }
+ nameColumn.push(optionName);
+ descriptionColumn.push(`/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */`);
+ marginLength = Math.max(optionName.length, marginLength);
+ }
+ }
+
+ // Write the output
+ const tab = makePadding(2);
+ const result: string[] = [];
+ result.push(`{`);
+ result.push(`${tab}"compilerOptions": {`);
+ // Print out each row, aligning all the descriptions on the same column.
+ for (let i = 0; i < nameColumn.length; i++) {
+ const optionName = nameColumn[i];
+ const description = descriptionColumn[i];
+ result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description);
+ }
+ if (configurations.files && configurations.files.length) {
+ result.push(`${tab}},`);
+ result.push(`${tab}"files": [`);
+ for (let i = 0; i < configurations.files.length; i++) {
+ result.push(`${tab}${tab}${JSON.stringify(configurations.files[i])}${i === configurations.files.length - 1 ? "" : ","}`);
+ }
+ result.push(`${tab}]`);
+ }
+ else {
+ result.push(`${tab}}`);
+ }
+ result.push(`}`);
+
+ return result.join(sys.newLine);
+ }
}
/**
@@ -1431,4 +1658,4 @@ namespace ts {
function caseInsensitiveKeyMapper(key: string) {
return key.toLowerCase();
}
-}
+}
\ No newline at end of file
diff --git a/src/compiler/core.ts b/src/compiler/core.ts
index c380a39611d..a56f1004d28 100644
--- a/src/compiler/core.ts
+++ b/src/compiler/core.ts
@@ -2360,4 +2360,8 @@ namespace ts {
return Extension.Jsx;
}
}
+
+ export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions) {
+ return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
+ }
}
diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json
index 66731bfaf88..545c2011d6f 100644
--- a/src/compiler/diagnosticMessages.json
+++ b/src/compiler/diagnosticMessages.json
@@ -1452,6 +1452,14 @@
"category": "Error",
"code": 2448
},
+ "Class '{0}' used before its declaration.": {
+ "category": "Error",
+ "code": 2449
+ },
+ "Enum '{0}' used before its declaration.": {
+ "category": "Error",
+ "code": 2450
+ },
"Cannot redeclare block-scoped variable '{0}'.": {
"category": "Error",
"code": 2451
@@ -2032,10 +2040,6 @@
"category": "Error",
"code": 2689
},
- "A class must be declared after its base class.": {
- "category": "Error",
- "code": 2690
- },
"An import path cannot end with a '{0}' extension. Consider importing '{1}' instead.": {
"category": "Error",
"code": 2691
@@ -2434,10 +2438,6 @@
"category": "Error",
"code": 5012
},
- "Unsupported file encoding.": {
- "category": "Error",
- "code": 5013
- },
"Failed to parse file '{0}': {1}.": {
"category": "Error",
"code": 5014
@@ -2806,7 +2806,7 @@
"category": "Message",
"code": 6083
},
- "Specify the object invoked for createElement and __spread when targeting 'react' JSX emit.": {
+ "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit": {
"category": "Message",
"code": 6084
},
@@ -3062,14 +3062,139 @@
"category": "Message",
"code": 6148
},
- "Use full down-level iteration for iterables and arrays for 'for-of', spread, and destructuring in ES5/3.": {
+ "Show diagnostic information.": {
"category": "Message",
"code": 6149
},
- "Enable all strict type checks.": {
+ "Show verbose diagnostic information.": {
"category": "Message",
"code": 6150
},
+ "Emit a single file with source maps instead of having a separate file.": {
+ "category": "Message",
+ "code": 6151
+ },
+ "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set.": {
+ "category": "Message",
+ "code": 6152
+ },
+ "Transpile each file as a separate module (similar to 'ts.transpileModule').": {
+ "category": "Message",
+ "code": 6153
+ },
+ "Print names of generated files part of the compilation.": {
+ "category": "Message",
+ "code": 6154
+ },
+ "Print names of files part of the compilation.": {
+ "category": "Message",
+ "code": 6155
+ },
+ "The locale used when displaying messages to the user (e.g. 'en-us')": {
+ "category": "Message",
+ "code": 6156
+ },
+ "Do not generate custom helper functions like '__extends' in compiled output.": {
+ "category": "Message",
+ "code": 6157
+ },
+ "Do not include the default library file (lib.d.ts).": {
+ "category": "Message",
+ "code": 6158
+ },
+ "Do not add triple-slash references or imported modules to the list of compiled files.": {
+ "category": "Message",
+ "code": 6159
+ },
+ "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files.": {
+ "category": "Message",
+ "code": 6160
+ },
+ "List of folders to include type definitions from.": {
+ "category": "Message",
+ "code": 6161
+ },
+ "Disable size limitations on JavaScript projects.": {
+ "category": "Message",
+ "code": 6162
+ },
+ "The character set of the input files.": {
+ "category": "Message",
+ "code": 6163
+ },
+ "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.": {
+ "category": "Message",
+ "code": 6164
+ },
+ "Do not truncate error messages.": {
+ "category": "Message",
+ "code": 6165
+ },
+ "Output directory for generated declaration files.": {
+ "category": "Message",
+ "code": 6166
+ },
+ "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'.": {
+ "category": "Message",
+ "code": 6167
+ },
+ "List of root folders whose combined content represents the structure of the project at runtime.": {
+ "category": "Message",
+ "code": 6168
+ },
+ "Show all compiler options.": {
+ "category": "Message",
+ "code": 6169
+ },
+ "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file": {
+ "category": "Message",
+ "code": 6170
+ },
+ "Command-line Options": {
+ "category": "Message",
+ "code": 6171
+ },
+ "Basic Options": {
+ "category": "Message",
+ "code": 6172
+ },
+ "Strict Type-Checking Options": {
+ "category": "Message",
+ "code": 6173
+ },
+ "Module Resolution Options": {
+ "category": "Message",
+ "code": 6174
+ },
+ "Source Map Options": {
+ "category": "Message",
+ "code": 6175
+ },
+ "Additional Checks": {
+ "category": "Message",
+ "code": 6176
+ },
+ "Experimental Options": {
+ "category": "Message",
+ "code": 6177
+ },
+ "Advanced Options": {
+ "category": "Message",
+ "code": 6178
+ },
+ "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'.": {
+ "category": "Message",
+ "code": 6179
+ },
+ "Enable all strict type-checking options.": {
+ "category": "Message",
+ "code": 6180
+ },
+ "List of language service plugins.": {
+ "category": "Message",
+ "code": 6181
+ },
+
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -3381,6 +3506,24 @@
"category": "Message",
"code": 90017
},
+ "Disable checking for this file.": {
+ "category": "Message",
+ "code": 90018
+ },
+ "Ignore this error message.": {
+ "category": "Message",
+ "code": 90019
+ },
+ "Initialize property '{0}' in the constructor.": {
+ "category": "Message",
+ "code": 90020
+ },
+ "Initialize static property '{0}'.": {
+ "category": "Message",
+ "code": 90021
+ },
+
+
"Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": {
"category": "Error",
"code": 8017
@@ -3388,5 +3531,9 @@
"Octal literals are not allowed in enums members initializer. Use the syntax '{0}'.": {
"category": "Error",
"code": 8018
+ },
+ "Report errors in .js files.": {
+ "category": "Message",
+ "code": 8019
}
}
diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts
index c9cd941c7fc..5553d5ee66a 100644
--- a/src/compiler/emitter.ts
+++ b/src/compiler/emitter.ts
@@ -199,6 +199,8 @@ namespace ts {
onEmitHelpers,
onSetSourceFile,
substituteNode,
+ onBeforeEmitNodeArray,
+ onAfterEmitNodeArray
} = handlers;
const newLine = getNewLineCharacter(printerOptions);
@@ -631,6 +633,11 @@ namespace ts {
if (isExpression(node)) {
return pipelineEmitExpression(trySubstituteNode(EmitHint.Expression, node));
}
+
+ if (isToken(node)) {
+ writeTokenText(kind);
+ return;
+ }
}
function pipelineEmitExpression(node: Node): void {
@@ -1554,6 +1561,10 @@ namespace ts {
emitSignatureAndBody(node, emitSignatureHead);
}
+ function emitBlockCallback(_hint: EmitHint, body: Node): void {
+ emitBlockFunctionBody(body);
+ }
+
function emitSignatureAndBody(node: FunctionLikeDeclaration, emitSignatureHead: (node: SignatureDeclaration) => void) {
const body = node.body;
if (body) {
@@ -1565,12 +1576,22 @@ namespace ts {
if (getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) {
emitSignatureHead(node);
- emitBlockFunctionBody(body);
+ if (onEmitNode) {
+ onEmitNode(EmitHint.Unspecified, body, emitBlockCallback);
+ }
+ else {
+ emitBlockFunctionBody(body);
+ }
}
else {
pushNameGenerationScope();
emitSignatureHead(node);
- emitBlockFunctionBody(body);
+ if (onEmitNode) {
+ onEmitNode(EmitHint.Unspecified, body, emitBlockCallback);
+ }
+ else {
+ emitBlockFunctionBody(body);
+ }
popNameGenerationScope();
}
@@ -2201,6 +2222,10 @@ namespace ts {
write(getOpeningBracket(format));
}
+ if (onBeforeEmitNodeArray) {
+ onBeforeEmitNodeArray(children);
+ }
+
if (isEmpty) {
// Write a line terminator if the parent node was multi-line
if (format & ListFormat.MultiLine) {
@@ -2316,6 +2341,10 @@ namespace ts {
}
}
+ if (onAfterEmitNodeArray) {
+ onAfterEmitNodeArray(children);
+ }
+
if (format & ListFormat.BracketsMask) {
write(getClosingBracket(format));
}
diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts
index 3ff3bc2782f..66b3eb713e5 100644
--- a/src/compiler/factory.ts
+++ b/src/compiler/factory.ts
@@ -45,7 +45,7 @@ namespace ts {
* Creates a shallow, memberwise clone of a node with no source map location.
*/
/* @internal */
- export function getSynthesizedClone(node: T): T {
+ export function getSynthesizedClone(node: T | undefined): T {
// We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
// the original node. We also need to exclude specific properties and only include own-
// properties (to skip members already defined on the shared prototype).
@@ -166,23 +166,23 @@ namespace ts {
// Reserved words
export function createSuper() {
- return createSynthesizedNode(SyntaxKind.SuperKeyword);
+ return createSynthesizedNode(SyntaxKind.SuperKeyword);
}
export function createThis() {
- return createSynthesizedNode(SyntaxKind.ThisKeyword);
+ return >createSynthesizedNode(SyntaxKind.ThisKeyword);
}
export function createNull() {
- return createSynthesizedNode(SyntaxKind.NullKeyword);
+ return >createSynthesizedNode(SyntaxKind.NullKeyword);
}
export function createTrue() {
- return createSynthesizedNode(SyntaxKind.TrueKeyword);
+ return >createSynthesizedNode(SyntaxKind.TrueKeyword);
}
export function createFalse() {
- return createSynthesizedNode(SyntaxKind.FalseKeyword);
+ return >createSynthesizedNode(SyntaxKind.FalseKeyword);
}
// Names
@@ -213,6 +213,284 @@ namespace ts {
: node;
}
+ // Type Elements
+
+ export function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
+ const signatureDeclaration = createSynthesizedNode(kind) as SignatureDeclaration;
+ signatureDeclaration.typeParameters = asNodeArray(typeParameters);
+ signatureDeclaration.parameters = asNodeArray(parameters);
+ signatureDeclaration.type = type;
+ return signatureDeclaration;
+ }
+
+ function updateSignatureDeclaration(node: SignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
+ : node;
+ }
+
+ export function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
+ return createSignatureDeclaration(SyntaxKind.FunctionType, typeParameters, parameters, type) as FunctionTypeNode;
+ }
+
+ export function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+
+ export function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
+ return createSignatureDeclaration(SyntaxKind.ConstructorType, typeParameters, parameters, type) as ConstructorTypeNode;
+ }
+
+ export function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+
+ export function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
+ return createSignatureDeclaration(SyntaxKind.CallSignature, typeParameters, parameters, type) as CallSignatureDeclaration;
+ }
+
+ export function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+
+ export function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined) {
+ return createSignatureDeclaration(SyntaxKind.ConstructSignature, typeParameters, parameters, type) as ConstructSignatureDeclaration;
+ }
+
+ export function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined) {
+ return updateSignatureDeclaration(node, typeParameters, parameters, type);
+ }
+
+ export function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined) {
+ const methodSignature = createSignatureDeclaration(SyntaxKind.MethodSignature, typeParameters, parameters, type) as MethodSignature;
+ methodSignature.name = asName(name);
+ methodSignature.questionToken = questionToken;
+ return methodSignature;
+ }
+
+ export function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined) {
+ return node.typeParameters !== typeParameters
+ || node.parameters !== parameters
+ || node.type !== type
+ || node.name !== name
+ || node.questionToken !== questionToken
+ ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
+ : node;
+ }
+
+ // Types
+
+ export function createKeywordTypeNode(kind: KeywordTypeNode["kind"]) {
+ return createSynthesizedNode(kind);
+ }
+
+ export function createThisTypeNode() {
+ return createSynthesizedNode(SyntaxKind.ThisType);
+ }
+
+ export function createLiteralTypeNode(literal: Expression) {
+ const literalTypeNode = createSynthesizedNode(SyntaxKind.LiteralType) as LiteralTypeNode;
+ literalTypeNode.literal = literal;
+ return literalTypeNode;
+ }
+
+ export function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression) {
+ return node.literal !== literal
+ ? updateNode(createLiteralTypeNode(literal), node)
+ : node;
+ }
+
+ export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) {
+ const typeReference = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode;
+ typeReference.typeName = asName(typeName);
+ typeReference.typeArguments = asNodeArray(typeArguments);
+ return typeReference;
+ }
+
+ export function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) {
+ return node.typeName !== typeName
+ || node.typeArguments !== typeArguments
+ ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
+ : node;
+ }
+
+ export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) {
+ const typePredicateNode = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode;
+ typePredicateNode.parameterName = asName(parameterName);
+ typePredicateNode.type = type;
+ return typePredicateNode;
+ }
+
+ export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) {
+ return node.parameterName !== parameterName
+ || node.type !== type
+ ? updateNode(createTypePredicateNode(parameterName, type), node)
+ : node;
+ }
+
+ export function createTypeQueryNode(exprName: EntityName) {
+ const typeQueryNode = createSynthesizedNode(SyntaxKind.TypeQuery) as TypeQueryNode;
+ typeQueryNode.exprName = exprName;
+ return typeQueryNode;
+ }
+
+ export function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) {
+ return node.exprName !== exprName ? updateNode(createTypeQueryNode(exprName), node) : node;
+ }
+
+ export function createArrayTypeNode(elementType: TypeNode) {
+ const arrayTypeNode = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode;
+ arrayTypeNode.elementType = elementType;
+ return arrayTypeNode;
+ }
+
+ export function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode {
+ return node.elementType !== elementType
+ ? updateNode(createArrayTypeNode(elementType), node)
+ : node;
+ }
+
+ export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode;
+ export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode;
+ export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode;
+ export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) {
+ const unionTypeNode = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode;
+ unionTypeNode.types = createNodeArray(types);
+ return unionTypeNode;
+ }
+
+ export function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray) {
+ return node.types !== types
+ ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
+ : node;
+ }
+
+ export function createTypeLiteralNode(members: TypeElement[]) {
+ const typeLiteralNode = createSynthesizedNode(SyntaxKind.TypeLiteral) as TypeLiteralNode;
+ typeLiteralNode.members = createNodeArray(members);
+ return typeLiteralNode;
+ }
+
+ export function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) {
+ return node.members !== members
+ ? updateNode(createTypeLiteralNode(members), node)
+ : node;
+ }
+
+ export function createTupleTypeNode(elementTypes: TypeNode[]) {
+ const tupleTypeNode = createSynthesizedNode(SyntaxKind.TupleType) as TupleTypeNode;
+ tupleTypeNode.elementTypes = createNodeArray(elementTypes);
+ return tupleTypeNode;
+ }
+
+ export function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]) {
+ return node.elementTypes !== elementTypes
+ ? updateNode(createTupleTypeNode(elementTypes), node)
+ : node;
+ }
+
+ export function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode {
+ const mappedTypeNode = createSynthesizedNode(SyntaxKind.MappedType) as MappedTypeNode;
+ mappedTypeNode.readonlyToken = readonlyToken;
+ mappedTypeNode.typeParameter = typeParameter;
+ mappedTypeNode.questionToken = questionToken;
+ mappedTypeNode.type = type;
+ return mappedTypeNode;
+ }
+
+ export function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode {
+ return node.readonlyToken !== readonlyToken
+ || node.typeParameter !== typeParameter
+ || node.questionToken !== questionToken
+ || node.type !== type
+ ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
+ : node;
+ }
+
+ export function createTypeOperatorNode(type: TypeNode) {
+ const typeOperatorNode = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode;
+ typeOperatorNode.operator = SyntaxKind.KeyOfKeyword;
+ typeOperatorNode.type = type;
+ return typeOperatorNode;
+ }
+
+ export function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode) {
+ return node.type !== type ? updateNode(createTypeOperatorNode(type), node) : node;
+ }
+
+ export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) {
+ const indexedAccessTypeNode = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode;
+ indexedAccessTypeNode.objectType = objectType;
+ indexedAccessTypeNode.indexType = indexType;
+ return indexedAccessTypeNode;
+ }
+
+ export function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) {
+ return node.objectType !== objectType
+ || node.indexType !== indexType
+ ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
+ : node;
+ }
+
+ // Type Declarations
+
+ export function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) {
+ const typeParameter = createSynthesizedNode(SyntaxKind.TypeParameter) as TypeParameterDeclaration;
+ typeParameter.name = asName(name);
+ typeParameter.constraint = constraint;
+ typeParameter.default = defaultType;
+
+ return typeParameter;
+ }
+
+ export function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined) {
+ return node.name !== name
+ || node.constraint !== constraint
+ || node.default !== defaultType
+ ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
+ : node;
+ }
+
+ // Signature elements
+
+ export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature {
+ const propertySignature = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature;
+ propertySignature.name = asName(name);
+ propertySignature.questionToken = questionToken;
+ propertySignature.type = type;
+ propertySignature.initializer = initializer;
+ return propertySignature;
+ }
+
+ export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
+ return node.name !== name
+ || node.questionToken !== questionToken
+ || node.type !== type
+ || node.initializer !== initializer
+ ? updateNode(createPropertySignature(name, questionToken, type, initializer), node)
+ : node;
+ }
+
+ export function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration {
+ const indexSignature = createSynthesizedNode(SyntaxKind.IndexSignature) as IndexSignatureDeclaration;
+ indexSignature.decorators = asNodeArray(decorators);
+ indexSignature.modifiers = asNodeArray(modifiers);
+ indexSignature.parameters = createNodeArray(parameters);
+ indexSignature.type = type;
+ return indexSignature;
+ }
+
+ export function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode) {
+ return node.parameters !== parameters
+ || node.type !== type
+ || node.decorators !== decorators
+ || node.modifiers !== modifiers
+ ? updateNode(createIndexSignatureDeclaration(decorators, modifiers, parameters, type), node)
+ : node;
+ }
+
// Signature elements
export function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression) {
@@ -227,11 +505,12 @@ namespace ts {
return node;
}
- export function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined) {
+ export function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.dotDotDotToken !== dotDotDotToken
|| node.name !== name
+ || node.questionToken !== questionToken
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer), node)
@@ -273,12 +552,13 @@ namespace ts {
: node;
}
- export function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
+ export function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
const node = createSynthesizedNode(SyntaxKind.MethodDeclaration);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.asteriskToken = asteriskToken;
node.name = asName(name);
+ node.questionToken = questionToken;
node.typeParameters = asNodeArray(typeParameters);
node.parameters = createNodeArray(parameters);
node.type = type;
@@ -286,7 +566,7 @@ namespace ts {
return node;
}
- export function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
+ export function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.asteriskToken !== asteriskToken
@@ -295,7 +575,7 @@ namespace ts {
|| node.parameters !== parameters
|| node.type !== type
|| node.body !== body
- ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
+ ? updateNode(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
: node;
}
@@ -1482,7 +1762,7 @@ namespace ts {
// Clauses
- export function createHeritageClause(token: SyntaxKind, types: ExpressionWithTypeArguments[]) {
+ export function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]) {
const node = createSynthesizedNode(SyntaxKind.HeritageClause);
node.token = token;
node.types = createNodeArray(types);
@@ -1789,7 +2069,9 @@ namespace ts {
function asName(name: string | Identifier): Identifier;
function asName(name: string | BindingName): BindingName;
function asName(name: string | PropertyName): PropertyName;
- function asName(name: string | Identifier | BindingName | PropertyName) {
+ function asName(name: string | EntityName): EntityName;
+ function asName(name: string | Identifier | ThisTypeNode): Identifier | ThisTypeNode;
+ function asName(name: string | Identifier | BindingName | PropertyName | QualifiedName | ThisTypeNode) {
return typeof name === "string" ? createIdentifier(name) : name;
}
diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts
index 1911605a0a6..699919e0566 100644
--- a/src/compiler/moduleNameResolver.ts
+++ b/src/compiler/moduleNameResolver.ts
@@ -1,4 +1,4 @@
-///
+///
///
namespace ts {
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts
index 3379c3fb3b4..d73b383a9c8 100644
--- a/src/compiler/parser.ts
+++ b/src/compiler/parser.ts
@@ -1315,7 +1315,7 @@ namespace ts {
case ParsingContext.ObjectBindingElements:
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName();
case ParsingContext.HeritageClauseElement:
- // If we see { } then only consume it as an expression if it is followed by , or {
+ // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
// That way we won't consume the body of a class in its heritage clause.
if (token() === SyntaxKind.OpenBraceToken) {
return lookAhead(isValidHeritageClauseObjectLiteral);
@@ -2119,7 +2119,7 @@ namespace ts {
return finishNode(node);
}
- function parseTypeParameters(): NodeArray {
+ function parseTypeParameters(): NodeArray | undefined {
if (token() === SyntaxKind.LessThanToken) {
return parseBracketedList(ParsingContext.TypeParameters, parseTypeParameter, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
}
@@ -2189,7 +2189,7 @@ namespace ts {
}
function fillSignature(
- returnToken: SyntaxKind,
+ returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken,
yieldContext: boolean,
awaitContext: boolean,
requireCompleteParameterList: boolean,
@@ -2379,14 +2379,14 @@ namespace ts {
}
function isTypeMemberStart(): boolean {
- let idToken: SyntaxKind;
// Return true if we have the start of a signature member
if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) {
return true;
}
+ let idToken: boolean;
// Eat up all modifiers, but hold on to the last one in case it is actually an identifier
while (isModifierKind(token())) {
- idToken = token();
+ idToken = true;
nextToken();
}
// Index signatures and computed property names are type members
@@ -2395,7 +2395,7 @@ namespace ts {
}
// Try to get the first property-like token following all modifiers
if (isLiteralPropertyName()) {
- idToken = token();
+ idToken = true;
nextToken();
}
// If we were able to get any potential identifier, check that it is
@@ -2503,7 +2503,7 @@ namespace ts {
return finishNode(node);
}
- function parseKeywordAndNoDot(): TypeNode {
+ function parseKeywordAndNoDot(): TypeNode | undefined {
const node = parseTokenNode();
return token() === SyntaxKind.DotToken ? undefined : node;
}
@@ -2641,7 +2641,7 @@ namespace ts {
return parseArrayTypeOrHigher();
}
- function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode {
+ function parseUnionOrIntersectionType(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, parseConstituentType: () => TypeNode, operator: SyntaxKind.BarToken | SyntaxKind.AmpersandToken): TypeNode {
parseOptional(operator);
let type = parseConstituentType();
if (token() === operator) {
@@ -3879,6 +3879,9 @@ namespace ts {
parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTagName));
break;
}
+ else if (token() === SyntaxKind.ConflictMarkerTrivia) {
+ break;
+ }
result.push(parseJsxChild());
}
@@ -5297,8 +5300,8 @@ namespace ts {
*
* In such situations, 'permitInvalidConstAsModifier' should be set to true.
*/
- function parseModifiers(permitInvalidConstAsModifier?: boolean): NodeArray {
- let modifiers: NodeArray;
+ function parseModifiers(permitInvalidConstAsModifier?: boolean): NodeArray | undefined {
+ let modifiers: NodeArray | undefined;
while (true) {
const modifierStart = scanner.getStartPos();
const modifierKind = token();
@@ -5438,7 +5441,7 @@ namespace ts {
return token() === SyntaxKind.ImplementsKeyword && lookAhead(nextTokenIsIdentifierOrKeyword);
}
- function parseHeritageClauses(): NodeArray {
+ function parseHeritageClauses(): NodeArray | undefined {
// ClassTail[Yield,Await] : (Modified) See 14.5
// ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
@@ -5449,10 +5452,11 @@ namespace ts {
return undefined;
}
- function parseHeritageClause() {
- if (token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword) {
+ function parseHeritageClause(): HeritageClause | undefined {
+ const tok = token();
+ if (tok === SyntaxKind.ExtendsKeyword || tok === SyntaxKind.ImplementsKeyword) {
const node = createNode(SyntaxKind.HeritageClause);
- node.token = token();
+ node.token = tok;
nextToken();
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
return finishNode(node);
@@ -5475,7 +5479,7 @@ namespace ts {
return token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword;
}
- function parseClassMembers() {
+ function parseClassMembers(): NodeArray {
return parseList(ParsingContext.ClassMembers, parseClassElement);
}
@@ -5639,17 +5643,7 @@ namespace ts {
if (isIdentifier()) {
identifier = parseIdentifier();
if (token() !== SyntaxKind.CommaToken && token() !== SyntaxKind.FromKeyword) {
- // ImportEquals declaration of type:
- // import x = require("mod"); or
- // import x = M.x;
- const importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart);
- importEqualsDeclaration.decorators = decorators;
- importEqualsDeclaration.modifiers = modifiers;
- importEqualsDeclaration.name = identifier;
- parseExpected(SyntaxKind.EqualsToken);
- importEqualsDeclaration.moduleReference = parseModuleReference();
- parseSemicolon();
- return addJSDocComment(finishNode(importEqualsDeclaration));
+ return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier);
}
}
@@ -5673,6 +5667,17 @@ namespace ts {
return finishNode(importDeclaration);
}
+ function parseImportEqualsDeclaration(fullStart: number, decorators: NodeArray, modifiers: NodeArray, identifier: ts.Identifier): ImportEqualsDeclaration {
+ const importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart);
+ importEqualsDeclaration.decorators = decorators;
+ importEqualsDeclaration.modifiers = modifiers;
+ importEqualsDeclaration.name = identifier;
+ parseExpected(SyntaxKind.EqualsToken);
+ importEqualsDeclaration.moduleReference = parseModuleReference();
+ parseSemicolon();
+ return addJSDocComment(finishNode(importEqualsDeclaration));
+ }
+
function parseImportClause(identifier: Identifier, fullStart: number) {
// ImportClause:
// ImportedDefaultBinding
@@ -5838,6 +5843,7 @@ namespace ts {
const typeReferenceDirectives: FileReference[] = [];
const amdDependencies: { path: string; name: string }[] = [];
let amdModuleName: string;
+ let checkJsDirective: CheckJsDirective = undefined;
// Keep scanning all the leading trivia in the file until we get to something that
// isn't trivia. Any single line comment will be analyzed to see if it is a
@@ -5899,6 +5905,16 @@ namespace ts {
amdDependencies.push(amdDependency);
}
}
+
+ const checkJsDirectiveRegEx = /^\/\/\/?\s*(@ts-check|@ts-nocheck)\s*$/gim;
+ const checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment);
+ if (checkJsDirectiveMatchResult) {
+ checkJsDirective = {
+ enabled: compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", /*ignoreCase*/ true) === Comparison.EqualTo,
+ end: range.end,
+ pos: range.pos
+ };
+ }
}
}
@@ -5906,6 +5922,7 @@ namespace ts {
sourceFile.typeReferenceDirectives = typeReferenceDirectives;
sourceFile.amdDependencies = amdDependencies;
sourceFile.moduleName = amdModuleName;
+ sourceFile.checkJsDirective = checkJsDirective;
}
function setExternalModuleIndicator(sourceFile: SourceFile) {
diff --git a/src/compiler/program.ts b/src/compiler/program.ts
index b50c96a5f0c..e69098a21a1 100644
--- a/src/compiler/program.ts
+++ b/src/compiler/program.ts
@@ -4,6 +4,7 @@
namespace ts {
const emptyArray: any[] = [];
+ const ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string {
while (true) {
@@ -87,9 +88,6 @@ namespace ts {
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
- // returned by CScript sys environment
- const unsupportedFileEncodingErrorCode = -2147024809;
-
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
let text: string;
try {
@@ -100,9 +98,7 @@ namespace ts {
}
catch (e) {
if (onError) {
- onError(e.number === unsupportedFileEncodingErrorCode
- ? createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText
- : e.message);
+ onError(e.message);
}
text = "";
}
@@ -303,8 +299,8 @@ namespace ts {
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map;
- let cachedSemanticDiagnosticsForFile: DiagnosticCache = {};
- let cachedDeclarationDiagnosticsForFile: DiagnosticCache = {};
+ const cachedSemanticDiagnosticsForFile: DiagnosticCache = {};
+ const cachedDeclarationDiagnosticsForFile: DiagnosticCache = {};
let resolvedTypeReferenceDirectives = createMap();
let fileProcessingDiagnostics = createDiagnosticCollection();
@@ -916,17 +912,42 @@ namespace ts {
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
- // For JavaScript files, we don't want to report semantic errors.
- // Instead, we'll report errors for using TypeScript-only constructs from within a
- // JavaScript file when we get syntactic diagnostics for the file.
- const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken);
+ // For JavaScript files, we don't want to report semantic errors unless explicitly requested.
+ const includeCheckDiagnostics = !isSourceFileJavaScript(sourceFile) || isCheckJsEnabledForFile(sourceFile, options);
+ const checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : [];
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
- return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
+ const diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
+ return isSourceFileJavaScript(sourceFile)
+ ? filter(diagnostics, shouldReportDiagnostic)
+ : diagnostics;
});
}
+ /**
+ * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines
+ */
+ function shouldReportDiagnostic(diagnostic: Diagnostic) {
+ const { file, start } = diagnostic;
+ const lineStarts = getLineStarts(file);
+ let { line } = computeLineAndCharacterOfPosition(lineStarts, start);
+ while (line > 0) {
+ const previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
+ const result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
+ if (!result) {
+ // non-empty line
+ return true;
+ }
+ if (result[3]) {
+ // @ts-ignore
+ return false;
+ }
+ line--;
+ }
+ return true;
+ }
+
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
@@ -1110,7 +1131,7 @@ namespace ts {
return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
}
- function getDeclarationDiagnosticsForFileNoCache(sourceFile: SourceFile| undefined, cancellationToken: CancellationToken) {
+ function getDeclarationDiagnosticsForFileNoCache(sourceFile: SourceFile | undefined, cancellationToken: CancellationToken) {
return runWithCancellationToken(() => {
const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
@@ -1726,6 +1747,10 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"));
}
+ if (options.checkJs && !options.allowJs) {
+ programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
+ }
+
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts
index fb91b0ff5b7..466074bdbcc 100644
--- a/src/compiler/scanner.ts
+++ b/src/compiler/scanner.ts
@@ -333,7 +333,7 @@ namespace ts {
}
/* @internal */
- export function getLineStarts(sourceFile: SourceFile): number[] {
+ export function getLineStarts(sourceFile: SourceFileLike): number[] {
return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
}
@@ -1716,7 +1716,14 @@ namespace ts {
while (pos < end) {
pos++;
char = text.charCodeAt(pos);
- if ((char === CharacterCodes.openBrace) || (char === CharacterCodes.lessThan)) {
+ if (char === CharacterCodes.openBrace) {
+ break;
+ }
+ if (char === CharacterCodes.lessThan) {
+ if (isConflictMarkerTrivia(text, pos)) {
+ pos = scanConflictMarkerTrivia(text, pos, error);
+ return token = SyntaxKind.ConflictMarkerTrivia;
+ }
break;
}
}
diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts
index 2a15df80102..5275d210172 100644
--- a/src/compiler/sys.ts
+++ b/src/compiler/sys.ts
@@ -74,13 +74,6 @@ namespace ts {
return parseInt(version.substring(1, dot));
}
- declare class Enumerator {
- public atEnd(): boolean;
- public moveNext(): boolean;
- public item(): any;
- constructor(o: any);
- }
-
declare var ChakraHost: {
args: string[];
currentDirectory: string;
@@ -104,152 +97,6 @@ namespace ts {
};
export let sys: System = (function() {
-
- function getWScriptSystem(): System {
-
- const fso = new ActiveXObject("Scripting.FileSystemObject");
- const shell = new ActiveXObject("WScript.Shell");
-
- const fileStream = new ActiveXObject("ADODB.Stream");
- fileStream.Type = 2 /*text*/;
-
- const binaryStream = new ActiveXObject("ADODB.Stream");
- binaryStream.Type = 1 /*binary*/;
-
- const args: string[] = [];
- for (let i = 0; i < WScript.Arguments.length; i++) {
- args[i] = WScript.Arguments.Item(i);
- }
-
- function readFile(fileName: string, encoding?: string): string {
- if (!fso.FileExists(fileName)) {
- return undefined;
- }
- fileStream.Open();
- try {
- if (encoding) {
- fileStream.Charset = encoding;
- fileStream.LoadFromFile(fileName);
- }
- else {
- // Load file and read the first two bytes into a string with no interpretation
- fileStream.Charset = "x-ansi";
- fileStream.LoadFromFile(fileName);
- const bom = fileStream.ReadText(2) || "";
- // Position must be at 0 before encoding can be changed
- fileStream.Position = 0;
- // [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8
- fileStream.Charset = bom.length >= 2 && (bom.charCodeAt(0) === 0xFF && bom.charCodeAt(1) === 0xFE || bom.charCodeAt(0) === 0xFE && bom.charCodeAt(1) === 0xFF) ? "unicode" : "utf-8";
- }
- // ReadText method always strips byte order mark from resulting string
- return fileStream.ReadText();
- }
- catch (e) {
- throw e;
- }
- finally {
- fileStream.Close();
- }
- }
-
- function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void {
- fileStream.Open();
- binaryStream.Open();
- try {
- // Write characters in UTF-8 encoding
- fileStream.Charset = "utf-8";
- fileStream.WriteText(data);
- // If we don't want the BOM, then skip it by setting the starting location to 3 (size of BOM).
- // If not, start from position 0, as the BOM will be added automatically when charset==utf8.
- if (writeByteOrderMark) {
- fileStream.Position = 0;
- }
- else {
- fileStream.Position = 3;
- }
- fileStream.CopyTo(binaryStream);
- binaryStream.SaveToFile(fileName, 2 /*overwrite*/);
- }
- finally {
- binaryStream.Close();
- fileStream.Close();
- }
- }
-
- function getNames(collection: any): string[] {
- const result: string[] = [];
- for (const e = new Enumerator(collection); !e.atEnd(); e.moveNext()) {
- result.push(e.item().Name);
- }
- return result.sort();
- }
-
- function getDirectories(path: string): string[] {
- const folder = fso.GetFolder(path);
- return getNames(folder.subfolders);
- }
-
- function getAccessibleFileSystemEntries(path: string): FileSystemEntries {
- try {
- const folder = fso.GetFolder(path || ".");
- const files = getNames(folder.files);
- const directories = getNames(folder.subfolders);
- return { files, directories };
- }
- catch (e) {
- return { files: [], directories: [] };
- }
- }
-
- function readDirectory(path: string, extensions?: string[], excludes?: string[], includes?: string[]): string[] {
- return matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
- }
-
- const wscriptSystem: System = {
- args,
- newLine: "\r\n",
- useCaseSensitiveFileNames: false,
- write(s: string): void {
- WScript.StdOut.Write(s);
- },
- readFile,
- writeFile,
- resolvePath(path: string): string {
- return fso.GetAbsolutePathName(path);
- },
- fileExists(path: string): boolean {
- return fso.FileExists(path);
- },
- directoryExists(path: string) {
- return fso.FolderExists(path);
- },
- createDirectory(directoryName: string) {
- if (!wscriptSystem.directoryExists(directoryName)) {
- fso.CreateFolder(directoryName);
- }
- },
- getExecutingFilePath() {
- return WScript.ScriptFullName;
- },
- getCurrentDirectory() {
- return shell.CurrentDirectory;
- },
- getDirectories,
- getEnvironmentVariable(name: string) {
- return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings(`%${name}%`);
- },
- readDirectory,
- exit(exitCode?: number): void {
- try {
- WScript.Quit(exitCode);
- }
- catch (e) {
- }
- }
- };
- return wscriptSystem;
- }
-
function getNodeSystem(): System {
const _fs = require("fs");
const _path = require("path");
@@ -355,7 +202,7 @@ namespace ts {
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
// Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
// flip all byte pairs and treat as little endian.
- len &= ~1;
+ len &= ~1; // Round down to a multiple of 2
for (let i = 0; i < len; i += 2) {
const temp = buffer[i];
buffer[i] = buffer[i + 1];
@@ -646,9 +493,6 @@ namespace ts {
if (typeof ChakraHost !== "undefined") {
sys = getChakraSystem();
}
- else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
- sys = getWScriptSystem();
- }
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
// process and process.nextTick checks if current environment is node-like
// process.browser check excludes webpack and browserify
diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts
index 31aae5055a0..088c57866d0 100644
--- a/src/compiler/transformers/es2017.ts
+++ b/src/compiler/transformers/es2017.ts
@@ -125,6 +125,7 @@ namespace ts {
visitNodes(node.modifiers, visitor, isModifier),
node.asteriskToken,
node.name,
+ /*questionToken*/ undefined,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts
index 971dddd20ea..83e84e6eab5 100644
--- a/src/compiler/transformers/esnext.ts
+++ b/src/compiler/transformers/esnext.ts
@@ -475,6 +475,7 @@ namespace ts {
/*modifiers*/ undefined,
node.dotDotDotToken,
getGeneratedNameForNode(node),
+ /*questionToken*/ undefined,
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression)
);
@@ -540,6 +541,7 @@ namespace ts {
? undefined
: node.asteriskToken,
visitNode(node.name, visitor, isPropertyName),
+ visitNode(/*questionToken*/ undefined, visitor, isToken),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts
index 7d26b27f0db..58b61c632ab 100644
--- a/src/compiler/transformers/module/module.ts
+++ b/src/compiler/transformers/module/module.ts
@@ -89,7 +89,8 @@ namespace ts {
startLexicalEnvironment();
const statements: Statement[] = [];
- const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
+ const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
+ const statementOffset = addPrologueDirectives(statements, node.statements, ensureUseStrict, sourceElementVisitor);
if (shouldEmitUnderscoreUnderscoreESModule()) {
append(statements, createUnderscoreUnderscoreESModule());
diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts
index f7395ab0791..d1cbfa8d4d8 100644
--- a/src/compiler/transformers/module/system.ts
+++ b/src/compiler/transformers/module/system.ts
@@ -223,7 +223,8 @@ namespace ts {
startLexicalEnvironment();
// Add any prologue directives.
- const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
+ const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
+ const statementOffset = addPrologueDirectives(statements, node.statements, ensureUseStrict, sourceElementVisitor);
// var __moduleName = context_1 && context_1.id;
statements.push(
diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts
index 885f8fad898..6dc643b9543 100644
--- a/src/compiler/transformers/ts.ts
+++ b/src/compiler/transformers/ts.ts
@@ -2049,6 +2049,7 @@ namespace ts {
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
visitPropertyNameOfClassElement(node),
+ /*questionToken*/ undefined,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts
index 32b6a90e268..4fd3ecb02bb 100644
--- a/src/compiler/tsc.ts
+++ b/src/compiler/tsc.ts
@@ -225,9 +225,9 @@ namespace ts {
return sys.exit(ExitStatus.Success);
}
- if (commandLine.options.help) {
+ if (commandLine.options.help || commandLine.options.all) {
printVersion();
- printHelp();
+ printHelp(commandLine.options.all);
return sys.exit(ExitStatus.Success);
}
@@ -264,7 +264,7 @@ namespace ts {
if (commandLine.fileNames.length === 0 && !configFileName) {
printVersion();
- printHelp();
+ printHelp(commandLine.options.all);
return sys.exit(ExitStatus.Success);
}
@@ -618,7 +618,7 @@ namespace ts {
sys.write(getDiagnosticText(Diagnostics.Version_0, ts.version) + sys.newLine);
}
- function printHelp() {
+ function printHelp(showAllOptions: boolean) {
const output: string[] = [];
// We want to align our "syntax" and "examples" commands to a certain margin.
@@ -643,8 +643,9 @@ namespace ts {
output.push(getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine);
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
- const optsList = filter(optionDeclarations.slice(), v => !v.experimental);
- optsList.sort((a, b) => compareValues(a.name.toLowerCase(), b.name.toLowerCase()));
+ const optsList = showAllOptions ?
+ optionDeclarations.slice().sort((a, b) => compareValues(a.name.toLowerCase(), b.name.toLowerCase())) :
+ filter(optionDeclarations.slice(), v => v.showInSimplifiedHelpView);
// We want our descriptions to align at the same column in our output,
// so we keep track of the longest option usage string.
@@ -738,7 +739,7 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* host */ undefined);
}
else {
- sys.writeFile(file, JSON.stringify(generateTSConfig(options, fileNames), undefined, 4));
+ sys.writeFile(file, generateTSConfig(options, fileNames));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* host */ undefined);
}
diff --git a/src/compiler/types.ts b/src/compiler/types.ts
index 762bbef3f82..1a740ceebcf 100644
--- a/src/compiler/types.ts
+++ b/src/compiler/types.ts
@@ -816,18 +816,21 @@ namespace ts {
export interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement {
kind: SyntaxKind.Constructor;
+ parent?: ClassDeclaration | ClassExpression;
body?: FunctionBody;
}
- // For when we encounter a semicolon in a class declaration. ES6 allows these as class elements.
+ /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements.*/
export interface SemicolonClassElement extends ClassElement {
kind: SyntaxKind.SemicolonClassElement;
+ parent?: ClassDeclaration | ClassExpression;
}
// See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a
// ClassElement and an ObjectLiteralElement.
export interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
kind: SyntaxKind.GetAccessor;
+ parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression;
name: PropertyName;
body: FunctionBody;
}
@@ -836,6 +839,7 @@ namespace ts {
// ClassElement and an ObjectLiteralElement.
export interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement {
kind: SyntaxKind.SetAccessor;
+ parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression;
name: PropertyName;
body: FunctionBody;
}
@@ -844,6 +848,7 @@ namespace ts {
export interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement {
kind: SyntaxKind.IndexSignature;
+ parent?: ClassDeclaration | ClassExpression | InterfaceDeclaration | TypeLiteralNode;
}
export interface TypeNode extends Node {
@@ -857,22 +862,24 @@ namespace ts {
| SyntaxKind.BooleanKeyword
| SyntaxKind.StringKeyword
| SyntaxKind.SymbolKeyword
- | SyntaxKind.VoidKeyword;
+ | SyntaxKind.ThisKeyword
+ | SyntaxKind.VoidKeyword
+ | SyntaxKind.UndefinedKeyword
+ | SyntaxKind.NullKeyword
+ | SyntaxKind.NeverKeyword;
}
export interface ThisTypeNode extends TypeNode {
kind: SyntaxKind.ThisType;
}
- export interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration {
- kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType;
- }
+ export type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode;
- export interface FunctionTypeNode extends FunctionOrConstructorTypeNode {
+ export interface FunctionTypeNode extends TypeNode, SignatureDeclaration {
kind: SyntaxKind.FunctionType;
}
- export interface ConstructorTypeNode extends FunctionOrConstructorTypeNode {
+ export interface ConstructorTypeNode extends TypeNode, SignatureDeclaration {
kind: SyntaxKind.ConstructorType;
}
@@ -909,17 +916,16 @@ namespace ts {
elementTypes: NodeArray;
}
- export interface UnionOrIntersectionTypeNode extends TypeNode {
- kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType;
+ export type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode;
+
+ export interface UnionTypeNode extends TypeNode {
+ kind: SyntaxKind.UnionType;
types: NodeArray;
}
- export interface UnionTypeNode extends UnionOrIntersectionTypeNode {
- kind: SyntaxKind.UnionType;
- }
-
- export interface IntersectionTypeNode extends UnionOrIntersectionTypeNode {
+ export interface IntersectionTypeNode extends TypeNode {
kind: SyntaxKind.IntersectionType;
+ types: NodeArray;
}
export interface ParenthesizedTypeNode extends TypeNode {
@@ -941,6 +947,7 @@ namespace ts {
export interface MappedTypeNode extends TypeNode, Declaration {
kind: SyntaxKind.MappedType;
+ parent?: TypeAliasDeclaration;
readonlyToken?: ReadonlyToken;
typeParameter: TypeParameterDeclaration;
questionToken?: QuestionToken;
@@ -1028,15 +1035,15 @@ namespace ts {
_primaryExpressionBrand: any;
}
- export interface NullLiteral extends PrimaryExpression {
+ export interface NullLiteral extends PrimaryExpression, TypeNode {
kind: SyntaxKind.NullKeyword;
}
- export interface BooleanLiteral extends PrimaryExpression {
+ export interface BooleanLiteral extends PrimaryExpression, TypeNode {
kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword;
}
- export interface ThisExpression extends PrimaryExpression {
+ export interface ThisExpression extends PrimaryExpression, KeywordTypeNode {
kind: SyntaxKind.ThisKeyword;
}
@@ -1463,7 +1470,7 @@ namespace ts {
kind: SyntaxKind.NewExpression;
expression: LeftHandSideExpression;
typeArguments?: NodeArray;
- arguments: NodeArray;
+ arguments?: NodeArray;
}
export interface TaggedTemplateExpression extends MemberExpression {
@@ -1517,6 +1524,7 @@ namespace ts {
export type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression;
export interface JsxAttributes extends ObjectLiteralExpressionBase {
+ parent?: JsxOpeningLikeElement;
}
/// The opening element of a ... JsxElement
@@ -1536,7 +1544,7 @@ namespace ts {
export interface JsxAttribute extends ObjectLiteralElement {
kind: SyntaxKind.JsxAttribute;
- parent?: JsxOpeningLikeElement;
+ parent?: JsxAttributes;
name: Identifier;
/// JSX attribute initializers are optional; is sugar for
initializer?: StringLiteral | JsxExpression;
@@ -1544,7 +1552,7 @@ namespace ts {
export interface JsxSpreadAttribute extends ObjectLiteralElement {
kind: SyntaxKind.JsxSpreadAttribute;
- parent?: JsxOpeningLikeElement;
+ parent?: JsxAttributes;
expression: Expression;
}
@@ -1789,8 +1797,8 @@ namespace ts {
export interface HeritageClause extends Node {
kind: SyntaxKind.HeritageClause;
parent?: InterfaceDeclaration | ClassDeclaration | ClassExpression;
- token: SyntaxKind;
- types?: NodeArray;
+ token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword;
+ types: NodeArray;
}
export interface TypeAliasDeclaration extends DeclarationStatement {
@@ -1823,7 +1831,7 @@ namespace ts {
kind: SyntaxKind.ModuleDeclaration;
parent?: ModuleBody | SourceFile;
name: ModuleName;
- body?: ModuleBody | JSDocNamespaceDeclaration | Identifier;
+ body?: ModuleBody | JSDocNamespaceDeclaration;
}
export type NamespaceBody = ModuleBlock | NamespaceDeclaration;
@@ -1848,6 +1856,11 @@ namespace ts {
export type ModuleReference = EntityName | ExternalModuleReference;
+ /**
+ * One of:
+ * - import x = require("mod");
+ * - import x = M.x;
+ */
export interface ImportEqualsDeclaration extends DeclarationStatement {
kind: SyntaxKind.ImportEqualsDeclaration;
parent?: SourceFile | ModuleBlock;
@@ -1899,7 +1912,6 @@ namespace ts {
export interface NamespaceExportDeclaration extends DeclarationStatement {
kind: SyntaxKind.NamespaceExportDeclaration;
name: Identifier;
- moduleReference: LiteralLikeNode;
}
export interface ExportDeclaration extends DeclarationStatement {
@@ -1950,6 +1962,10 @@ namespace ts {
fileName: string;
}
+ export interface CheckJsDirective extends TextRange {
+ enabled: boolean;
+ }
+
export type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia;
export interface CommentRange extends TextRange {
@@ -2215,6 +2231,16 @@ namespace ts {
name: string;
}
+ /* @internal */
+ /**
+ * Subset of properties from SourceFile that are used in multiple utility functions
+ */
+ export interface SourceFileLike {
+ readonly text: string;
+ lineMap: number[];
+ }
+
+
// Source files are declarations when they are external modules.
export interface SourceFile extends Declaration {
kind: SyntaxKind.SourceFile;
@@ -2222,7 +2248,7 @@ namespace ts {
endOfFileToken: Token;
fileName: string;
- /* internal */ path: Path;
+ /* @internal */ path: Path;
text: string;
amdDependencies: AmdDependency[];
@@ -2282,6 +2308,7 @@ namespace ts {
/* @internal */ moduleAugmentations: LiteralExpression[];
/* @internal */ patternAmbientModules?: PatternAmbientModule[];
/* @internal */ ambientModuleNames: string[];
+ /* @internal */ checkJsDirective: CheckJsDirective | undefined;
}
export interface Bundle extends Node {
@@ -2464,6 +2491,14 @@ namespace ts {
/* @internal */ getParameterType(signature: Signature, parameterIndex: number): Type;
getNonNullableType(type: Type): Type;
+ /** Note that the resulting nodes cannot be checked. */
+
+ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode;
+ /** Note that the resulting nodes cannot be checked. */
+ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration;
+ /** Note that the resulting nodes cannot be checked. */
+ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration;
+
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
@@ -2515,6 +2550,16 @@ namespace ts {
/* @internal */ getTypeCount(): number;
}
+ export enum NodeBuilderFlags {
+ None = 0,
+ allowThisInObjectLiteral = 1 << 0,
+ allowQualifedNameInPlaceOfIdentifier = 1 << 1,
+ allowTypeParameterInQualifiedName = 1 << 2,
+ allowAnonymousIdentifier = 1 << 3,
+ allowEmptyUnionOrIntersection = 1 << 4,
+ allowEmptyTuple = 1 << 5
+ }
+
export interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
@@ -2821,13 +2866,15 @@ namespace ts {
export const enum CheckFlags {
Instantiated = 1 << 0, // Instantiated symbol
SyntheticProperty = 1 << 1, // Property in union or intersection type
- Readonly = 1 << 2, // Readonly transient symbol
- Partial = 1 << 3, // Synthetic property present in some but not all constituents
- HasNonUniformType = 1 << 4, // Synthetic property with non-uniform type in constituents
- ContainsPublic = 1 << 5, // Synthetic property with public constituent(s)
- ContainsProtected = 1 << 6, // Synthetic property with protected constituent(s)
- ContainsPrivate = 1 << 7, // Synthetic property with private constituent(s)
- ContainsStatic = 1 << 8, // Synthetic property with static constituent(s)
+ SyntheticMethod = 1 << 2, // Method in union or intersection type
+ Readonly = 1 << 3, // Readonly transient symbol
+ Partial = 1 << 4, // Synthetic property present in some but not all constituents
+ HasNonUniformType = 1 << 5, // Synthetic property with non-uniform type in constituents
+ ContainsPublic = 1 << 6, // Synthetic property with public constituent(s)
+ ContainsProtected = 1 << 7, // Synthetic property with protected constituent(s)
+ ContainsPrivate = 1 << 8, // Synthetic property with private constituent(s)
+ ContainsStatic = 1 << 9, // Synthetic property with static constituent(s)
+ Synthetic = SyntheticProperty | SyntheticMethod
}
/* @internal */
@@ -3004,7 +3051,6 @@ namespace ts {
ObjectLiteral = 1 << 7, // Originates in an object literal
EvolvingArray = 1 << 8, // Evolving array type
ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties
- NonPrimitive = 1 << 10, // NonPrimitive object type
ClassOrInterface = Class | Interface
}
@@ -3315,6 +3361,7 @@ namespace ts {
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[];
export interface CompilerOptions {
+ /*@internal*/ all?: boolean;
allowJs?: boolean;
/*@internal*/ allowNonTsExtensions?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -3323,6 +3370,7 @@ namespace ts {
alwaysStrict?: boolean; // Always combine with strict property
baseUrl?: string;
charset?: string;
+ checkJs?: boolean;
/* @internal */ configFilePath?: string;
declaration?: boolean;
declarationDir?: string;
@@ -3508,8 +3556,10 @@ namespace ts {
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does
paramType?: DiagnosticMessage; // The name to be used for a non-boolean option's parameter
- experimental?: boolean;
isTSConfigOnly?: boolean; // True if option can only be specified via tsconfig.json file
+ isCommandLineOnly?: boolean;
+ showInSimplifiedHelpView?: boolean;
+ category?: DiagnosticMessage;
}
/* @internal */
@@ -4064,7 +4114,7 @@ namespace ts {
export type Transformer = (node: T) => T;
/**
- * A function that accepts and possible transforms a node.
+ * A function that accepts and possibly transforms a node.
*/
export type Visitor = (node: Node) => VisitResult;
@@ -4145,6 +4195,8 @@ namespace ts {
/*@internal*/ onEmitSourceMapOfPosition?: (pos: number) => void;
/*@internal*/ onEmitHelpers?: (node: Node, writeLines: (text: string) => void) => void;
/*@internal*/ onSetSourceFile?: (node: SourceFile) => void;
+ /*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray) => void;
+ /*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray) => void;
}
export interface PrinterOptions {
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts
index 4eb78736e16..659e516d9d1 100644
--- a/src/compiler/utilities.ts
+++ b/src/compiler/utilities.ts
@@ -184,7 +184,7 @@ namespace ts {
return false;
}
- export function getStartPositionOfLine(line: number, sourceFile: SourceFile): number {
+ export function getStartPositionOfLine(line: number, sourceFile: SourceFileLike): number {
Debug.assert(line >= 0);
return getLineStarts(sourceFile)[line];
}
@@ -204,7 +204,7 @@ namespace ts {
return value !== undefined;
}
- export function getEndLinePosition(line: number, sourceFile: SourceFile): number {
+ export function getEndLinePosition(line: number, sourceFile: SourceFileLike): number {
Debug.assert(line >= 0);
const lineStarts = getLineStarts(sourceFile);
@@ -255,7 +255,11 @@ namespace ts {
return !nodeIsMissing(node);
}
- export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile, includeJsDoc?: boolean): number {
+ export function isToken(n: Node): boolean {
+ return n.kind >= SyntaxKind.FirstToken && n.kind <= SyntaxKind.LastToken;
+ }
+
+ export function getTokenPosOfNode(node: Node, sourceFile?: SourceFileLike, includeJsDoc?: boolean): number {
// With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
// want to skip trivia because this will launch us forward to the next token.
if (nodeIsMissing(node)) {
@@ -289,7 +293,7 @@ namespace ts {
return node.kind >= SyntaxKind.FirstJSDocTagNode && node.kind <= SyntaxKind.LastJSDocTagNode;
}
- export function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number {
+ export function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFileLike): number {
if (nodeIsMissing(node) || !node.decorators) {
return getTokenPosOfNode(node, sourceFile);
}
@@ -521,6 +525,10 @@ namespace ts {
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}
+ export function getNameFromIndexInfo(info: IndexInfo) {
+ return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
+ }
+
export function getTextOfPropertyName(name: PropertyName): string {
switch (name.kind) {
case SyntaxKind.Identifier:
@@ -740,8 +748,8 @@ namespace ts {
//
// let a: A.B.C;
//
- // Calling isPartOfTypeNode would consider the qualified name A.B a type node. Only C or
- // A.B.C is a type node.
+ // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
+ // Only C and A.B.C are type nodes.
if (SyntaxKind.FirstTypeNode <= parent.kind && parent.kind <= SyntaxKind.LastTypeNode) {
return true;
}
@@ -1446,13 +1454,10 @@ namespace ts {
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
- export function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind {
+ export function getSpecialPropertyAssignmentKind(expression: ts.BinaryExpression): SpecialPropertyAssignmentKind {
if (!isInJavaScriptFile(expression)) {
return SpecialPropertyAssignmentKind.None;
}
- if (expression.kind !== SyntaxKind.BinaryExpression) {
- return SpecialPropertyAssignmentKind.None;
- }
const expr = expression;
if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || expr.left.kind !== SyntaxKind.PropertyAccessExpression) {
return SpecialPropertyAssignmentKind.None;
@@ -2495,7 +2500,7 @@ namespace ts {
return indentStrings[1].length;
}
- export function createTextWriter(newLine: String): EmitTextWriter {
+ export function createTextWriter(newLine: string): EmitTextWriter {
let output: string;
let indent: number;
let lineStart: boolean;
@@ -2675,7 +2680,7 @@ namespace ts {
if (sourceFiles.length) {
const jsFilePath = options.outFile || options.out;
const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
- const declarationFilePath = options.declaration ? removeFileExtension(jsFilePath) + ".d.ts" : undefined;
+ const declarationFilePath = options.declaration ? removeFileExtension(jsFilePath) + ".d.ts" : "";
action({ jsFilePath, sourceMapFilePath, declarationFilePath }, createBundle(sourceFiles), emitOnlyDtsFiles);
}
}
@@ -3713,10 +3718,14 @@ namespace ts {
return (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode)
|| kind === SyntaxKind.AnyKeyword
|| kind === SyntaxKind.NumberKeyword
+ || kind === SyntaxKind.ObjectKeyword
|| kind === SyntaxKind.BooleanKeyword
|| kind === SyntaxKind.StringKeyword
|| kind === SyntaxKind.SymbolKeyword
+ || kind === SyntaxKind.ThisKeyword
|| kind === SyntaxKind.VoidKeyword
+ || kind === SyntaxKind.UndefinedKeyword
+ || kind === SyntaxKind.NullKeyword
|| kind === SyntaxKind.NeverKeyword
|| kind === SyntaxKind.ExpressionWithTypeArguments;
}
diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts
index 0f4a4ed6561..297d2cc0dde 100644
--- a/src/compiler/visitor.ts
+++ b/src/compiler/visitor.ts
@@ -154,9 +154,9 @@ namespace ts {
* Starts a new lexical environment and visits a parameter list, suspending the lexical
* environment upon completion.
*/
- export function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext) {
+ export function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes) {
context.startLexicalEnvironment();
- const updated = visitNodes(nodes, visitor, isParameterDeclaration);
+ const updated = nodesVisitor(nodes, visitor, isParameterDeclaration);
context.suspendLexicalEnvironment();
return updated;
}
@@ -204,21 +204,17 @@ namespace ts {
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
- export function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext): T | undefined;
+ export function visitEachChild(node: T | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes, tokenVisitor?: Visitor): T | undefined;
- export function visitEachChild(node: Node, visitor: Visitor, context: TransformationContext): Node {
+ export function visitEachChild(node: Node, visitor: Visitor, context: TransformationContext, nodesVisitor = visitNodes, tokenVisitor?: Visitor): Node {
if (node === undefined) {
return undefined;
}
const kind = node.kind;
- // No need to visit nodes with no children.
- if ((kind > SyntaxKind.FirstToken && kind <= SyntaxKind.LastToken)) {
- return node;
- }
- // We do not yet support types.
- if ((kind >= SyntaxKind.TypePredicate && kind <= SyntaxKind.LiteralType)) {
+ // No need to visit nodes with no children.
+ if ((kind > SyntaxKind.FirstToken && kind <= SyntaxKind.LastToken) || kind === SyntaxKind.ThisType) {
return node;
}
@@ -227,6 +223,8 @@ namespace ts {
case SyntaxKind.EmptyStatement:
case SyntaxKind.OmittedExpression:
case SyntaxKind.DebuggerStatement:
+ case SyntaxKind.EndOfDeclarationMarker:
+ case SyntaxKind.MissingDeclaration:
// No need to visit nodes with no children.
return node;
@@ -240,13 +238,53 @@ namespace ts {
return updateComputedPropertyName(node,
visitNode((node).expression, visitor, isExpression));
- // Signature elements
+ // Signatures and Signature Elements
+ case SyntaxKind.FunctionType:
+ return updateFunctionTypeNode(node,
+ nodesVisitor((node).typeParameters, visitor, isTypeParameter),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
+ visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.ConstructorType:
+ return updateConstructorTypeNode(node,
+ nodesVisitor((node).typeParameters, visitor, isTypeParameter),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
+ visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.CallSignature:
+ return updateCallSignatureDeclaration(node,
+ nodesVisitor((node).typeParameters, visitor, isTypeParameter),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
+ visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.ConstructSignature:
+ return updateConstructSignatureDeclaration(node,
+ nodesVisitor((node).typeParameters, visitor, isTypeParameter),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
+ visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.MethodSignature:
+ return updateMethodSignature(node,
+ nodesVisitor((node).typeParameters, visitor, isTypeParameter),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
+ visitNode((node).type, visitor, isTypeNode),
+ visitNode((node).name, visitor, isPropertyName),
+ visitNode((node).questionToken, tokenVisitor, isToken));
+
+ case SyntaxKind.IndexSignature:
+ return updateIndexSignatureDeclaration(node,
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
+ visitNode((node).type, visitor, isTypeNode));
+
case SyntaxKind.Parameter:
return updateParameter(node,
- visitNodes((node).decorators, visitor, isDecorator),
- visitNodes((node).modifiers, visitor, isModifier),
- (node).dotDotDotToken,
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
+ visitNode((node).dotDotDotToken, tokenVisitor, isToken),
visitNode((node).name, visitor, isBindingName),
+ visitNode((node).questionToken, tokenVisitor, isToken),
visitNode((node).type, visitor, isTypeNode),
visitNode((node).initializer, visitor, isExpression));
@@ -254,62 +292,130 @@ namespace ts {
return updateDecorator(node,
visitNode((node).expression, visitor, isExpression));
- // Type member
+ // Types
+
+ case SyntaxKind.TypeReference:
+ return updateTypeReferenceNode(node,
+ visitNode((node).typeName, visitor, isEntityName),
+ nodesVisitor((node).typeArguments, visitor, isTypeNode));
+
+ case SyntaxKind.TypePredicate:
+ return updateTypePredicateNode(node,
+ visitNode((node).parameterName, visitor),
+ visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.TypeQuery:
+ return updateTypeQueryNode((node), visitNode((node).exprName, visitor, isEntityName));
+
+ case SyntaxKind.TypeLiteral:
+ return updateTypeLiteralNode((node), nodesVisitor((node).members, visitor));
+
+ case SyntaxKind.ArrayType:
+ return updateArrayTypeNode(node, visitNode((node).elementType, visitor, isTypeNode));
+
+ case SyntaxKind.TupleType:
+ return updateTypleTypeNode((node), nodesVisitor((node).elementTypes, visitor, isTypeNode));
+
+ case SyntaxKind.UnionType:
+ case SyntaxKind.IntersectionType:
+ return updateUnionOrIntersectionTypeNode(node,
+ nodesVisitor((node).types, visitor, isTypeNode));
+
+ case SyntaxKind.ParenthesizedType:
+ Debug.fail("not implemented.");
+
+ case SyntaxKind.TypeOperator:
+ return updateTypeOperatorNode(node, visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.IndexedAccessType:
+ return updateIndexedAccessTypeNode((node),
+ visitNode((node).objectType, visitor, isTypeNode),
+ visitNode((node).indexType, visitor, isTypeNode));
+
+ case SyntaxKind.MappedType:
+ return updateMappedTypeNode((node),
+ visitNode((node).readonlyToken, tokenVisitor, isToken),
+ visitNode((node).typeParameter, visitor, isTypeParameter),
+ visitNode((node).questionToken, tokenVisitor, isToken),
+ visitNode((node).type, visitor, isTypeNode));
+
+ case SyntaxKind.LiteralType:
+ return updateLiteralTypeNode(node,
+ visitNode((node).literal, visitor, isExpression));
+
+ // Type Declarations
+
+ case SyntaxKind.TypeParameter:
+ return updateTypeParameterDeclaration(node,
+ visitNode((node).name, visitor, isIdentifier),
+ visitNode((node).constraint, visitor, isTypeNode),
+ visitNode((node).default, visitor, isTypeNode));
+
+ // Type members
+
+ case SyntaxKind.PropertySignature:
+ return updatePropertySignature((node),
+ visitNode((node).name, visitor, isPropertyName),
+ visitNode((node).questionToken, tokenVisitor, isToken),
+ visitNode((node).type, visitor, isTypeNode),
+ visitNode((node).initializer, visitor, isExpression));
+
case SyntaxKind.PropertyDeclaration:
return updateProperty(node,
- visitNodes((node).decorators, visitor, isDecorator),
- visitNodes((node).modifiers, visitor, isModifier),
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
visitNode((node).name, visitor, isPropertyName),
visitNode((node).type, visitor, isTypeNode),
visitNode((node).initializer, visitor, isExpression));
case SyntaxKind.MethodDeclaration:
return updateMethod(node,
- visitNodes((node).decorators, visitor, isDecorator),
- visitNodes((node).modifiers, visitor, isModifier),
- (node).asteriskToken,
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
+ visitNode((node).asteriskToken, tokenVisitor, isToken),
visitNode((node).name, visitor, isPropertyName),
- visitNodes((node).typeParameters, visitor, isTypeParameter),
- visitParameterList((node).parameters, visitor, context),
+ visitNode((node).questionToken, tokenVisitor, isToken),
+ nodesVisitor((node).typeParameters, visitor, isTypeParameter),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
visitNode((node).type, visitor, isTypeNode),
visitFunctionBody((node).body, visitor, context));
case SyntaxKind.Constructor:
return updateConstructor(node,
- visitNodes((node).decorators, visitor, isDecorator),
- visitNodes((node).modifiers, visitor, isModifier),
- visitParameterList((node).parameters, visitor, context),
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
visitFunctionBody((node).body, visitor, context));
case SyntaxKind.GetAccessor:
return updateGetAccessor(node,
- visitNodes((node).decorators, visitor, isDecorator),
- visitNodes((node).modifiers, visitor, isModifier),
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
visitNode((node).name, visitor, isPropertyName),
- visitParameterList((node).parameters, visitor, context),
+ visitParameterList((node).parameters, visitor, context, nodesVisitor),
visitNode((node).type, visitor, isTypeNode),
visitFunctionBody((node).body, visitor, context));
case SyntaxKind.SetAccessor:
return updateSetAccessor(node,
- visitNodes((node).decorators, visitor, isDecorator),
- visitNodes((node).modifiers, visitor, isModifier),
+ nodesVisitor((node).decorators, visitor, isDecorator),
+ nodesVisitor((node).modifiers, visitor, isModifier),
visitNode((