diff --git a/.gitignore b/.gitignore
index 90b078fc94f..40c473d13dd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,3 +59,11 @@ internal/
.idea
yarn.lock
.parallelperf.*
+tests/cases/user/*/package-lock.json
+tests/cases/user/*/node_modules/
+tests/cases/user/*/**/*.js
+tests/cases/user/*/**/*.js.map
+tests/cases/user/*/**/*.d.ts
+!tests/cases/user/zone.js/
+!tests/cases/user/bignumber.js/
+!tests/cases/user/discord.js/
diff --git a/.travis.yml b/.travis.yml
index d24e155b580..06e912c55f5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,8 +2,8 @@ language: node_js
node_js:
- 'stable'
+ - '8'
- '6'
- - '4'
sudo: false
diff --git a/Gulpfile.ts b/Gulpfile.ts
index 5a27eb52b32..aedde5c33d9 100644
--- a/Gulpfile.ts
+++ b/Gulpfile.ts
@@ -46,14 +46,15 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
boolean: ["debug", "inspect", "light", "colors", "lint", "soft"],
string: ["browser", "tests", "host", "reporter", "stackTraceLimit", "timeout"],
alias: {
- b: "browser",
- d: "debug", "debug-brk": "debug",
- i: "inspect", "inspect-brk": "inspect",
- t: "tests", test: "tests",
- r: "reporter",
- c: "colors", color: "colors",
- f: "files", file: "files",
- w: "workers",
+ "b": "browser",
+ "d": "debug", "debug-brk": "debug",
+ "i": "inspect", "inspect-brk": "inspect",
+ "t": "tests", "test": "tests",
+ "ru": "runners", "runner": "runners",
+ "r": "reporter",
+ "c": "colors", "color": "colors",
+ "f": "files", "file": "files",
+ "w": "workers",
},
default: {
soft: false,
@@ -64,6 +65,7 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
browser: process.env.browser || process.env.b || "IE",
timeout: process.env.timeout || 40000,
tests: process.env.test || process.env.tests || process.env.t,
+ runners: process.env.runners || process.env.runner || process.env.ru,
light: process.env.light === undefined || process.env.light !== "false",
reporter: process.env.reporter || process.env.r,
lint: process.env.lint || true,
@@ -72,7 +74,8 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
}
});
-function exec(cmd: string, args: string[], complete: () => void = (() => { }), error: (e: any, status: number) => void = (() => { })) {
+const noop = () => {}; // tslint:disable-line no-empty
+function exec(cmd: string, args: string[], complete: () => void = noop, error: (e: any, status: number) => void = noop) {
console.log(`${cmd} ${args.join(" ")}`);
// TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition
const subshellFlag = isWin ? "/c" : "-c";
@@ -99,12 +102,12 @@ const lclDirectory = "src/loc/lcl";
const builtDirectory = "built/";
const builtLocalDirectory = "built/local/";
-const LKGDirectory = "lib/";
+const lkgDirectory = "lib/";
const copyright = "CopyrightNotice.txt";
const compilerFilename = "tsc.js";
-const LKGCompiler = path.join(LKGDirectory, compilerFilename);
+const lkgCompiler = path.join(lkgDirectory, compilerFilename);
const builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
const nodeModulesPathPrefix = path.resolve("./node_modules/.bin/");
@@ -123,34 +126,31 @@ const es2015LibrarySources = [
"es2015.symbol.wellknown.d.ts"
];
-const es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
- return { target: "lib." + source, sources: ["header.d.ts", source] };
-});
+const es2015LibrarySourceMap = es2015LibrarySources.map(source =>
+ ({ target: "lib." + source, sources: ["header.d.ts", source] }));
const es2016LibrarySource = ["es2016.array.include.d.ts"];
-const es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
- return { target: "lib." + source, sources: ["header.d.ts", source] };
-});
+const es2016LibrarySourceMap = es2016LibrarySource.map(source =>
+ ({ target: "lib." + source, sources: ["header.d.ts", source] }));
const es2017LibrarySource = [
"es2017.object.d.ts",
"es2017.sharedmemory.d.ts",
"es2017.string.d.ts",
"es2017.intl.d.ts",
+ "es2017.typedarrays.d.ts",
];
-const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) {
- return { target: "lib." + source, sources: ["header.d.ts", source] };
-});
+const es2017LibrarySourceMap = es2017LibrarySource.map(source =>
+ ({ target: "lib." + source, sources: ["header.d.ts", source] }));
const esnextLibrarySource = [
"esnext.asynciterable.d.ts"
];
-const esnextLibrarySourceMap = esnextLibrarySource.map(function (source) {
- return { target: "lib." + source, sources: ["header.d.ts", source] };
-});
+const esnextLibrarySourceMap = esnextLibrarySource.map(source =>
+ ({ target: "lib." + source, sources: ["header.d.ts", source] }));
const hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"];
@@ -171,14 +171,13 @@ const librarySourceMap = [
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
- { target: "lib.es2016.full.d.ts", sources: ["header.d.ts", "es2016.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
- { target: "lib.es2017.full.d.ts", sources: ["header.d.ts", "es2017.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
- { target: "lib.esnext.full.d.ts", sources: ["header.d.ts", "esnext.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
+ { target: "lib.es2016.full.d.ts", sources: ["header.d.ts", "es2016.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") },
+ { target: "lib.es2017.full.d.ts", sources: ["header.d.ts", "es2017.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") },
+ { target: "lib.esnext.full.d.ts", sources: ["header.d.ts", "esnext.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, esnextLibrarySourceMap);
-const libraryTargets = librarySourceMap.map(function(f) {
- return path.join(builtLocalDirectory, f.target);
-});
+const libraryTargets = librarySourceMap.map(f =>
+ path.join(builtLocalDirectory, f.target));
/**
* .lcg file is what localization team uses to know what messages to localize.
@@ -193,22 +192,19 @@ const generatedLCGFile = path.join(builtLocalDirectory, "enu", "diagnosticMessag
* 2. 'src\compiler\diagnosticMessages.generated.json' => 'built\local\ENU\diagnosticMessages.generated.json.lcg'
* generate the lcg file (source of messages to localize) from the diagnosticMessages.generated.json
*/
-const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-CN", "zh-TW"].map(function (f) {
- return path.join(builtLocalDirectory, f, "diagnosticMessages.generated.json");
-}).concat(generatedLCGFile);
+const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-BR", "ru", "tr", "zh-CN", "zh-TW"]
+ .map(f => path.join(builtLocalDirectory, f, "diagnosticMessages.generated.json"))
+ .concat(generatedLCGFile);
for (const i in libraryTargets) {
const entry = librarySourceMap[i];
const target = libraryTargets[i];
- const sources = [copyright].concat(entry.sources.map(function(s) {
- return path.join(libraryDirectory, s);
- }));
- gulp.task(target, /*help*/ false, [], function() {
- return gulp.src(sources)
+ const sources = [copyright].concat(entry.sources.map(s => path.join(libraryDirectory, s)));
+ gulp.task(target, /*help*/ false, [], () =>
+ gulp.src(sources)
.pipe(newer(target))
.pipe(concat(target, { newLine: "\n\n" }))
- .pipe(gulp.dest("."));
- });
+ .pipe(gulp.dest(".")));
}
const configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js");
@@ -575,9 +571,7 @@ gulp.task(specMd, /*help*/ false, [word2mdJs], (done) => {
const specMDFullPath = path.resolve(specMd);
const cmd = "cscript //nologo " + word2mdJs + " \"" + specWordFullPath + "\" " + "\"" + specMDFullPath + "\"";
console.log(cmd);
- cp.exec(cmd, function() {
- done();
- });
+ cp.exec(cmd, done);
});
gulp.task("generate-spec", "Generates a Markdown version of the Language Specification", [specMd]);
@@ -599,7 +593,7 @@ gulp.task("VerifyLKG", /*help*/ false, [], () => {
". The following files are missing:\n" + missingFiles.join("\n"));
}
// Copy all the targets into the LKG directory
- return gulp.src([...expectedFiles, path.join(builtLocalDirectory, "**"), `!${path.join(builtLocalDirectory, "tslint")}`, `!${path.join(builtLocalDirectory, "*.*")}`]).pipe(gulp.dest(LKGDirectory));
+ return gulp.src([...expectedFiles, path.join(builtLocalDirectory, "**"), `!${path.join(builtLocalDirectory, "tslint")}`, `!${path.join(builtLocalDirectory, "*.*")}`]).pipe(gulp.dest(lkgDirectory));
});
gulp.task("LKGInternal", /*help*/ false, ["lib", "local"]);
@@ -658,6 +652,7 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done:
const debug = cmdLineOptions.debug;
const inspect = cmdLineOptions.inspect;
const tests = cmdLineOptions.tests;
+ const runners = cmdLineOptions.runners;
const light = cmdLineOptions.light;
const stackTraceLimit = cmdLineOptions.stackTraceLimit;
const testConfigFile = "test.config";
@@ -678,8 +673,8 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done:
workerCount = cmdLineOptions.workers;
}
- if (tests || light || taskConfigsFolder) {
- writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit);
+ if (tests || runners || light || taskConfigsFolder) {
+ writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit);
}
if (tests && tests.toLocaleLowerCase() === "rwc") {
@@ -714,17 +709,13 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done:
}
args.push(run);
setNodeEnvToDevelopment();
- exec(mocha, args, lintThenFinish, function(e, status) {
- finish(e, status);
- });
+ exec(mocha, args, lintThenFinish, finish);
}
else {
// run task to load all tests and partition them between workers
setNodeEnvToDevelopment();
- exec(host, [run], lintThenFinish, function(e, status) {
- finish(e, status);
- });
+ exec(host, [run], lintThenFinish, finish);
}
});
@@ -874,8 +865,8 @@ function cleanTestDirs(done: (e?: any) => void) {
}
// used to pass data from jake command line directly to run.js
-function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?: string, workerCount?: number, stackTraceLimit?: string) {
- const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light, workerCount, stackTraceLimit, taskConfigsFolder, noColor: !cmdLineOptions.colors });
+function writeTestConfigFile(tests: string, runners: string, light: boolean, taskConfigsFolder?: string, workerCount?: number, stackTraceLimit?: string) {
+ const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, runner: runners ? runners.split(",") : undefined, light, workerCount, stackTraceLimit, taskConfigsFolder, noColor: !cmdLineOptions.colors });
console.log("Running tests with config: " + testConfigContents);
fs.writeFileSync("test.config", testConfigContents);
}
@@ -886,13 +877,14 @@ gulp.task("runtests-browser", "Runs the tests using the built run.js file like '
if (err) { console.error(err); done(err); process.exit(1); }
host = "node";
const tests = cmdLineOptions.tests;
+ const runners = cmdLineOptions.runners;
const light = cmdLineOptions.light;
const testConfigFile = "test.config";
if (fs.existsSync(testConfigFile)) {
fs.unlinkSync(testConfigFile);
}
- if (tests || light) {
- writeTestConfigFile(tests, light);
+ if (tests || runners || light) {
+ writeTestConfigFile(tests, runners, light);
}
const args = [nodeServerOutFile];
@@ -1006,7 +998,7 @@ gulp.task(loggedIOJsPath, /*help*/ false, [], (done) => {
const temp = path.join(builtLocalDirectory, "temp");
mkdirP(temp, (err) => {
if (err) { console.error(err); done(err); process.exit(1); }
- exec(host, [LKGCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => {
+ exec(host, [lkgCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => {
fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath);
del(temp).then(() => done(), done);
}, done);
@@ -1043,7 +1035,7 @@ gulp.task("update-sublime", "Updates the sublime plugin's tsserver", ["local", s
});
gulp.task("build-rules", "Compiles tslint rules to js", () => {
- const settings: tsc.Settings = getCompilerSettings({ module: "commonjs", "lib": ["es6"] }, /*useBuiltCompiler*/ false);
+ const settings: tsc.Settings = getCompilerSettings({ module: "commonjs", lib: ["es6"] }, /*useBuiltCompiler*/ false);
const dest = path.join(builtLocalDirectory, "tslint");
return gulp.src("scripts/tslint/**/*.ts")
.pipe(newer({
@@ -1082,7 +1074,7 @@ function sendNextFile(files: {path: string}[], child: cp.ChildProcess, callback:
function spawnLintWorker(files: {path: string}[], callback: (failures: number) => void) {
const child = cp.fork("./scripts/parallel-lint");
let failures = 0;
- child.on("message", function(data) {
+ child.on("message", data => {
switch (data.kind) {
case "result":
if (data.failures > 0) {
@@ -1106,7 +1098,7 @@ gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are:
const fileMatcher = cmdLineOptions.files;
const files = fileMatcher
? `src/**/${fileMatcher}`
- : "Gulpfile.ts 'scripts/generateLocalizedDiagnosticMessages.ts' 'scripts/tslint/**/*.ts' 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
+ : "Gulpfile.ts 'scripts/generateLocalizedDiagnosticMessages.ts' 'scripts/tslint/**/*.ts' 'src/**/*.ts' --exclude 'src/lib/*.d.ts'";
const cmd = `node node_modules/tslint/bin/tslint ${files} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`;
console.log("Linting: " + cmd);
child_process.execSync(cmd, { stdio: [0, 1, 2] });
diff --git a/Jakefile.js b/Jakefile.js
index da7d96f0699..c2d0717641f 100644
--- a/Jakefile.js
+++ b/Jakefile.js
@@ -105,6 +105,7 @@ var harnessCoreSources = [
"projectsRunner.ts",
"loggedIO.ts",
"rwcRunner.ts",
+ "externalCompileRunner.ts",
"test262Runner.ts",
"./parallel/shared.ts",
"./parallel/host.ts",
@@ -196,7 +197,8 @@ var es2017LibrarySource = [
"es2017.object.d.ts",
"es2017.sharedmemory.d.ts",
"es2017.string.d.ts",
- "es2017.intl.d.ts"
+ "es2017.intl.d.ts",
+ "es2017.typedarrays.d.ts",
];
var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
@@ -843,8 +845,9 @@ function cleanTestDirs() {
}
// used to pass data from jake command line directly to run.js
-function writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit, colors) {
+function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors) {
var testConfigContents = JSON.stringify({
+ runners: runners ? runners.split(",") : undefined,
test: tests ? [tests] : undefined,
light: light,
workerCount: workerCount,
@@ -870,6 +873,7 @@ function runConsoleTests(defaultReporter, runInParallel) {
var debug = process.env.debug || process.env["debug-brk"] || process.env.d;
var inspect = process.env.inspect || process.env["inspect-brk"] || process.env.i;
var testTimeout = process.env.timeout || defaultTestTimeout;
+ var runners = process.env.runners || process.env.runner || process.env.ru;
var tests = process.env.test || process.env.tests || process.env.t;
var light = process.env.light === undefined || process.env.light !== "false";
var stackTraceLimit = process.env.stackTraceLimit;
@@ -891,8 +895,8 @@ function runConsoleTests(defaultReporter, runInParallel) {
workerCount = process.env.workerCount || process.env.p || os.cpus().length;
}
- if (tests || light || taskConfigsFolder) {
- writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit, colors);
+ if (tests || runners || light || taskConfigsFolder) {
+ writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors);
}
if (tests && tests.toLocaleLowerCase() === "rwc") {
@@ -1027,14 +1031,15 @@ task("runtests-browser", ["browserify", nodeServerOutFile], function () {
cleanTestDirs();
host = "node";
var browser = process.env.browser || process.env.b || (os.platform() === "linux" ? "chrome" : "IE");
+ var runners = process.env.runners || process.env.runner || process.env.ru;
var tests = process.env.test || process.env.tests || process.env.t;
var light = process.env.light || false;
var testConfigFile = 'test.config';
if (fs.existsSync(testConfigFile)) {
fs.unlinkSync(testConfigFile);
}
- if (tests || light) {
- writeTestConfigFile(tests, light);
+ if (tests || runners || light) {
+ writeTestConfigFile(tests, runners, light);
}
tests = tests ? tests : '';
@@ -1282,7 +1287,7 @@ task("lint", ["build-rules"], () => {
const fileMatcher = process.env.f || process.env.file || process.env.files;
const files = fileMatcher
? `src/**/${fileMatcher}`
- : "Gulpfile.ts 'scripts/generateLocalizedDiagnosticMessages.ts' 'scripts/tslint/**/*.ts' 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
+ : "Gulpfile.ts 'scripts/generateLocalizedDiagnosticMessages.ts' 'scripts/tslint/**/*.ts' 'src/**/*.ts' --exclude 'src/lib/*.d.ts'";
const cmd = `node node_modules/tslint/bin/tslint ${files} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish`;
console.log("Linting: " + cmd);
jake.exec([cmd], { interactive: true }, () => {
diff --git a/netci.groovy b/netci.groovy
index fc6d00e4e7f..5fa8b02baf2 100644
--- a/netci.groovy
+++ b/netci.groovy
@@ -5,7 +5,7 @@ import jobs.generation.Utilities;
def project = GithubProject
def branch = GithubBranchName
-def nodeVersions = ['stable', '6', '4']
+def nodeVersions = ['stable', '8', '6']
nodeVersions.each { nodeVer ->
diff --git a/package.json b/package.json
index e76d480937c..e329db05d85 100644
--- a/package.json
+++ b/package.json
@@ -74,10 +74,12 @@
"q": "latest",
"run-sequence": "latest",
"sorcery": "latest",
+ "source-map-support": "latest",
"through2": "latest",
"travis-fold": "latest",
"ts-node": "latest",
"tslint": "latest",
+ "vinyl": "latest",
"colors": "latest",
"typescript": "next"
},
diff --git a/scripts/generateLocalizedDiagnosticMessages.ts b/scripts/generateLocalizedDiagnosticMessages.ts
index 36df92590c7..566eb557fd5 100644
--- a/scripts/generateLocalizedDiagnosticMessages.ts
+++ b/scripts/generateLocalizedDiagnosticMessages.ts
@@ -65,10 +65,11 @@ function main(): void {
* There are three exceptions, zh-CN, zh-TW and pt-BR.
*/
function getPreferedLocaleName(localeName: string) {
+ localeName = localeName.toLowerCase();
switch (localeName) {
- case "zh-CN":
- case "zh-TW":
- case "pt-BR":
+ case "zh-cn":
+ case "zh-tw":
+ case "pt-br":
return localeName;
default:
return localeName.split("-")[0];
@@ -86,9 +87,9 @@ function main(): void {
const out: any = {};
for (const item of o.LCX.Item[0].Item[0].Item) {
let ItemId = item.$.ItemId;
- let Val = item.Str[0].Tgt ? item.Str[0].Tgt[0].Val[0] : item.Str[0].Val[0];
+ let val = item.Str[0].Tgt ? item.Str[0].Tgt[0].Val[0] : item.Str[0].Val[0];
- if (typeof ItemId !== "string" || typeof Val !== "string") {
+ if (typeof ItemId !== "string" || typeof val !== "string") {
console.error("Unexpected XML file structure");
process.exit(1);
}
@@ -97,8 +98,8 @@ function main(): void {
ItemId = ItemId.slice(1); // remove leading semicolon
}
- Val = Val.replace(/]5D;/, "]"); // unescape `]`
- out[ItemId] = Val;
+ val = val.replace(/]5D;/, "]"); // unescape `]`
+ out[ItemId] = val;
}
return JSON.stringify(out, undefined, 2);
}
diff --git a/scripts/ior.ts b/scripts/ior.ts
index 91580203350..374747d8439 100644
--- a/scripts/ior.ts
+++ b/scripts/ior.ts
@@ -64,7 +64,6 @@ module Commands {
}
if (path.charAt(1) === ":") {
if (path.charAt(2) === directorySeparator) return 3;
- return 2;
}
return 0;
}
diff --git a/scripts/processDiagnosticMessages.ts b/scripts/processDiagnosticMessages.ts
index ff4047d310d..dd66564b134 100644
--- a/scripts/processDiagnosticMessages.ts
+++ b/scripts/processDiagnosticMessages.ts
@@ -1,4 +1,5 @@
///
+///
interface DiagnosticDetails {
category: string;
@@ -9,80 +10,79 @@ interface DiagnosticDetails {
type InputDiagnosticMessageTable = ts.Map;
function main(): void {
- var sys = ts.sys;
+ const sys = ts.sys;
if (sys.args.length < 1) {
- sys.write("Usage:" + sys.newLine)
+ sys.write("Usage:" + sys.newLine);
sys.write("\tnode processDiagnosticMessages.js " + sys.newLine);
return;
}
function writeFile(fileName: string, contents: string) {
- // TODO: Fix path joining
- var inputDirectory = inputFilePath.substr(0,inputFilePath.lastIndexOf("/"));
- var fileOutputPath = inputDirectory + "/" + fileName;
+ const inputDirectory = ts.getDirectoryPath(inputFilePath);
+ const fileOutputPath = ts.combinePaths(inputDirectory, fileName);
sys.writeFile(fileOutputPath, contents);
}
- var inputFilePath = sys.args[0].replace(/\\/g, "/");
- var inputStr = sys.readFile(inputFilePath);
+ const inputFilePath = sys.args[0].replace(/\\/g, "/");
+ const inputStr = sys.readFile(inputFilePath);
- var diagnosticMessagesJson: { [key: string]: DiagnosticDetails } = JSON.parse(inputStr);
- // Check that there are no duplicates.
- const seenNames = ts.createMap();
- for (const name of Object.keys(diagnosticMessagesJson)) {
- if (seenNames.has(name))
- throw new Error(`Name ${name} appears twice`);
- seenNames.set(name, true);
- }
+ const diagnosticMessagesJson: { [key: string]: DiagnosticDetails } = JSON.parse(inputStr);
const diagnosticMessages: InputDiagnosticMessageTable = ts.createMapFromTemplate(diagnosticMessagesJson);
- var infoFileOutput = buildInfoFileOutput(diagnosticMessages);
+ const outputFilesDir = ts.getDirectoryPath(inputFilePath);
+ const thisFilePathRel = ts.getRelativePathToDirectoryOrUrl(outputFilesDir, sys.getExecutingFilePath(),
+ sys.getCurrentDirectory(), ts.createGetCanonicalFileName(sys.useCaseSensitiveFileNames), /* isAbsolutePathAnUrl */ false);
+
+ const infoFileOutput = buildInfoFileOutput(diagnosticMessages, "./diagnosticInformationMap.generated.ts", thisFilePathRel);
checkForUniqueCodes(diagnosticMessages);
writeFile("diagnosticInformationMap.generated.ts", infoFileOutput);
- var messageOutput = buildDiagnosticMessageOutput(diagnosticMessages);
+ const messageOutput = buildDiagnosticMessageOutput(diagnosticMessages);
writeFile("diagnosticMessages.generated.json", messageOutput);
}
function checkForUniqueCodes(diagnosticTable: InputDiagnosticMessageTable) {
const allCodes: { [key: number]: true | undefined } = [];
diagnosticTable.forEach(({ code }) => {
- if (allCodes[code])
+ if (allCodes[code]) {
throw new Error(`Diagnostic code ${code} appears more than once.`);
+ }
allCodes[code] = true;
});
}
-function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable): string {
- var result =
- '// \r\n' +
- '/// \r\n' +
- '/* @internal */\r\n' +
- 'namespace ts {\r\n' +
+function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, inputFilePathRel: string, thisFilePathRel: string): string {
+ let result =
+ "// \r\n" +
+ "// generated from '" + inputFilePathRel + "' by '" + thisFilePathRel + "'\r\n" +
+ "/// \r\n" +
+ "/* @internal */\r\n" +
+ "namespace ts {\r\n" +
" function diag(code: number, category: DiagnosticCategory, key: string, message: string): DiagnosticMessage {\r\n" +
" return { code, category, key, message };\r\n" +
" }\r\n" +
- ' export const Diagnostics = {\r\n';
+ " // tslint:disable-next-line variable-name\r\n" +
+ " export const Diagnostics = {\r\n";
messageTable.forEach(({ code, category }, name) => {
const propName = convertPropertyName(name);
result += ` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}),\r\n`;
});
- result += ' };\r\n}';
+ result += " };\r\n}";
return result;
}
function buildDiagnosticMessageOutput(messageTable: InputDiagnosticMessageTable): string {
- let result = '{';
+ let result = "{";
messageTable.forEach(({ code }, name) => {
const propName = convertPropertyName(name);
result += `\r\n "${createKey(propName, code)}" : "${name.replace(/[\"]/g, '\\"')}",`;
});
// Shave trailing comma, then add newline and ending brace
- result = result.slice(0, result.length - 1) + '\r\n}';
+ result = result.slice(0, result.length - 1) + "\r\n}";
// Assert that we generated valid JSON
JSON.parse(result);
@@ -90,15 +90,15 @@ function buildDiagnosticMessageOutput(messageTable: InputDiagnosticMessageTable)
return result;
}
-function createKey(name: string, code: number) : string {
- return name.slice(0, 100) + '_' + code;
+function createKey(name: string, code: number): string {
+ return name.slice(0, 100) + "_" + code;
}
function convertPropertyName(origName: string): string {
- var result = origName.split("").map(char => {
- if (char === '*') { return "_Asterisk"; }
- if (char === '/') { return "_Slash"; }
- if (char === ':') { return "_Colon"; }
+ let result = origName.split("").map(char => {
+ if (char === "*") { return "_Asterisk"; }
+ if (char === "/") { return "_Slash"; }
+ if (char === ":") { return "_Colon"; }
return /\w/.test(char) ? char : "_";
}).join("");
@@ -106,7 +106,7 @@ function convertPropertyName(origName: string): string {
result = result.replace(/_+/g, "_");
// remove any leading underscore, unless it is followed by a number.
- result = result.replace(/^_([^\d])/, "$1")
+ result = result.replace(/^_([^\d])/, "$1");
// get rid of all trailing underscores.
result = result.replace(/_$/, "");
diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts
index 35a62a644d8..4e89abde780 100644
--- a/src/compiler/binder.ts
+++ b/src/compiler/binder.ts
@@ -133,7 +133,7 @@ namespace ts {
let symbolCount = 0;
- let Symbol: { new (flags: SymbolFlags, name: __String): Symbol };
+ let Symbol: { new (flags: SymbolFlags, name: __String): Symbol }; // tslint:disable-line variable-name
let classifiableNames: UnderscoreEscapedMap;
const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
@@ -192,7 +192,7 @@ namespace ts {
return bindSourceFile;
function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean {
- if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) {
+ if (getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
// bind in strict mode source files with alwaysStrict option
return true;
}
@@ -1550,7 +1550,7 @@ namespace ts {
function setExportContextFlag(node: ModuleDeclaration | SourceFile) {
// A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
// declarations with export modifiers) is an export context in which declarations are implicitly exported.
- if (isInAmbientContext(node) && !hasExportDeclarations(node)) {
+ if (node.flags & NodeFlags.Ambient && !hasExportDeclarations(node)) {
node.flags |= NodeFlags.ExportContext;
}
else {
@@ -1726,7 +1726,7 @@ namespace ts {
node.originalKeywordKind >= SyntaxKind.FirstFutureReservedWord &&
node.originalKeywordKind <= SyntaxKind.LastFutureReservedWord &&
!isIdentifierName(node) &&
- !isInAmbientContext(node)) {
+ !(node.flags & NodeFlags.Ambient)) {
// Report error only if there are no parse errors in file
if (!file.parseDiagnostics.length) {
@@ -2205,15 +2205,14 @@ namespace ts {
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
}
else {
- // An export default clause with an expression exports a value
- // We want to exclude both class and function here, this is necessary to issue an error when there are both
- // default export-assignment and default export function and class declaration.
- const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node)
+ const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node)
// An export default clause with an EntityNameExpression exports all meanings of that identifier
? SymbolFlags.Alias
// An export default clause with any other expression exports a value
: SymbolFlags.Property;
- declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.Property | SymbolFlags.AliasExcludes | SymbolFlags.Class | SymbolFlags.Function);
+ // If there is an `export default x;` alias declaration, can't `export default` anything else.
+ // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
+ declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All);
}
}
@@ -2481,7 +2480,7 @@ namespace ts {
}
function bindParameter(node: ParameterDeclaration) {
- if (inStrictMode && !isInAmbientContext(node)) {
+ if (inStrictMode && !(node.flags & NodeFlags.Ambient)) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
checkStrictModeEvalOrArguments(node, node.name);
@@ -2503,7 +2502,7 @@ namespace ts {
}
function bindFunctionDeclaration(node: FunctionDeclaration) {
- if (!file.isDeclarationFile && !isInAmbientContext(node)) {
+ if (!file.isDeclarationFile && !(node.flags & NodeFlags.Ambient)) {
if (isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
@@ -2520,7 +2519,7 @@ namespace ts {
}
function bindFunctionExpression(node: FunctionExpression) {
- if (!file.isDeclarationFile && !isInAmbientContext(node)) {
+ if (!file.isDeclarationFile && !(node.flags & NodeFlags.Ambient)) {
if (isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
@@ -2534,7 +2533,7 @@ namespace ts {
}
function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
- if (!file.isDeclarationFile && !isInAmbientContext(node) && isAsyncFunction(node)) {
+ if (!file.isDeclarationFile && !(node.flags & NodeFlags.Ambient) && isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
@@ -2583,7 +2582,7 @@ namespace ts {
// On the other side we do want to report errors on non-initialized 'lets' because of TDZ
const reportUnreachableCode =
!options.allowUnreachableCode &&
- !isInAmbientContext(node) &&
+ !(node.flags & NodeFlags.Ambient) &&
(
node.kind !== SyntaxKind.VariableStatement ||
getCombinedNodeFlags((node).declarationList) & NodeFlags.BlockScoped ||
@@ -2963,6 +2962,7 @@ namespace ts {
|| hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.typeParameters
|| node.type
+ || (node.name && isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -2993,6 +2993,7 @@ namespace ts {
if (node.decorators
|| hasModifier(node, ModifierFlags.TypeScriptModifier)
|| node.type
+ || (node.name && isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly
|| !node.body) {
transformFlags |= TransformFlags.AssertTypeScript;
}
@@ -3296,6 +3297,9 @@ namespace ts {
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxText:
case SyntaxKind.JsxClosingElement:
+ case SyntaxKind.JsxFragment:
+ case SyntaxKind.JsxOpeningFragment:
+ case SyntaxKind.JsxClosingFragment:
case SyntaxKind.JsxAttribute:
case SyntaxKind.JsxAttributes:
case SyntaxKind.JsxSpreadAttribute:
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts
index aaaa0ed50b8..a9aaa77fa74 100644
--- a/src/compiler/checker.ts
+++ b/src/compiler/checker.ts
@@ -48,9 +48,11 @@ namespace ts {
let requestedExternalEmitHelpers: ExternalEmitHelpers;
let externalHelpersModule: Symbol;
+ // tslint:disable variable-name
const Symbol = objectAllocator.getSymbolConstructor();
const Type = objectAllocator.getTypeConstructor();
const Signature = objectAllocator.getSignatureConstructor();
+ // tslint:enable variable-name
let typeCount = 0;
let symbolCount = 0;
@@ -64,11 +66,11 @@ namespace ts {
const languageVersion = getEmitScriptTarget(compilerOptions);
const modulekind = getEmitModuleKind(compilerOptions);
const noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters;
- const allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ModuleKind.System;
- const strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks;
- const strictFunctionTypes = compilerOptions.strictFunctionTypes === undefined ? compilerOptions.strict : compilerOptions.strictFunctionTypes;
- const noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny;
- const noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis;
+ const allowSyntheticDefaultImports = getAllowSyntheticDefaultImports(compilerOptions);
+ const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
+ const strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes");
+ const noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny");
+ const noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis");
const emitResolver = createResolver();
const nodeBuilder = createNodeBuilder();
@@ -260,6 +262,7 @@ namespace ts {
const literalTypes = createMap();
const indexedAccessTypes = createMap();
const evolvingArrayTypes: EvolvingArrayType[] = [];
+ const undefinedProperties = createMap() as UnderscoreEscapedMap;
const unknownSymbol = createSymbol(SymbolFlags.Property, "unknown" as __String);
const resolvingSymbol = createSymbol(0, InternalSymbolName.Resolving);
@@ -280,6 +283,7 @@ namespace ts {
const voidType = createIntrinsicType(TypeFlags.Void, "void");
const neverType = createIntrinsicType(TypeFlags.Never, "never");
const silentNeverType = createIntrinsicType(TypeFlags.Never, "never");
+ const implicitNeverType = createIntrinsicType(TypeFlags.Never, "never");
const nonPrimitiveType = createIntrinsicType(TypeFlags.NonPrimitive, "object");
const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined);
@@ -451,29 +455,29 @@ namespace ts {
}
const typeofEQFacts = createMapFromTemplate({
- "string": TypeFacts.TypeofEQString,
- "number": TypeFacts.TypeofEQNumber,
- "boolean": TypeFacts.TypeofEQBoolean,
- "symbol": TypeFacts.TypeofEQSymbol,
- "undefined": TypeFacts.EQUndefined,
- "object": TypeFacts.TypeofEQObject,
- "function": TypeFacts.TypeofEQFunction
+ string: TypeFacts.TypeofEQString,
+ number: TypeFacts.TypeofEQNumber,
+ boolean: TypeFacts.TypeofEQBoolean,
+ symbol: TypeFacts.TypeofEQSymbol,
+ undefined: TypeFacts.EQUndefined,
+ object: TypeFacts.TypeofEQObject,
+ function: TypeFacts.TypeofEQFunction
});
const typeofNEFacts = createMapFromTemplate({
- "string": TypeFacts.TypeofNEString,
- "number": TypeFacts.TypeofNENumber,
- "boolean": TypeFacts.TypeofNEBoolean,
- "symbol": TypeFacts.TypeofNESymbol,
- "undefined": TypeFacts.NEUndefined,
- "object": TypeFacts.TypeofNEObject,
- "function": TypeFacts.TypeofNEFunction
+ string: TypeFacts.TypeofNEString,
+ number: TypeFacts.TypeofNENumber,
+ boolean: TypeFacts.TypeofNEBoolean,
+ symbol: TypeFacts.TypeofNESymbol,
+ undefined: TypeFacts.NEUndefined,
+ object: TypeFacts.TypeofNEObject,
+ function: TypeFacts.TypeofNEFunction
});
const typeofTypesByName = createMapFromTemplate({
- "string": stringType,
- "number": numberType,
- "boolean": booleanType,
- "symbol": esSymbolType,
- "undefined": undefinedType
+ string: stringType,
+ number: numberType,
+ boolean: booleanType,
+ symbol: esSymbolType,
+ undefined: undefinedType
});
const typeofType = createTypeofType();
@@ -487,17 +491,6 @@ namespace ts {
/** Things we lazy load from the JSX namespace */
const jsxTypes = createUnderscoreEscapedMap();
- const JsxNames = {
- JSX: "JSX" as __String,
- IntrinsicElements: "IntrinsicElements" as __String,
- ElementClass: "ElementClass" as __String,
- ElementAttributesPropertyNameContainer: "ElementAttributesProperty" as __String,
- ElementChildrenAttributeNameContainer: "ElementChildrenAttribute" as __String,
- Element: "Element" as __String,
- IntrinsicAttributes: "IntrinsicAttributes" as __String,
- IntrinsicClassAttributes: "IntrinsicClassAttributes" as __String
- };
-
const subtypeRelation = createMap();
const assignableRelation = createMap();
const comparableRelation = createMap();
@@ -528,6 +521,11 @@ namespace ts {
Strict,
}
+ const enum MappedTypeModifiers {
+ Readonly = 1 << 0,
+ Optional = 1 << 1,
+ }
+
const builtinGlobals = createSymbolTable();
builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
@@ -690,7 +688,7 @@ namespace ts {
else {
// find a module that about to be augmented
// do not validate names of augmentations that are defined in ambient context
- const moduleNotFoundError = !isInAmbientContext(moduleName.parent.parent)
+ const moduleNotFoundError = !(moduleName.parent.parent.flags & NodeFlags.Ambient)
? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
: undefined;
let mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
@@ -795,7 +793,7 @@ namespace ts {
if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
(!compilerOptions.outFile && !compilerOptions.out) ||
isInTypeQuery(usage) ||
- isInAmbientContext(declaration)) {
+ declaration.flags & NodeFlags.Ambient) {
// nodes are in different files and order cannot be determined
return true;
}
@@ -1367,7 +1365,7 @@ namespace ts {
}
}
else if (meaning & (SymbolFlags.Type & ~SymbolFlags.NamespaceModule & ~SymbolFlags.Value)) {
- const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.NamespaceModule & ~SymbolFlags.Type, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
+ const symbol = resolveSymbol(resolveName(errorLocation, name, (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule) & ~SymbolFlags.Type, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol) {
error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name));
return true;
@@ -1383,7 +1381,7 @@ namespace ts {
Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined");
- if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
+ if (!(declaration.flags & NodeFlags.Ambient) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
if (result.flags & SymbolFlags.BlockScopedVariable) {
error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration)));
}
@@ -1906,8 +1904,9 @@ namespace ts {
* Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
* Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
*/
- function extendExportSymbols(target: SymbolTable, source: SymbolTable, lookupTable?: ExportCollisionTrackerTable, exportNode?: ExportDeclaration) {
- source && source.forEach((sourceSymbol, id) => {
+ function extendExportSymbols(target: SymbolTable, source: SymbolTable | undefined, lookupTable?: ExportCollisionTrackerTable, exportNode?: ExportDeclaration) {
+ if (!source) return;
+ source.forEach((sourceSymbol, id) => {
if (id === "default") return;
const targetSymbol = target.get(id);
@@ -2162,7 +2161,6 @@ namespace ts {
return forEachEntry(symbols, symbolFromSymbolTable => {
if (symbolFromSymbolTable.flags & SymbolFlags.Alias
&& symbolFromSymbolTable.escapedName !== "export="
- && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)
&& !(isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && isExternalModule(getSourceFileOfNode(enclosingDeclaration)))
// If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
&& (!useOnlyExternalAliasing || some(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration))) {
@@ -2443,18 +2441,21 @@ namespace ts {
function createNodeBuilder() {
return {
typeToTypeNode: (type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => {
+ Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & NodeFlags.Synthesized) === 0);
const context = createNodeBuilderContext(enclosingDeclaration, flags);
const resultingNode = typeToTypeNodeHelper(type, context);
const result = context.encounteredError ? undefined : resultingNode;
return result;
},
indexInfoToIndexSignatureDeclaration: (indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => {
+ Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & NodeFlags.Synthesized) === 0);
const context = createNodeBuilderContext(enclosingDeclaration, flags);
const resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context);
const result = context.encounteredError ? undefined : resultingNode;
return result;
},
signatureToSignatureDeclaration: (signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags) => {
+ Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & NodeFlags.Synthesized) === 0);
const context = createNodeBuilderContext(enclosingDeclaration, flags);
const resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context);
const result = context.encounteredError ? undefined : resultingNode;
@@ -2495,7 +2496,7 @@ namespace ts {
if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) {
const parentSymbol = getParentOfSymbol(type.symbol);
const parentName = symbolToName(parentSymbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false);
- const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : createQualifiedName(parentName, getNameOfSymbol(type.symbol, context));
+ const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : createQualifiedName(parentName, symbolName(type.symbol));
return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined);
}
if (type.flags & TypeFlags.EnumLike) {
@@ -2850,8 +2851,7 @@ namespace ts {
function mapToTypeNodes(types: Type[], context: NodeBuilderContext): TypeNode[] {
if (some(types)) {
const result = [];
- for (let i = 0; i < types.length; ++i) {
- const type = types[i];
+ for (const type of types) {
const typeNode = typeToTypeNodeHelper(type, context);
if (typeNode) {
result.push(typeNode);
@@ -3015,8 +3015,7 @@ namespace ts {
typeParameterNodes = mapToTypeNodes(typeParameters, context);
}
- const symbolName = getNameOfSymbol(symbol, context);
- const identifier = setEmitFlags(createIdentifier(symbolName, typeParameterNodes), EmitFlags.NoAsciiEscaping);
+ const identifier = setEmitFlags(createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), EmitFlags.NoAsciiEscaping);
return index > 0 ? createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
}
@@ -3128,7 +3127,14 @@ namespace ts {
symbolStack: Symbol[] | undefined;
}
- function getNameOfSymbol(symbol: Symbol, context?: NodeBuilderContext): string {
+ /**
+ * Gets a human-readable name for a symbol.
+ * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
+ *
+ * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
+ * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
+ */
+ function getNameOfSymbolAsWritten(symbol: Symbol, context?: NodeBuilderContext): string {
if (symbol.declarations && symbol.declarations.length) {
const declaration = symbol.declarations[0];
const name = getNameOfDeclaration(declaration);
@@ -3165,7 +3171,7 @@ namespace ts {
* for the name of the symbol if it is available to match how the user wrote the name.
*/
function appendSymbolNameOnly(symbol: Symbol, writer: SymbolWriter): void {
- writer.writeSymbol(getNameOfSymbol(symbol), symbol);
+ writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol);
}
/**
@@ -3174,7 +3180,7 @@ namespace ts {
* ensuring that any names written with literals use element accesses.
*/
function appendPropertyOrElementAccessForSymbol(symbol: Symbol, writer: SymbolWriter): void {
- const symbolName = getNameOfSymbol(symbol);
+ const symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol);
const firstChar = symbolName.charCodeAt(0);
const needsElementAccess = !isIdentifierStart(firstChar, languageVersion);
@@ -3939,7 +3945,7 @@ namespace ts {
const parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(getCombinedModifierFlags(node) & ModifierFlags.Export) &&
- !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && isInAmbientContext(parent))) {
+ !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && parent.flags & NodeFlags.Ambient)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -4317,7 +4323,7 @@ namespace ts {
if ((noImplicitAny || isInJavaScriptFile(declaration)) &&
declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) &&
- !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !isInAmbientContext(declaration)) {
+ !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) {
// If --noImplicitAny is on or the declaration is in a Javascript file,
// use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
// initializer or a 'null' or 'undefined' initializer.
@@ -5190,7 +5196,7 @@ namespace ts {
function isLiteralEnumMember(member: EnumMember) {
const expr = member.initializer;
if (!expr) {
- return !isInAmbientContext(member);
+ return !(member.flags & NodeFlags.Ambient);
}
switch (expr.kind) {
case SyntaxKind.StringLiteral:
@@ -5866,6 +5872,17 @@ namespace ts {
return type.modifiersType;
}
+ function getMappedTypeModifiers(type: MappedType): MappedTypeModifiers {
+ return (type.declaration.readonlyToken ? MappedTypeModifiers.Readonly : 0) |
+ (type.declaration.questionToken ? MappedTypeModifiers.Optional : 0);
+ }
+
+ function getCombinedMappedTypeModifiers(type: MappedType): MappedTypeModifiers {
+ const modifiersType = getModifiersTypeFromMappedType(type);
+ return getMappedTypeModifiers(type) |
+ (isGenericMappedType(modifiersType) ? getMappedTypeModifiers(modifiersType) : 0);
+ }
+
function isPartialMappedType(type: Type) {
return getObjectFlags(type) & ObjectFlags.Mapped && !!(type).declaration.questionToken;
}
@@ -6566,7 +6583,7 @@ namespace ts {
if (!node) return false;
switch (node.kind) {
case SyntaxKind.Identifier:
- return (node).escapedText === "arguments" && isPartOfExpression(node);
+ return (node).escapedText === "arguments" && isExpressionNode(node);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.MethodDeclaration:
@@ -6885,7 +6902,7 @@ namespace ts {
const numTypeArguments = length(node.typeArguments);
const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
const isJs = isInJavaScriptFile(node);
- const isJsImplicitAny = !compilerOptions.noImplicitAny && isJs;
+ const isJsImplicitAny = !noImplicitAny && isJs;
if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
const missingAugmentsTag = isJs && node.parent.kind !== SyntaxKind.JSDocAugmentsTag;
const diag = minTypeArgumentCount === typeParameters.length
@@ -7292,6 +7309,9 @@ namespace ts {
property.type = typeParameter;
properties.push(property);
}
+ const lengthSymbol = createSymbol(SymbolFlags.Property, "length" as __String);
+ lengthSymbol.type = getLiteralType(arity);
+ properties.push(lengthSymbol);
const type = createObjectType(ObjectFlags.Tuple | ObjectFlags.Reference);
type.typeParameters = typeParameters;
type.outerTypeParameters = undefined;
@@ -7341,28 +7361,12 @@ namespace ts {
unionIndex?: number;
}
- function binarySearchTypes(types: Type[], type: Type): number {
- let low = 0;
- let high = types.length - 1;
- const typeId = type.id;
- while (low <= high) {
- const middle = low + ((high - low) >> 1);
- const id = types[middle].id;
- if (id === typeId) {
- return middle;
- }
- else if (id > typeId) {
- high = middle - 1;
- }
- else {
- low = middle + 1;
- }
- }
- return ~low;
+ function getTypeId(type: Type) {
+ return type.id;
}
function containsType(types: Type[], type: Type): boolean {
- return binarySearchTypes(types, type) >= 0;
+ return binarySearch(types, type, getTypeId, compareValues) >= 0;
}
// Return true if the given intersection type contains (a) more than one unit type or (b) an object
@@ -7403,7 +7407,7 @@ namespace ts {
if (flags & TypeFlags.Number) typeSet.containsNumber = true;
if (flags & TypeFlags.StringOrNumberLiteral) typeSet.containsStringOrNumberLiteral = true;
const len = typeSet.length;
- const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type);
+ const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues);
if (index < 0) {
if (!(flags & TypeFlags.Object && (type).objectFlags & ObjectFlags.Anonymous &&
type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) {
@@ -7430,9 +7434,12 @@ namespace ts {
return false;
}
- function isSubtypeOfAny(candidate: Type, types: Type[]): boolean {
- for (const type of types) {
- if (candidate !== type && isTypeSubtypeOf(candidate, type)) {
+ function isSubtypeOfAny(source: Type, targets: Type[]): boolean {
+ for (const target of targets) {
+ if (source !== target && isTypeSubtypeOf(source, target) && (
+ !(getObjectFlags(getTargetType(source)) & ObjectFlags.Class) ||
+ !(getObjectFlags(getTargetType(target)) & ObjectFlags.Class) ||
+ isTypeDerivedFrom(source, target))) {
return true;
}
}
@@ -7579,11 +7586,11 @@ namespace ts {
}
}
- // Add the given types to the given type set. Order is preserved, duplicates are removed,
- // and nested types of the given kind are flattened into the set.
+ // Add the given types to the given type set. Order is preserved, freshness is removed from literal
+ // types, duplicates are removed, and nested types of the given kind are flattened into the set.
function addTypesToIntersection(typeSet: TypeSet, types: Type[]) {
for (const type of types) {
- addTypeToIntersection(typeSet, type);
+ addTypeToIntersection(typeSet, getRegularTypeOfLiteralType(type));
}
}
@@ -7672,7 +7679,7 @@ namespace ts {
function getIndexTypeOrString(type: Type): Type {
const indexType = getIndexType(type);
- return indexType !== neverType ? indexType : stringType;
+ return indexType.flags & TypeFlags.Never ? stringType : indexType;
}
function getTypeFromTypeOperatorNode(node: TypeOperatorNode) {
@@ -7981,11 +7988,16 @@ namespace ts {
}
}
- const spread = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
+ const spread = createAnonymousType(
+ symbol,
+ members,
+ emptyArray,
+ emptyArray,
+ getNonReadonlyIndexSignature(stringIndexInfo),
+ getNonReadonlyIndexSignature(numberIndexInfo));
spread.flags |= propagatedFlags;
spread.flags |= TypeFlags.FreshLiteral | TypeFlags.ContainsObjectLiteral;
- (spread as ObjectType).objectFlags |= ObjectFlags.ObjectLiteral;
- spread.symbol = symbol;
+ (spread as ObjectType).objectFlags |= (ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread);
return spread;
}
@@ -8001,6 +8013,13 @@ namespace ts {
return result;
}
+ function getNonReadonlyIndexSignature(index: IndexInfo) {
+ if (index && index.isReadonly) {
+ return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration);
+ }
+ return index;
+ }
+
function isClassMethod(prop: Symbol) {
return prop.flags & SymbolFlags.Method && find(prop.declarations, decl => isClassLike(decl.parent));
}
@@ -8555,12 +8574,19 @@ namespace ts {
return isTypeRelatedTo(source, target, assignableRelation);
}
- // A type S is considered to be an instance of a type T if S and T are the same type or if S is a
- // subtype of T but not structurally identical to T. This specifically means that two distinct but
- // structurally identical types (such as two classes) are not considered instances of each other.
- function isTypeInstanceOf(source: Type, target: Type): boolean {
- return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target);
- }
+ // An object type S is considered to be derived from an object type T if
+ // S is a union type and every constituent of S is derived from T,
+ // T is a union type and S is derived from at least one constituent of T, or
+ // T is one of the global types Object and Function and S is a subtype of T, or
+ // T occurs directly or indirectly in an 'extends' clause of S.
+ // Note that this check ignores type parameters and only considers the
+ // inheritance hierarchy.
+ function isTypeDerivedFrom(source: Type, target: Type): boolean {
+ return source.flags & TypeFlags.Union ? every((source).types, t => isTypeDerivedFrom(t, target)) :
+ target.flags & TypeFlags.Union ? some((target).types, t => isTypeDerivedFrom(source, t)) :
+ target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) :
+ hasBaseType(source, getTargetType(target));
+ }
/**
* This is *not* a bi-directional relationship.
@@ -8842,8 +8868,8 @@ namespace ts {
function isSimpleTypeRelatedTo(source: Type, target: Type, relation: Map, errorReporter?: ErrorReporter) {
const s = source.flags;
const t = target.flags;
- if (t & TypeFlags.Never) return false;
if (t & TypeFlags.Any || s & TypeFlags.Never) return true;
+ if (t & TypeFlags.Never) return false;
if (s & TypeFlags.StringLike && t & TypeFlags.String) return true;
if (s & TypeFlags.StringLiteral && s & TypeFlags.EnumLiteral &&
t & TypeFlags.StringLiteral && !(t & TypeFlags.EnumLiteral) &&
@@ -9026,7 +9052,7 @@ namespace ts {
if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True;
- if (getObjectFlags(source) & ObjectFlags.ObjectLiteral && source.flags & TypeFlags.FreshLiteral) {
+ if (isObjectLiteralType(source) && source.flags & TypeFlags.FreshLiteral) {
if (hasExcessProperties(source, target, reportErrors)) {
if (reportErrors) {
reportRelationError(headMessage, source, target);
@@ -9229,20 +9255,24 @@ namespace ts {
return Ternary.False;
}
+ // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) {
let match: Type;
const sourceProperties = getPropertiesOfObjectType(source);
if (sourceProperties) {
- const sourceProperty = findSingleDiscriminantProperty(sourceProperties, target);
- if (sourceProperty) {
- const sourceType = getTypeOfSymbol(sourceProperty);
- for (const type of target.types) {
- const targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName);
- if (targetType && isRelatedTo(sourceType, targetType)) {
- if (match) {
- return undefined;
+ const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
+ if (sourcePropertiesFiltered) {
+ for (const sourceProperty of sourcePropertiesFiltered) {
+ const sourceType = getTypeOfSymbol(sourceProperty);
+ for (const type of target.types) {
+ const targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName);
+ if (targetType && isRelatedTo(sourceType, targetType)) {
+ if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine
+ if (match) {
+ return undefined;
+ }
+ match = type;
}
- match = type;
}
}
}
@@ -9413,6 +9443,7 @@ namespace ts {
function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary {
let result: Ternary;
+ let originalErrorInfo: DiagnosticMessageChain;
const saveErrorInfo = errorInfo;
if (target.flags & TypeFlags.TypeParameter) {
// A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P].
@@ -9453,32 +9484,30 @@ namespace ts {
}
}
}
+ else if (isGenericMappedType(target) && !isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) {
+ // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X.
+ const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
+ const templateType = getTemplateTypeFromMappedType(target);
+ if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ }
if (source.flags & TypeFlags.TypeParameter) {
- // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X.
- if (getObjectFlags(target) & ObjectFlags.Mapped && getConstraintTypeFromMappedType(target) === getIndexType(source)) {
- const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target));
- const templateType = getTemplateTypeFromMappedType(target);
- if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
+ let constraint = getConstraintOfTypeParameter(source);
+ // A type parameter with no constraint is not related to the non-primitive object type.
+ if (constraint || !(target.flags & TypeFlags.NonPrimitive)) {
+ if (!constraint || constraint.flags & TypeFlags.Any) {
+ constraint = emptyObjectType;
+ }
+ // Report constraint errors only if the constraint is not the empty object type
+ const reportConstraintErrors = reportErrors && constraint !== emptyObjectType;
+ if (result = isRelatedTo(constraint, target, reportConstraintErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
- else {
- let constraint = getConstraintOfTypeParameter(source);
- // A type parameter with no constraint is not related to the non-primitive object type.
- if (constraint || !(target.flags & TypeFlags.NonPrimitive)) {
- if (!constraint || constraint.flags & TypeFlags.Any) {
- constraint = emptyObjectType;
- }
- // Report constraint errors only if the constraint is not the empty object type
- const reportConstraintErrors = reportErrors && constraint !== emptyObjectType;
- if (result = isRelatedTo(constraint, target, reportConstraintErrors)) {
- errorInfo = saveErrorInfo;
- return result;
- }
- }
- }
}
else if (source.flags & TypeFlags.IndexedAccess) {
// A type S[K] is related to a type T if A[K] is related to T, where K is string-like and
@@ -9494,6 +9523,7 @@ namespace ts {
// 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)) {
+ errorInfo = saveErrorInfo;
return result;
}
}
@@ -9525,6 +9555,10 @@ namespace ts {
if (!(reportErrors && some(variances, v => v === Variance.Invariant))) {
return Ternary.False;
}
+ // We remember the original error information so we can restore it in case the structural
+ // comparison unexpectedly succeeds. This can happen when the structural comparison result
+ // is a Ternary.Maybe for example caused by the recursion depth limiter.
+ originalErrorInfo = errorInfo;
errorInfo = saveErrorInfo;
}
}
@@ -9563,8 +9597,11 @@ namespace ts {
}
}
if (result) {
- errorInfo = saveErrorInfo;
- return result;
+ if (!originalErrorInfo) {
+ errorInfo = saveErrorInfo;
+ return result;
+ }
+ errorInfo = originalErrorInfo;
}
}
}
@@ -9575,13 +9612,10 @@ namespace ts {
// related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
// that S and T are contra-variant whereas X and Y are co-variant.
function mappedTypeRelatedTo(source: MappedType, target: MappedType, reportErrors: boolean): Ternary {
- const sourceReadonly = !!source.declaration.readonlyToken;
- const sourceOptional = !!source.declaration.questionToken;
- const targetReadonly = !!target.declaration.readonlyToken;
- const targetOptional = !!target.declaration.questionToken;
- const modifiersRelated = relation === identityRelation ?
- sourceReadonly === targetReadonly && sourceOptional === targetOptional :
- relation === comparableRelation || !sourceOptional || targetOptional;
+ const modifiersRelated = relation === comparableRelation || (
+ relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
+ !(getCombinedMappedTypeModifiers(source) & MappedTypeModifiers.Optional) ||
+ getCombinedMappedTypeModifiers(target) & MappedTypeModifiers.Optional);
if (modifiersRelated) {
let result: Ternary;
if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
@@ -9596,7 +9630,7 @@ namespace ts {
if (relation === identityRelation) {
return propertiesIdenticalTo(source, target);
}
- const requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & ObjectFlags.ObjectLiteral);
+ const requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source);
const unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties);
if (unmatchedProperty) {
if (reportErrors) {
@@ -9604,6 +9638,19 @@ namespace ts {
}
return Ternary.False;
}
+ if (isObjectLiteralType(target)) {
+ for (const sourceProp of getPropertiesOfType(source)) {
+ if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
+ const sourceType = getTypeOfSymbol(sourceProp);
+ if (!(sourceType === undefinedType || sourceType === undefinedWideningType)) {
+ if (reportErrors) {
+ reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
+ }
+ return Ternary.False;
+ }
+ }
+ }
+ }
let result = Ternary.True;
const properties = getPropertiesOfObjectType(target);
for (const targetProp of properties) {
@@ -10291,6 +10338,11 @@ namespace ts {
!(type.flags & TypeFlags.Nullable) && isTypeAssignableTo(type, anyReadonlyArrayType);
}
+ function isEmptyArrayLiteralType(type: Type): boolean {
+ const elementType = isArrayType(type) ? (type).typeArguments[0] : undefined;
+ return elementType === undefinedWideningType || elementType === implicitNeverType;
+ }
+
function isTupleLikeType(type: Type): boolean {
return !!getPropertyOfType(type, "0" as __String);
}
@@ -10425,7 +10477,7 @@ namespace ts {
* Leave signatures alone since they are not subject to the check.
*/
function getRegularTypeOfObjectLiteral(type: Type): Type {
- if (!(getObjectFlags(type) & ObjectFlags.ObjectLiteral && type.flags & TypeFlags.FreshLiteral)) {
+ if (!(isObjectLiteralType(type) && type.flags & TypeFlags.FreshLiteral)) {
return type;
}
const regularType = (type).regularType;
@@ -10447,18 +10499,74 @@ namespace ts {
return regularNew;
}
- function getWidenedProperty(prop: Symbol): Symbol {
+ function createWideningContext(parent: WideningContext, propertyName: __String, siblings: Type[]): WideningContext {
+ return { parent, propertyName, siblings, resolvedPropertyNames: undefined };
+ }
+
+ function getSiblingsOfContext(context: WideningContext): Type[] {
+ if (!context.siblings) {
+ const siblings: Type[] = [];
+ for (const type of getSiblingsOfContext(context.parent)) {
+ if (isObjectLiteralType(type)) {
+ const prop = getPropertyOfObjectType(type, context.propertyName);
+ if (prop) {
+ forEachType(getTypeOfSymbol(prop), t => {
+ siblings.push(t);
+ });
+ }
+ }
+ }
+ context.siblings = siblings;
+ }
+ return context.siblings;
+ }
+
+ function getPropertyNamesOfContext(context: WideningContext): __String[] {
+ if (!context.resolvedPropertyNames) {
+ const names = createMap() as UnderscoreEscapedMap;
+ for (const t of getSiblingsOfContext(context)) {
+ if (isObjectLiteralType(t) && !(getObjectFlags(t) & ObjectFlags.ContainsSpread)) {
+ for (const prop of getPropertiesOfType(t)) {
+ names.set(prop.escapedName, true);
+ }
+ }
+ }
+ context.resolvedPropertyNames = arrayFrom(names.keys());
+ }
+ return context.resolvedPropertyNames;
+ }
+
+ function getWidenedProperty(prop: Symbol, context: WideningContext): Symbol {
const original = getTypeOfSymbol(prop);
- const widened = getWidenedType(original);
+ const propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
+ const widened = getWidenedTypeWithContext(original, propContext);
return widened === original ? prop : createSymbolWithType(prop, widened);
}
- function getWidenedTypeOfObjectLiteral(type: Type): Type {
+ function getUndefinedProperty(name: __String) {
+ const cached = undefinedProperties.get(name);
+ if (cached) {
+ return cached;
+ }
+ const result = createSymbol(SymbolFlags.Property | SymbolFlags.Optional, name);
+ result.type = undefinedType;
+ undefinedProperties.set(name, result);
+ return result;
+ }
+
+ function getWidenedTypeOfObjectLiteral(type: Type, context: WideningContext): Type {
const members = createSymbolTable();
for (const prop of getPropertiesOfObjectType(type)) {
// Since get accessors already widen their return value there is no need to
// widen accessor based properties here.
- members.set(prop.escapedName, prop.flags & SymbolFlags.Property ? getWidenedProperty(prop) : prop);
+ members.set(prop.escapedName, prop.flags & SymbolFlags.Property ? getWidenedProperty(prop, context) : prop);
+ }
+ if (context) {
+ for (const name of getPropertyNamesOfContext(context)) {
+ if (!members.has(name)) {
+ members.set(name, getUndefinedProperty(name));
+ }
+ }
}
const stringIndexInfo = getIndexInfoOfType(type, IndexKind.String);
const numberIndexInfo = getIndexInfoOfType(type, IndexKind.Number);
@@ -10467,20 +10575,25 @@ namespace ts {
numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
}
- function getWidenedConstituentType(type: Type): Type {
- return type.flags & TypeFlags.Nullable ? type : getWidenedType(type);
+ function getWidenedType(type: Type) {
+ return getWidenedTypeWithContext(type, /*context*/ undefined);
}
- function getWidenedType(type: Type): Type {
+ function getWidenedTypeWithContext(type: Type, context: WideningContext): Type {
if (type.flags & TypeFlags.RequiresWidening) {
if (type.flags & TypeFlags.Nullable) {
return anyType;
}
- if (getObjectFlags(type) & ObjectFlags.ObjectLiteral) {
- return getWidenedTypeOfObjectLiteral(type);
+ if (isObjectLiteralType(type)) {
+ return getWidenedTypeOfObjectLiteral(type, context);
}
if (type.flags & TypeFlags.Union) {
- return getUnionType(sameMap((type).types, getWidenedConstituentType));
+ const unionContext = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, (type).types);
+ const widenedTypes = sameMap((type).types, t => t.flags & TypeFlags.Nullable ? t : getWidenedTypeWithContext(t, unionContext));
+ // Widening an empty object literal transitions from a highly restrictive type to
+ // a highly inclusive one. For that reason we perform subtype reduction here if the
+ // union includes empty object types (e.g. reducing {} | string to just {}).
+ return getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType));
}
if (isArrayType(type) || isTupleType(type)) {
return createTypeReference((type).target, sameMap((type).typeArguments, getWidenedType));
@@ -10502,28 +10615,35 @@ namespace ts {
*/
function reportWideningErrorsInType(type: Type): boolean {
let errorReported = false;
- if (type.flags & TypeFlags.Union) {
- for (const t of (type).types) {
- if (reportWideningErrorsInType(t)) {
+ if (type.flags & TypeFlags.ContainsWideningType) {
+ if (type.flags & TypeFlags.Union) {
+ if (some((type).types, isEmptyObjectType)) {
errorReported = true;
}
+ else {
+ for (const t of (type).types) {
+ if (reportWideningErrorsInType(t)) {
+ errorReported = true;
+ }
+ }
+ }
}
- }
- if (isArrayType(type) || isTupleType(type)) {
- for (const t of (type).typeArguments) {
- if (reportWideningErrorsInType(t)) {
- errorReported = true;
+ if (isArrayType(type) || isTupleType(type)) {
+ for (const t of (type).typeArguments) {
+ if (reportWideningErrorsInType(t)) {
+ errorReported = true;
+ }
}
}
- }
- if (getObjectFlags(type) & ObjectFlags.ObjectLiteral) {
- for (const p of getPropertiesOfObjectType(type)) {
- const t = getTypeOfSymbol(p);
- if (t.flags & TypeFlags.ContainsWideningType) {
- if (!reportWideningErrorsInType(t)) {
- error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolName(p), typeToString(getWidenedType(t)));
+ if (isObjectLiteralType(type)) {
+ for (const p of getPropertiesOfObjectType(type)) {
+ const t = getTypeOfSymbol(p);
+ if (t.flags & TypeFlags.ContainsWideningType) {
+ if (!reportWideningErrorsInType(t)) {
+ error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolName(p), typeToString(getWidenedType(t)));
+ }
+ errorReported = true;
}
- errorReported = true;
}
}
}
@@ -10703,7 +10823,7 @@ namespace ts {
}
function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean) {
- const properties = getPropertiesOfObjectType(target);
+ const properties = target.flags & TypeFlags.Intersection ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target);
for (const targetProp of properties) {
if (requireOptionalProperties || !(targetProp.flags & SymbolFlags.Optional)) {
const sourceProp = getPropertyOfType(source, targetProp.escapedName);
@@ -10777,9 +10897,10 @@ namespace ts {
// Because the anyFunctionType is internal, it should not be exposed to the user by adding
// it as an inference candidate. Hopefully, a better candidate will come along that does
// not contain anyFunctionType when we come back to this argument for its second round
- // of inference. Also, we exclude inferences for silentNeverType which is used as a wildcard
- // when constructing types from type parameters that had no inference candidates.
- if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType) {
+ // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
+ // when constructing types from type parameters that had no inference candidates) and
+ // implicitNeverType (which is used as the element type for empty array literals).
+ if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType || source === implicitNeverType) {
return;
}
const inference = getInferenceInfoForType(target);
@@ -11029,11 +11150,28 @@ namespace ts {
return constraint && maybeTypeOfKind(constraint, TypeFlags.Primitive | TypeFlags.Index);
}
+ function isObjectLiteralType(type: Type) {
+ return !!(getObjectFlags(type) & ObjectFlags.ObjectLiteral);
+ }
+
+ function widenObjectLiteralCandidates(candidates: Type[]): Type[] {
+ if (candidates.length > 1) {
+ const objectLiterals = filter(candidates, isObjectLiteralType);
+ if (objectLiterals.length) {
+ const objectLiteralsType = getWidenedType(getUnionType(objectLiterals, /*subtypeReduction*/ true));
+ return concatenate(filter(candidates, t => !isObjectLiteralType(t)), [objectLiteralsType]);
+ }
+ }
+ return candidates;
+ }
+
function getInferredType(context: InferenceContext, index: number): Type {
const inference = context.inferences[index];
let inferredType = inference.inferredType;
if (!inferredType) {
if (inference.candidates) {
+ // Extract all object literal types and replace them with a single widened and normalized type.
+ const candidates = widenObjectLiteralCandidates(inference.candidates);
// We widen inferred literal types if
// all inferences were made to top-level ocurrences of the type parameter, and
// the type parameter has no constraint or its constraint includes no primitive or literal types, and
@@ -11042,7 +11180,7 @@ namespace ts {
const widenLiteralTypes = inference.topLevel &&
!hasPrimitiveConstraint(inference.typeParameter) &&
(inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
- const baseCandidates = widenLiteralTypes ? sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates;
+ const baseCandidates = widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : candidates;
// If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if
// union types were requested or if all inferences were made from the return type position, infer a
// union type. Otherwise, infer a common supertype.
@@ -11248,14 +11386,15 @@ namespace ts {
return false;
}
- function findSingleDiscriminantProperty(sourceProperties: Symbol[], target: Type): Symbol | undefined {
- let result: Symbol;
+ function findDiscriminantProperties(sourceProperties: Symbol[], target: Type): Symbol[] | undefined {
+ let result: Symbol[];
for (const sourceProperty of sourceProperties) {
if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
if (result) {
- return undefined;
+ result.push(sourceProperty);
+ continue;
}
- result = sourceProperty;
+ result = [sourceProperty];
}
}
return result;
@@ -12309,7 +12448,7 @@ namespace ts {
}
if (targetType) {
- return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf);
+ return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
}
return type;
@@ -12416,7 +12555,7 @@ namespace ts {
if (isRightSideOfQualifiedNameOrPropertyAccess(location)) {
location = location.parent;
}
- if (isPartOfExpression(location) && !isAssignmentTarget(location)) {
+ if (isExpressionNode(location) && !isAssignmentTarget(location)) {
const type = getTypeOfExpression(location);
if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
return type;
@@ -12639,7 +12778,7 @@ namespace ts {
const assumeInitialized = isParameter || isAlias || isOuterVariable ||
type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0 || isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) ||
node.parent.kind === SyntaxKind.NonNullExpression ||
- isInAmbientContext(declaration);
+ declaration.flags & NodeFlags.Ambient;
const initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, getRootDeclaration(declaration) as VariableLikeDeclaration) : type) :
type === autoType || type === autoArrayType ? undefinedType :
getNullableType(type, TypeFlags.Undefined);
@@ -13491,7 +13630,13 @@ namespace ts {
// JSX expression can appear in two position : JSX Element's children or JSX attribute
const jsxAttributes = isJsxAttributeLike(node.parent) ?
node.parent.parent :
- node.parent.openingElement.attributes; // node.parent is JsxElement
+ isJsxElement(node.parent) ?
+ node.parent.openingElement.attributes :
+ undefined; // node.parent is JsxFragment with no attributes
+
+ if (!jsxAttributes) {
+ return undefined; // don't check children of a fragment
+ }
// When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
// which is a type of the parameter of the signature we are trying out.
@@ -13537,8 +13682,32 @@ namespace ts {
// Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
// be "pushed" onto a node using the contextualType property.
function getApparentTypeOfContextualType(node: Expression): Type {
- const type = getContextualType(node);
- return type && getApparentType(type);
+ let contextualType = getContextualType(node);
+ contextualType = contextualType && mapType(contextualType, getApparentType);
+ if (!(contextualType && contextualType.flags & TypeFlags.Union && isObjectLiteralExpression(node))) {
+ return contextualType;
+ }
+ // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType`
+ let match: Type | undefined;
+ propLoop: for (const prop of node.properties) {
+ if (!prop.symbol) continue;
+ if (prop.kind !== SyntaxKind.PropertyAssignment) continue;
+ if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) {
+ const discriminatingType = getTypeOfNode(prop.initializer);
+ for (const type of (contextualType as UnionType).types) {
+ const targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName);
+ if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) {
+ if (match) {
+ if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine
+ match = undefined;
+ break propLoop;
+ }
+ match = type;
+ }
+ }
+ }
+ }
+ return match || contextualType;
}
/**
@@ -13771,7 +13940,6 @@ namespace ts {
type.pattern = node;
return type;
}
- const contextualType = getApparentTypeOfContextualType(node);
if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
const pattern = contextualType.pattern;
// If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
@@ -13798,7 +13966,7 @@ namespace ts {
}
return createArrayType(elementTypes.length ?
getUnionType(elementTypes, /*subtypeReduction*/ true) :
- strictNullChecks ? neverType : undefinedWideningType);
+ strictNullChecks ? implicitNeverType : undefinedWideningType);
}
function isNumericName(name: DeclarationName): boolean {
@@ -14071,13 +14239,13 @@ namespace ts {
}
function checkJsxSelfClosingElement(node: JsxSelfClosingElement): Type {
- checkJsxOpeningLikeElement(node);
+ checkJsxOpeningLikeElementOrOpeningFragment(node);
return getJsxGlobalElementType() || anyType;
}
function checkJsxElement(node: JsxElement): Type {
// Check attributes
- checkJsxOpeningLikeElement(node.openingElement);
+ checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
// Perform resolution on the closing tag so that rename/go to definition/etc work
if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
@@ -14090,6 +14258,16 @@ namespace ts {
return getJsxGlobalElementType() || anyType;
}
+ function checkJsxFragment(node: JsxFragment): Type {
+ checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
+
+ if (compilerOptions.jsx === JsxEmit.React && compilerOptions.jsxFactory) {
+ error(node, Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory);
+ }
+
+ return getJsxGlobalElementType() || anyType;
+ }
+
/**
* Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
*/
@@ -14753,14 +14931,19 @@ namespace ts {
}
}
- function checkJsxOpeningLikeElement(node: JsxOpeningLikeElement) {
- checkGrammarJsxElement(node);
+ function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment) {
+ const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node);
+
+ if (isNodeOpeningLikeElement) {
+ checkGrammarJsxElement(node);
+ }
checkJsxPreconditions(node);
// The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
// And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
const reactRefErr = diagnostics && compilerOptions.jsx === JsxEmit.React ? Diagnostics.Cannot_find_name_0 : undefined;
const reactNamespace = getJsxNamespace();
- const reactSym = resolveName(node.tagName, reactNamespace, SymbolFlags.Value, reactRefErr, reactNamespace, /*isUse*/ true);
+ const reactLocation = isNodeOpeningLikeElement ? (node).tagName : node;
+ const reactSym = resolveName(reactLocation, reactNamespace, SymbolFlags.Value, reactRefErr, reactNamespace, /*isUse*/ true);
if (reactSym) {
// Mark local symbol as referenced here because it might not have been marked
// if jsx emit was not react as there wont be error being emitted
@@ -14772,7 +14955,9 @@ namespace ts {
}
}
- checkJsxAttributesAssignableToTagNameAttributes(node);
+ if (isNodeOpeningLikeElement) {
+ checkJsxAttributesAssignableToTagNameAttributes(node);
+ }
}
/**
@@ -14928,12 +15113,11 @@ namespace ts {
}
}
- // Referencing Abstract Properties within Constructors is not allowed
- if ((flags & ModifierFlags.Abstract) && symbolHasNonMethodDeclaration(prop)) {
+ // Referencing abstract properties within their own constructors is not allowed
+ if ((flags & ModifierFlags.Abstract) && isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
-
- if (declaringClassDeclaration && isNodeWithinConstructor(node, declaringClassDeclaration)) {
- error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), typeToString(getDeclaringClass(prop)));
+ if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) {
+ error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name));
return false;
}
}
@@ -14977,12 +15161,11 @@ namespace ts {
if (flags & ModifierFlags.Static) {
return true;
}
- // An instance property must be accessed through an instance of the enclosing class
- if (type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType) {
+ if (type.flags & TypeFlags.TypeParameter) {
// get the original type -- represented as the type constraint of the 'this' type
- type = getConstraintOfTypeParameter(type);
+ type = (type as TypeParameter).isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type);
}
- if (!(getObjectFlags(getTargetType(type)) & ObjectFlags.ClassOrInterface && hasBaseType(type, enclosingClass))) {
+ if (!type || !hasBaseType(type, enclosingClass)) {
error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
return false;
}
@@ -15039,7 +15222,7 @@ namespace ts {
if (indexInfo.isReadonly && (isAssignmentTarget(node) || isDeleteTarget(node))) {
error(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
}
- return indexInfo.type;
+ return getFlowTypeOfPropertyAccess(node, /*prop*/ undefined, indexInfo.type, getAssignmentTargetKind(node));
}
if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
reportNonexistentProperty(right, type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType ? apparentType : type);
@@ -15064,16 +15247,21 @@ namespace ts {
return unknownType;
}
}
+ return getFlowTypeOfPropertyAccess(node, prop, propType, assignmentKind);
+ }
- // Only compute control flow type if this is a property access expression that isn't an
- // assignment target, and the referenced property was declared as a variable, property,
- // accessor, or optional method.
- if (node.kind !== SyntaxKind.PropertyAccessExpression || assignmentKind === AssignmentKind.Definite ||
- !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) &&
- !(prop.flags & SymbolFlags.Method && propType.flags & TypeFlags.Union)) {
- return propType;
+ /**
+ * Only compute control flow type if this is a property access expression that isn't an
+ * assignment target, and the referenced property was declared as a variable, property,
+ * accessor, or optional method.
+ */
+ function getFlowTypeOfPropertyAccess(node: PropertyAccessExpression | QualifiedName, prop: Symbol | undefined, type: Type, assignmentKind: AssignmentKind) {
+ if (node.kind !== SyntaxKind.PropertyAccessExpression ||
+ assignmentKind === AssignmentKind.Definite ||
+ prop && !(prop.flags & (SymbolFlags.Variable | SymbolFlags.Property | SymbolFlags.Accessor)) && !(prop.flags & SymbolFlags.Method && type.flags & TypeFlags.Union)) {
+ return type;
}
- const flowType = getFlowTypeOfReference(node, propType);
+ const flowType = getFlowTypeOfReference(node, type);
return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
}
@@ -15090,7 +15278,7 @@ namespace ts {
}
else if (valueDeclaration.kind === SyntaxKind.ClassDeclaration &&
node.parent.kind !== SyntaxKind.TypeReference &&
- !isInAmbientContext(valueDeclaration) &&
+ !(valueDeclaration.flags & NodeFlags.Ambient) &&
!isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
error(right, Diagnostics.Class_0_used_before_its_declaration, idText(right));
}
@@ -15105,7 +15293,7 @@ namespace ts {
// We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`.
return false;
default:
- return isPartOfExpression(node) ? false : "quit";
+ return isExpressionNode(node) ? false : "quit";
}
});
}
@@ -15162,9 +15350,10 @@ namespace ts {
return suggestion && symbolName(suggestion);
}
- function getSuggestionForNonexistentSymbol(location: Node, name: __String, meaning: SymbolFlags): string {
- const result = resolveNameHelper(location, name, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ false, (symbols, name, meaning) => {
- // `name` from the callback === the outer `name`
+ function getSuggestionForNonexistentSymbol(location: Node, outerName: __String, meaning: SymbolFlags): string {
+ Debug.assert(outerName !== undefined, "outername should always be defined");
+ const result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, (symbols, name, meaning) => {
+ Debug.assertEqual(outerName, name, "name should equal outerName");
const symbol = getSymbol(symbols, name, meaning);
// Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function
// So the table *contains* `x` but `x` isn't actually in scope.
@@ -16489,21 +16678,9 @@ namespace ts {
* but is a subtype of the Function interface, the call is an untyped function call.
*/
function isUntypedFunctionCall(funcType: Type, apparentFuncType: Type, numCallSignatures: number, numConstructSignatures: number) {
- if (isTypeAny(funcType)) {
- return true;
- }
- if (isTypeAny(apparentFuncType) && funcType.flags & TypeFlags.TypeParameter) {
- return true;
- }
- if (!numCallSignatures && !numConstructSignatures) {
- // We exclude union types because we may have a union of function types that happen to have
- // no common signatures.
- if (funcType.flags & TypeFlags.Union) {
- return false;
- }
- return isTypeAssignableTo(funcType, globalFunctionType);
- }
- return false;
+ // We exclude union types because we may have a union of function types that happen to have no common signatures.
+ return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & TypeFlags.TypeParameter ||
+ !numCallSignatures && !numConstructSignatures && !(funcType.flags & (TypeFlags.Union | TypeFlags.Never)) && isTypeAssignableTo(funcType, globalFunctionType);
}
function resolveNewExpression(node: NewExpression, candidatesOutArray: Signature[]): Signature {
@@ -16555,7 +16732,7 @@ namespace ts {
// only the class declaration node will have the Abstract flag set.
const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol);
if (valueDecl && hasModifier(valueDecl, ModifierFlags.Abstract)) {
- error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(getNameOfDeclaration(valueDecl)));
+ error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
@@ -16860,8 +17037,7 @@ namespace ts {
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
function checkCallExpression(node: CallExpression | NewExpression): Type {
- // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true
- checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node.arguments);
+ if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments);
const signature = getResolvedSignature(node);
@@ -16908,7 +17084,7 @@ namespace ts {
function checkImportCallExpression(node: ImportCall): Type {
// Check grammar of dynamic import
- checkGrammarArguments(node.arguments) || checkGrammarImportCallExpression(node);
+ if (!checkGrammarArguments(node.arguments)) checkGrammarImportCallExpression(node);
if (node.arguments.length === 0) {
return createPromiseReturnType(node, anyType);
@@ -16958,7 +17134,7 @@ namespace ts {
return type;
}
- function isCommonJsRequire(node: Node) {
+ function isCommonJsRequire(node: Node): boolean {
if (!isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
return false;
}
@@ -16982,7 +17158,7 @@ namespace ts {
if (targetDeclarationKind !== SyntaxKind.Unknown) {
const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
// function/variable declaration should be ambient
- return isInAmbientContext(decl);
+ return !!(decl.flags & NodeFlags.Ambient);
}
return false;
}
@@ -17959,14 +18135,6 @@ namespace ts {
return (target.flags & TypeFlags.Nullable) !== 0 || isTypeComparableTo(source, target);
}
- function getBestChoiceType(type1: Type, type2: Type): Type {
- const firstAssignableToSecond = isTypeAssignableTo(type1, type2);
- const secondAssignableToFirst = isTypeAssignableTo(type2, type1);
- return secondAssignableToFirst && !firstAssignableToSecond ? type1 :
- firstAssignableToSecond && !secondAssignableToFirst ? type2 :
- getUnionType([type1, type2], /*subtypeReduction*/ true);
- }
-
function checkBinaryExpression(node: BinaryExpression, checkMode?: CheckMode) {
return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node);
}
@@ -18103,7 +18271,7 @@ namespace ts {
leftType;
case SyntaxKind.BarBarToken:
return getTypeFacts(leftType) & TypeFacts.Falsy ?
- getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) :
+ getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], /*subtypeReduction*/ true) :
leftType;
case SyntaxKind.EqualsToken:
checkAssignmentOperator(rightType);
@@ -18263,7 +18431,7 @@ namespace ts {
checkExpression(node.condition);
const type1 = checkExpression(node.whenTrue, checkMode);
const type2 = checkExpression(node.whenFalse, checkMode);
- return getBestChoiceType(type1, type2);
+ return getUnionType([type1, type2], /*subtypeReduction*/ true);
}
function checkTemplateExpression(node: TemplateExpression): Type {
@@ -18549,6 +18717,8 @@ namespace ts {
return checkJsxElement(node);
case SyntaxKind.JsxSelfClosingElement:
return checkJsxSelfClosingElement(node);
+ case SyntaxKind.JsxFragment:
+ return checkJsxFragment(node);
case SyntaxKind.JsxAttributes:
return checkJsxAttributes(node, checkMode);
case SyntaxKind.JsxOpeningElement:
@@ -18589,9 +18759,7 @@ namespace ts {
// It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
// Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
// or if its FunctionBody is strict code(11.1.5).
-
- // Grammar checking
- checkGrammarDecorators(node) || checkGrammarModifiers(node);
+ checkGrammarDecoratorsAndModifiers(node);
checkVariableLikeDeclaration(node);
const func = getContainingFunction(node);
@@ -18900,7 +19068,7 @@ namespace ts {
case "arguments":
case "prototype":
const message = Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
- const className = getNameOfSymbol(getSymbolOfNode(node));
+ const className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
error(memberNameNode, message, memberName, className);
break;
}
@@ -18981,14 +19149,13 @@ namespace ts {
function checkPropertyDeclaration(node: PropertyDeclaration) {
// Grammar checking
- checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name);
-
+ if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name);
checkVariableLikeDeclaration(node);
}
function checkMethodDeclaration(node: MethodDeclaration) {
// Grammar checking
- checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name);
+ if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name);
// Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
checkFunctionOrMethodDeclaration(node);
@@ -19004,7 +19171,7 @@ namespace ts {
// Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
checkSignatureDeclaration(node);
// Grammar check for checking only related to constructorDeclaration
- checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node);
+ if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node);
checkSourceElement(node.body);
registerForUnusedIdentifiersCheck(node);
@@ -19101,12 +19268,12 @@ namespace ts {
function checkAccessorDeclaration(node: AccessorDeclaration) {
if (produceDiagnostics) {
// Grammar checking accessors
- checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name);
+ if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name);
checkDecorators(node);
checkSignatureDeclaration(node);
if (node.kind === SyntaxKind.GetAccessor) {
- if (!isInAmbientContext(node) && nodeIsPresent(node.body) && (node.flags & NodeFlags.HasImplicitReturn)) {
+ if (!(node.flags & NodeFlags.Ambient) && nodeIsPresent(node.body) && (node.flags & NodeFlags.HasImplicitReturn)) {
if (!(node.flags & NodeFlags.HasExplicitReturn)) {
error(node.name, Diagnostics.A_get_accessor_must_return_a_value);
}
@@ -19289,7 +19456,7 @@ namespace ts {
}
function isPrivateWithinAmbient(node: Node): boolean {
- return hasModifier(node, ModifierFlags.Private) && isInAmbientContext(node);
+ return hasModifier(node, ModifierFlags.Private) && !!(node.flags & NodeFlags.Ambient);
}
function getEffectiveDeclarationFlags(n: Node, flagsToCheck: ModifierFlags): ModifierFlags {
@@ -19300,7 +19467,7 @@ namespace ts {
if (n.parent.kind !== SyntaxKind.InterfaceDeclaration &&
n.parent.kind !== SyntaxKind.ClassDeclaration &&
n.parent.kind !== SyntaxKind.ClassExpression &&
- isInAmbientContext(n)) {
+ n.flags & NodeFlags.Ambient) {
if (!(flags & ModifierFlags.Ambient)) {
// It is nested in an ambient context, which means it is automatically exported
flags |= ModifierFlags.Export;
@@ -19439,7 +19606,7 @@ namespace ts {
let multipleConstructorImplementation = false;
for (const current of declarations) {
const node = current;
- const inAmbientContext = isInAmbientContext(node);
+ const inAmbientContext = node.flags & NodeFlags.Ambient;
const inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext;
if (inAmbientContextOrInterface) {
// check if declarations are consecutive only if they are non-ambient
@@ -20095,6 +20262,10 @@ namespace ts {
case SyntaxKind.Parameter:
markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
+ const containingSignature = (node as ParameterDeclaration).parent;
+ for (const parameter of containingSignature.parameters) {
+ markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
+ }
break;
}
}
@@ -20280,21 +20451,20 @@ namespace ts {
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
- case SyntaxKind.IndexSignature:
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
- checkUnusedTypeParameters(node);
- break;
case SyntaxKind.TypeAliasDeclaration:
- checkUnusedTypeParameters(node);
+ checkUnusedTypeParameters(node);
break;
+ default:
+ Debug.fail("Node should not have been registered for unused identifiers check");
}
}
}
}
function checkUnusedLocalsAndParameters(node: Node): void {
- if (node.parent.kind !== SyntaxKind.InterfaceDeclaration && noUnusedIdentifiers && !isInAmbientContext(node)) {
+ if (noUnusedIdentifiers && !(node.flags & NodeFlags.Ambient)) {
node.locals.forEach(local => {
if (!local.isReferenced) {
if (local.valueDeclaration && getRootDeclaration(local.valueDeclaration).kind === SyntaxKind.Parameter) {
@@ -20347,7 +20517,7 @@ namespace ts {
}
function checkUnusedClassMembers(node: ClassDeclaration | ClassExpression): void {
- if (compilerOptions.noUnusedLocals && !isInAmbientContext(node)) {
+ if (compilerOptions.noUnusedLocals && !(node.flags & NodeFlags.Ambient)) {
if (node.members) {
for (const member of node.members) {
if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.PropertyDeclaration) {
@@ -20368,7 +20538,7 @@ namespace ts {
}
function checkUnusedTypeParameters(node: ClassDeclaration | ClassExpression | FunctionDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction | ConstructorDeclaration | SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration) {
- if (compilerOptions.noUnusedLocals && !isInAmbientContext(node)) {
+ if (compilerOptions.noUnusedLocals && !(node.flags & NodeFlags.Ambient)) {
if (node.typeParameters) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
@@ -20387,7 +20557,7 @@ namespace ts {
}
function checkUnusedModuleMembers(node: ModuleDeclaration | SourceFile): void {
- if (compilerOptions.noUnusedLocals && !isInAmbientContext(node)) {
+ if (compilerOptions.noUnusedLocals && !(node.flags & NodeFlags.Ambient)) {
node.locals.forEach(local => {
if (!local.isReferenced && !local.exportSymbol) {
for (const declaration of local.declarations) {
@@ -20420,7 +20590,7 @@ namespace ts {
function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) {
// no rest parameters \ declaration context \ overload - no codegen impact
- if (!hasRestParameter(node) || isInAmbientContext(node) || nodeIsMissing((node).body)) {
+ if (!hasRestParameter(node) || node.flags & NodeFlags.Ambient || nodeIsMissing((node).body)) {
return;
}
@@ -20446,7 +20616,7 @@ namespace ts {
return false;
}
- if (isInAmbientContext(node)) {
+ if (node.flags & NodeFlags.Ambient) {
// ambient context - no codegen impact
return false;
}
@@ -20511,7 +20681,7 @@ namespace ts {
// bubble up and find containing type
const enclosingClass = getContainingClass(node);
// if containing type was not found or it is ambient - exit (no codegen)
- if (!enclosingClass || isInAmbientContext(enclosingClass)) {
+ if (!enclosingClass || enclosingClass.flags & NodeFlags.Ambient) {
return;
}
@@ -20864,8 +21034,7 @@ namespace ts {
function checkVariableStatement(node: VariableStatement) {
// Grammar checking
- checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node);
-
+ if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedLetOrConstStatement(node);
forEach(node.declarationList.declarations, checkSourceElement);
}
@@ -21373,7 +21542,7 @@ namespace ts {
function checkBreakOrContinueStatement(node: BreakOrContinueStatement) {
// Grammar checking
- checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node);
+ if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node);
// TODO: Check that target label is valid
}
@@ -21826,7 +21995,7 @@ namespace ts {
checkClassForDuplicateDeclarations(node);
// Only check for reserved static identifiers on non-ambient context.
- if (!isInAmbientContext(node)) {
+ if (!(node.flags & NodeFlags.Ambient)) {
checkClassForStaticPropertyNameConflicts(node);
}
@@ -22054,7 +22223,7 @@ namespace ts {
function checkInterfaceDeclaration(node: InterfaceDeclaration) {
// Grammar checking
- checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node);
+ if (!checkGrammarDecoratorsAndModifiers(node)) checkGrammarInterfaceDeclaration(node);
checkTypeParameters(node.typeParameters);
if (produceDiagnostics) {
@@ -22096,7 +22265,7 @@ namespace ts {
function checkTypeAliasDeclaration(node: TypeAliasDeclaration) {
// Grammar checking
- checkGrammarDecorators(node) || checkGrammarModifiers(node);
+ checkGrammarDecoratorsAndModifiers(node);
checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0);
checkTypeParameters(node.typeParameters);
@@ -22132,7 +22301,7 @@ namespace ts {
}
// In ambient enum declarations that specify no const modifier, enum member declarations that omit
// a value are considered computed members (as opposed to having auto-incremented values).
- if (isInAmbientContext(member.parent) && !isConst(member.parent)) {
+ if (member.parent.flags & NodeFlags.Ambient && !isConst(member.parent)) {
return undefined;
}
// If the member declaration specifies no value, the member is considered a constant enum member.
@@ -22165,7 +22334,7 @@ namespace ts {
else if (isConstEnum) {
error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression);
}
- else if (isInAmbientContext(member.parent)) {
+ else if (member.parent.flags & NodeFlags.Ambient) {
error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
}
else {
@@ -22266,7 +22435,7 @@ namespace ts {
}
// Grammar checking
- checkGrammarDecorators(node) || checkGrammarModifiers(node);
+ checkGrammarDecoratorsAndModifiers(node);
checkTypeNameIsReserved(node.name, Diagnostics.Enum_name_cannot_be_0);
checkCollisionWithCapturedThisVariable(node, node.name);
@@ -22278,7 +22447,7 @@ namespace ts {
computeEnumMemberValues(node);
const enumIsConst = isConst(node);
- if (compilerOptions.isolatedModules && enumIsConst && isInAmbientContext(node)) {
+ if (compilerOptions.isolatedModules && enumIsConst && node.flags & NodeFlags.Ambient) {
error(node.name, Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided);
}
@@ -22330,7 +22499,7 @@ namespace ts {
for (const declaration of declarations) {
if ((declaration.kind === SyntaxKind.ClassDeclaration ||
(declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) &&
- !isInAmbientContext(declaration)) {
+ !(declaration.flags & NodeFlags.Ambient)) {
return declaration;
}
}
@@ -22355,7 +22524,7 @@ namespace ts {
if (produceDiagnostics) {
// Grammar checking
const isGlobalAugmentation = isGlobalScopeAugmentation(node);
- const inAmbientContext = isInAmbientContext(node);
+ const inAmbientContext = node.flags & NodeFlags.Ambient;
if (isGlobalAugmentation && !inAmbientContext) {
error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
}
@@ -22369,7 +22538,7 @@ namespace ts {
return;
}
- if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) {
+ if (!checkGrammarDecoratorsAndModifiers(node)) {
if (!inAmbientContext && node.name.kind === SyntaxKind.StringLiteral) {
grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names);
}
@@ -22574,7 +22743,7 @@ namespace ts {
if (compilerOptions.isolatedModules
&& node.kind === SyntaxKind.ExportSpecifier
&& !(target.flags & SymbolFlags.Value)
- && !isInAmbientContext(node)) {
+ && !(node.flags & NodeFlags.Ambient)) {
error(node, Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided);
}
}
@@ -22592,7 +22761,7 @@ namespace ts {
// If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
return;
}
- if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && hasModifiers(node)) {
+ if (!checkGrammarDecoratorsAndModifiers(node) && hasModifiers(node)) {
grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers);
}
if (checkExternalImportOrExportDeclaration(node)) {
@@ -22619,13 +22788,13 @@ namespace ts {
return;
}
- checkGrammarDecorators(node) || checkGrammarModifiers(node);
+ checkGrammarDecoratorsAndModifiers(node);
if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
checkImportBinding(node);
if (hasModifier(node, ModifierFlags.Export)) {
markExportAsReferenced(node);
}
- if (isInternalModuleImportEqualsDeclaration(node)) {
+ if (node.moduleReference.kind !== SyntaxKind.ExternalModuleReference) {
const target = resolveAlias(getSymbolOfNode(node));
if (target !== unknownSymbol) {
if (target.flags & SymbolFlags.Value) {
@@ -22641,7 +22810,7 @@ namespace ts {
}
}
else {
- if (modulekind >= ModuleKind.ES2015 && !isInAmbientContext(node)) {
+ if (modulekind >= ModuleKind.ES2015 && !(node.flags & NodeFlags.Ambient)) {
// Import equals declaration is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
}
@@ -22655,7 +22824,7 @@ namespace ts {
return;
}
- if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && hasModifiers(node)) {
+ if (!checkGrammarDecoratorsAndModifiers(node) && hasModifiers(node)) {
grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers);
}
@@ -22667,7 +22836,7 @@ namespace ts {
const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && isAmbientModule(node.parent.parent);
const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === SyntaxKind.ModuleBlock &&
- !node.moduleSpecifier && isInAmbientContext(node);
+ !node.moduleSpecifier && node.flags & NodeFlags.Ambient;
if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
@@ -22728,7 +22897,7 @@ namespace ts {
return;
}
// Grammar checking
- if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && hasModifiers(node)) {
+ if (!checkGrammarDecoratorsAndModifiers(node) && hasModifiers(node)) {
grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers);
}
if (node.expression.kind === SyntaxKind.Identifier) {
@@ -22740,11 +22909,11 @@ namespace ts {
checkExternalModuleExports(container);
- if (isInAmbientContext(node) && !isEntityNameExpression(node.expression)) {
+ if ((node.flags & NodeFlags.Ambient) && !isEntityNameExpression(node.expression)) {
grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
}
- if (node.isExportEquals && !isInAmbientContext(node)) {
+ if (node.isExportEquals && !(node.flags & NodeFlags.Ambient)) {
if (modulekind >= ModuleKind.ES2015) {
// export assignment is not supported in es6 modules
grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
@@ -22773,29 +22942,31 @@ namespace ts {
}
// Checks for export * conflicts
const exports = getExportsOfModule(moduleSymbol);
- exports && exports.forEach(({ declarations, flags }, id) => {
- if (id === "__export") {
- return;
- }
- // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
- // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
- if (flags & (SymbolFlags.Namespace | SymbolFlags.Interface | SymbolFlags.Enum)) {
- return;
- }
- const exportedDeclarationsCount = countWhere(declarations, isNotOverloadAndNotAccessor);
- if (flags & SymbolFlags.TypeAlias && exportedDeclarationsCount <= 2) {
- // it is legal to merge type alias with other values
- // so count should be either 1 (just type alias) or 2 (type alias + merged value)
- return;
- }
- if (exportedDeclarationsCount > 1) {
- for (const declaration of declarations) {
- if (isNotOverload(declaration)) {
- diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id)));
+ if (exports) {
+ exports.forEach(({ declarations, flags }, id) => {
+ if (id === "__export") {
+ return;
+ }
+ // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
+ // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
+ if (flags & (SymbolFlags.Namespace | SymbolFlags.Interface | SymbolFlags.Enum)) {
+ return;
+ }
+ const exportedDeclarationsCount = countWhere(declarations, isNotOverloadAndNotAccessor);
+ if (flags & SymbolFlags.TypeAlias && exportedDeclarationsCount <= 2) {
+ // it is legal to merge type alias with other values
+ // so count should be either 1 (just type alias) or 2 (type alias + merged value)
+ return;
+ }
+ if (exportedDeclarationsCount > 1) {
+ for (const declaration of declarations) {
+ if (isNotOverload(declaration)) {
+ diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id)));
+ }
}
}
- }
- });
+ });
+ }
links.exportsChecked = true;
}
}
@@ -23035,7 +23206,7 @@ namespace ts {
checkDeferredNodes();
- if (isExternalModule(node)) {
+ if (isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
@@ -23263,9 +23434,9 @@ namespace ts {
return result;
}
- function isNodeWithinConstructor(node: Node, classDeclaration: ClassLikeDeclaration) {
+ function isNodeWithinConstructorOfClass(node: Node, classDeclaration: ClassLikeDeclaration) {
return findAncestor(node, element => {
- if (isConstructorDeclaration(element) && nodeIsPresent(element.body)) {
+ if (isConstructorDeclaration(element) && nodeIsPresent(element.body) && element.parent === classDeclaration) {
return true;
}
else if (element === classDeclaration || isFunctionLikeDeclaration(element)) {
@@ -23376,7 +23547,7 @@ namespace ts {
return typeParameter && typeParameter.symbol;
}
- if (isPartOfExpression(entityName)) {
+ if (isExpressionNode(entityName)) {
if (nodeIsMissing(entityName)) {
// Missing entity name.
return undefined;
@@ -23508,6 +23679,8 @@ namespace ts {
return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores((node as StringLiteral | NumericLiteral).text));
case SyntaxKind.DefaultKeyword:
+ case SyntaxKind.FunctionKeyword:
+ case SyntaxKind.EqualsGreaterThanToken:
return getSymbolOfNode(node.parent);
default:
@@ -23550,7 +23723,7 @@ namespace ts {
return typeFromTypeNode;
}
- if (isPartOfExpression(node)) {
+ if (isExpressionNode(node)) {
return getRegularTypeOfExpression(node);
}
@@ -24376,7 +24549,7 @@ namespace ts {
function checkExternalEmitHelpers(location: Node, helpers: ExternalEmitHelpers) {
if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
const sourceFile = getSourceFileOfNode(location);
- if (isEffectiveExternalModule(sourceFile, compilerOptions) && !isInAmbientContext(location)) {
+ if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & NodeFlags.Ambient)) {
const helpersModule = resolveHelpersModule(sourceFile, location);
if (helpersModule !== unknownSymbol) {
const uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
@@ -24426,12 +24599,16 @@ namespace ts {
}
// GRAMMAR CHECKING
+ function checkGrammarDecoratorsAndModifiers(node: Node): boolean {
+ return checkGrammarDecorators(node) || checkGrammarModifiers(node);
+ }
+
function checkGrammarDecorators(node: Node): boolean {
if (!node.decorators) {
return false;
}
if (!nodeCanBeDecorated(node)) {
- if (node.kind === SyntaxKind.MethodDeclaration && !ts.nodeIsPresent((node).body)) {
+ if (node.kind === SyntaxKind.MethodDeclaration && !nodeIsPresent((node).body)) {
return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
}
else {
@@ -24578,7 +24755,7 @@ namespace ts {
else if (node.kind === SyntaxKind.Parameter) {
return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
}
- else if (isInAmbientContext(node.parent) && node.parent.kind === SyntaxKind.ModuleBlock) {
+ else if ((node.parent.flags & NodeFlags.Ambient) && node.parent.kind === SyntaxKind.ModuleBlock) {
return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
}
flags |= ModifierFlags.Ambient;
@@ -24614,7 +24791,7 @@ namespace ts {
if (flags & ModifierFlags.Async) {
return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async");
}
- else if (flags & ModifierFlags.Ambient || isInAmbientContext(node.parent)) {
+ else if (flags & ModifierFlags.Ambient || node.parent.flags & NodeFlags.Ambient) {
return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
}
else if (node.kind === SyntaxKind.Parameter) {
@@ -24781,7 +24958,7 @@ namespace ts {
function checkGrammarFunctionLikeDeclaration(node: FunctionLikeDeclaration): boolean {
// Prevent cascading error by short-circuit
const file = getSourceFileOfNode(node);
- return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
+ return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file);
}
@@ -24837,7 +25014,7 @@ namespace ts {
function checkGrammarIndexSignature(node: SignatureDeclaration) {
// Prevent cascading error by short-circuit
- return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node);
+ return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
}
function checkGrammarForAtLeastOneTypeArgument(node: Node, typeArguments: NodeArray): boolean {
@@ -24888,7 +25065,7 @@ namespace ts {
let seenExtendsClause = false;
let seenImplementsClause = false;
- if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) {
+ if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
for (const heritageClause of node.heritageClauses) {
if (heritageClause.token === SyntaxKind.ExtendsKeyword) {
if (seenExtendsClause) {
@@ -24962,7 +25139,7 @@ namespace ts {
node.kind === SyntaxKind.FunctionDeclaration ||
node.kind === SyntaxKind.FunctionExpression ||
node.kind === SyntaxKind.MethodDeclaration);
- if (isInAmbientContext(node)) {
+ if (node.flags & NodeFlags.Ambient) {
return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
}
if (!node.body) {
@@ -24978,11 +25155,13 @@ namespace ts {
}
function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression, inDestructuring: boolean) {
- const seen = createUnderscoreEscapedMap();
- const Property = 1;
- const GetAccessor = 2;
- const SetAccessor = 4;
- const GetOrSetAccessor = GetAccessor | SetAccessor;
+ const enum Flags {
+ Property = 1,
+ GetAccessor = 2,
+ SetAccessor = 4,
+ GetOrSetAccessor = GetAccessor | SetAccessor,
+ }
+ const seen = createUnderscoreEscapedMap();
for (const prop of node.properties) {
if (prop.kind === SyntaxKind.SpreadAssignment) {
@@ -25017,26 +25196,27 @@ namespace ts {
// c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
// d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
// and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
- let currentKind: number;
- if (prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment) {
- // Grammar checking for computedPropertyName and shorthandPropertyAssignment
- checkGrammarForInvalidQuestionMark((prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional);
- if (name.kind === SyntaxKind.NumericLiteral) {
- checkGrammarNumericLiteral(name);
- }
- currentKind = Property;
- }
- else if (prop.kind === SyntaxKind.MethodDeclaration) {
- currentKind = Property;
- }
- else if (prop.kind === SyntaxKind.GetAccessor) {
- currentKind = GetAccessor;
- }
- else if (prop.kind === SyntaxKind.SetAccessor) {
- currentKind = SetAccessor;
- }
- else {
- Debug.assertNever(prop, "Unexpected syntax kind:" + (prop).kind);
+ let currentKind: Flags;
+ switch (prop.kind) {
+ case SyntaxKind.PropertyAssignment:
+ case SyntaxKind.ShorthandPropertyAssignment:
+ // Grammar checking for computedPropertyName and shorthandPropertyAssignment
+ checkGrammarForInvalidQuestionMark((prop).questionToken, Diagnostics.An_object_member_cannot_be_declared_optional);
+ if (name.kind === SyntaxKind.NumericLiteral) {
+ checkGrammarNumericLiteral(name);
+ }
+ // falls through
+ case SyntaxKind.MethodDeclaration:
+ currentKind = Flags.Property;
+ break;
+ case SyntaxKind.GetAccessor:
+ currentKind = Flags.GetAccessor;
+ break;
+ case SyntaxKind.SetAccessor:
+ currentKind = Flags.SetAccessor;
+ break;
+ default:
+ Debug.assertNever(prop, "Unexpected syntax kind:" + (prop).kind);
}
const effectiveName = getPropertyNameForPropertyNameNode(name);
@@ -25049,11 +25229,11 @@ namespace ts {
seen.set(effectiveName, currentKind);
}
else {
- if (currentKind === Property && existingKind === Property) {
+ if (currentKind === Flags.Property && existingKind === Flags.Property) {
grammarErrorOnNode(name, Diagnostics.Duplicate_identifier_0, getTextOfNode(name));
}
- else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) {
- if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) {
+ else if ((currentKind & Flags.GetOrSetAccessor) && (existingKind & Flags.GetOrSetAccessor)) {
+ if (existingKind !== Flags.GetOrSetAccessor && currentKind !== existingKind) {
seen.set(effectiveName, currentKind | existingKind);
}
else {
@@ -25149,7 +25329,7 @@ namespace ts {
if (languageVersion < ScriptTarget.ES5) {
return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
}
- else if (isInAmbientContext(accessor)) {
+ else if (accessor.flags & NodeFlags.Ambient) {
return grammarErrorOnNode(accessor.name, Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context);
}
else if (accessor.body === undefined && !hasModifier(accessor, ModifierFlags.Abstract)) {
@@ -25228,7 +25408,7 @@ namespace ts {
// However, property declarations disallow computed names in general,
// and accessors are not allowed in ambient contexts in general,
// so this error only really matters for methods.
- if (isInAmbientContext(node)) {
+ if (node.flags & NodeFlags.Ambient) {
return checkGrammarForNonSymbolComputedProperty(node.name, Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol);
}
else if (!node.body) {
@@ -25323,7 +25503,7 @@ namespace ts {
function checkGrammarVariableDeclaration(node: VariableDeclaration) {
if (node.parent.parent.kind !== SyntaxKind.ForInStatement && node.parent.parent.kind !== SyntaxKind.ForOfStatement) {
- if (isInAmbientContext(node)) {
+ if (node.flags & NodeFlags.Ambient) {
if (node.initializer) {
if (isConst(node) && !node.type) {
if (!isStringOrNumberLiteralExpression(node.initializer)) {
@@ -25353,7 +25533,7 @@ namespace ts {
}
if (compilerOptions.module !== ModuleKind.ES2015 && compilerOptions.module !== ModuleKind.ESNext && compilerOptions.module !== ModuleKind.System && !compilerOptions.noEmit &&
- !isInAmbientContext(node.parent.parent) && hasModifier(node.parent.parent, ModifierFlags.Export)) {
+ !(node.parent.parent.flags & NodeFlags.Ambient) && hasModifier(node.parent.parent, ModifierFlags.Export)) {
checkESModuleMarker(node.name);
}
@@ -25512,7 +25692,7 @@ namespace ts {
}
}
- if (isInAmbientContext(node) && node.initializer) {
+ if (node.flags & NodeFlags.Ambient && node.initializer) {
return grammarErrorOnFirstToken(node.initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
}
}
@@ -25555,11 +25735,11 @@ namespace ts {
}
function checkGrammarSourceFile(node: SourceFile): boolean {
- return isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
+ return !!(node.flags & NodeFlags.Ambient) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
}
function checkGrammarStatementInAmbientContext(node: Node): boolean {
- if (isInAmbientContext(node)) {
+ if (node.flags & NodeFlags.Ambient) {
// An accessors is already reported about the ambient context
if (isAccessor(node.parent)) {
return getNodeLinks(node).hasReportedStatementInAmbientContext = true;
@@ -25681,4 +25861,17 @@ namespace ts {
return false;
}
}
+
+ namespace JsxNames {
+ // tslint:disable variable-name
+ export const JSX = "JSX" as __String;
+ export const IntrinsicElements = "IntrinsicElements" as __String;
+ export const ElementClass = "ElementClass" as __String;
+ export const ElementAttributesPropertyNameContainer = "ElementAttributesProperty" as __String;
+ export const ElementChildrenAttributeNameContainer = "ElementChildrenAttribute" as __String;
+ export const Element = "Element" as __String;
+ export const IntrinsicAttributes = "IntrinsicAttributes" as __String;
+ export const IntrinsicClassAttributes = "IntrinsicClassAttributes" as __String;
+ // tslint:enable variable-name
+ }
}
diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts
index f050c4a5d16..43ea77c8020 100644
--- a/src/compiler/commandLineParser.ts
+++ b/src/compiler/commandLineParser.ts
@@ -76,13 +76,13 @@ namespace ts {
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,
+ 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,
@@ -93,14 +93,14 @@ namespace ts {
name: "module",
shortName: "m",
type: createMapFromTemplate({
- "none": ModuleKind.None,
- "commonjs": ModuleKind.CommonJS,
- "amd": ModuleKind.AMD,
- "system": ModuleKind.System,
- "umd": ModuleKind.UMD,
- "es6": ModuleKind.ES2015,
- "es2015": ModuleKind.ES2015,
- "esnext": ModuleKind.ESNext
+ none: ModuleKind.None,
+ commonjs: ModuleKind.CommonJS,
+ amd: ModuleKind.AMD,
+ system: ModuleKind.System,
+ umd: ModuleKind.UMD,
+ es6: ModuleKind.ES2015,
+ es2015: ModuleKind.ES2015,
+ esnext: ModuleKind.ESNext
}),
paramType: Diagnostics.KIND,
showInSimplifiedHelpView: true,
@@ -141,6 +141,7 @@ namespace ts {
"es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts",
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
+ "es2017.typedarrays": "lib.es2017.typedarrays.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
}),
},
@@ -325,8 +326,8 @@ namespace ts {
{
name: "moduleResolution",
type: createMapFromTemplate({
- "node": ModuleResolutionKind.NodeJs,
- "classic": ModuleResolutionKind.Classic,
+ node: ModuleResolutionKind.NodeJs,
+ classic: ModuleResolutionKind.Classic,
}),
paramType: Diagnostics.STRATEGY,
category: Diagnostics.Module_Resolution_Options,
@@ -521,8 +522,8 @@ namespace ts {
{
name: "newLine",
type: createMapFromTemplate({
- "crlf": NewLineKind.CarriageReturnLineFeed,
- "lf": NewLineKind.LineFeed
+ crlf: NewLineKind.CarriageReturnLineFeed,
+ lf: NewLineKind.LineFeed
}),
paramType: Diagnostics.NEWLINE,
category: Diagnostics.Advanced_Options,
@@ -1138,6 +1139,13 @@ namespace ts {
reportInvalidOptionValue(option && option.type !== "number");
return Number((valueExpression).text);
+ case SyntaxKind.PrefixUnaryExpression:
+ if ((valueExpression).operator !== SyntaxKind.MinusToken || (valueExpression).operand.kind !== SyntaxKind.NumericLiteral) {
+ break; // not valid JSON syntax
+ }
+ reportInvalidOptionValue(option && option.type !== "number");
+ return -Number(((valueExpression).operand).text);
+
case SyntaxKind.ObjectLiteralExpression:
reportInvalidOptionValue(option && option.type !== "object");
const objectLiteralExpression = valueExpression;
diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts
index 025a4f36d26..1fec1e9562f 100644
--- a/src/compiler/comments.ts
+++ b/src/compiler/comments.ts
@@ -260,7 +260,7 @@ namespace ts {
}
}
- function emitLeadingComment(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
+ function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
if (!hasWrittenComment) {
emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos);
hasWrittenComment = true;
@@ -274,7 +274,7 @@ namespace ts {
if (hasTrailingNewLine) {
writer.writeLine();
}
- else {
+ else if (kind === SyntaxKind.MultiLineCommentTrivia) {
writer.write(" ");
}
}
diff --git a/src/compiler/core.ts b/src/compiler/core.ts
index 657f362067b..f3dd99ee5bf 100644
--- a/src/compiler/core.ts
+++ b/src/compiler/core.ts
@@ -20,12 +20,6 @@ namespace ts {
/* @internal */
namespace ts {
-
- // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times.
- export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(/*locales*/ undefined, { usage: "sort", sensitivity: "accent" }) : undefined;
- // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B".
- export const localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0;
-
/** Create a MapLike with good performance. */
function createDictionaryObject(): MapLike {
const map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
@@ -76,7 +70,7 @@ namespace ts {
// The global Map object. This may not be available, so we must test for it.
declare const Map: { new (): Map } | undefined;
// Internet Explorer's Map doesn't support iteration, so don't use it.
- // tslint:disable-next-line:no-in-operator
+ // tslint:disable-next-line no-in-operator variable-name
const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
// Keep the class inside a function so it doesn't get compiled if it's not used.
@@ -165,12 +159,6 @@ namespace ts {
return getCanonicalFileName(nonCanonicalizedPath);
}
- export const enum Comparison {
- LessThan = -1,
- EqualTo = 0,
- GreaterThan = 1
- }
-
export function length(array: ReadonlyArray) {
return array ? array.length : 0;
}
@@ -307,10 +295,10 @@ namespace ts {
Debug.fail();
}
- export function contains(array: ReadonlyArray, value: T): boolean {
+ export function contains(array: ReadonlyArray, value: T, equalityComparer: EqualityComparer = equateValues): boolean {
if (array) {
for (const v of array) {
- if (v === value) {
+ if (equalityComparer(v, value)) {
return true;
}
}
@@ -655,24 +643,85 @@ namespace ts {
return [...array1, ...array2];
}
- // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication.
- export function deduplicate(array: ReadonlyArray, areEqual?: (a: T, b: T) => boolean): T[] {
- let result: T[];
- if (array) {
- result = [];
- loop: for (const item of array) {
- for (const res of result) {
- if (areEqual ? areEqual(res, item) : res === item) {
- continue loop;
- }
- }
- result.push(item);
+ function deduplicateRelational(array: ReadonlyArray, equalityComparer: EqualityComparer, comparer: Comparer) {
+ // Perform a stable sort of the array. This ensures the first entry in a list of
+ // duplicates remains the first entry in the result.
+ const indices = array.map((_, i) => i);
+ stableSortIndices(array, indices, comparer);
+
+ let last = array[indices[0]];
+ const deduplicated: number[] = [indices[0]];
+ for (let i = 1; i < indices.length; i++) {
+ const index = indices[i];
+ const item = array[index];
+ if (!equalityComparer(last, item)) {
+ deduplicated.push(index);
+ last = item;
}
}
+
+ // restore original order
+ deduplicated.sort();
+ return deduplicated.map(i => array[i]);
+ }
+
+ function deduplicateEquality(array: ReadonlyArray, equalityComparer: EqualityComparer) {
+ const result: T[] = [];
+ for (const item of array) {
+ pushIfUnique(result, item, equalityComparer);
+ }
return result;
}
- export function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean {
+ /**
+ * Deduplicates an unsorted array.
+ * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param comparer An optional `Comparer` used to sort entries before comparison, though the
+ * result will remain in the original order in `array`.
+ */
+ export function deduplicate(array: ReadonlyArray, equalityComparer: EqualityComparer, comparer?: Comparer): T[] {
+ return !array ? undefined :
+ array.length === 0 ? [] :
+ array.length === 1 ? array.slice() :
+ comparer ? deduplicateRelational(array, equalityComparer, comparer) :
+ deduplicateEquality(array, equalityComparer);
+ }
+
+ /**
+ * Deduplicates an array that has already been sorted.
+ */
+ function deduplicateSorted(array: ReadonlyArray, comparer: EqualityComparer | Comparer) {
+ if (!array) return undefined;
+ if (array.length === 0) return [];
+
+ let last = array[0];
+ const deduplicated: T[] = [last];
+ for (let i = 1; i < array.length; i++) {
+ const next = array[i];
+ switch (comparer(next, last)) {
+ // equality comparison
+ case true:
+
+ // relational comparison
+ case Comparison.EqualTo:
+ continue;
+
+ case Comparison.LessThan:
+ // If `array` is sorted, `next` should **never** be less than `last`.
+ return Debug.fail("Array is unsorted.");
+ }
+
+ deduplicated.push(last = next);
+ }
+
+ return deduplicated;
+ }
+
+ export function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer) {
+ return deduplicateSorted(sort(array, comparer), equalityComparer || comparer);
+ }
+
+ export function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equalityComparer: (a: T, b: T) => boolean = equateValues): boolean {
if (!array1 || !array2) {
return array1 === array2;
}
@@ -682,8 +731,7 @@ namespace ts {
}
for (let i = 0; i < array1.length; i++) {
- const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i];
- if (!equals) {
+ if (!equalityComparer(array1[i], array2[i])) {
return false;
}
}
@@ -734,22 +782,44 @@ namespace ts {
}
/**
- * Gets the relative complement of `arrayA` with respect to `b`, returning the elements that
+ * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
* are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
* based on the provided comparer.
*/
- export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: Comparer = compareValues, offsetA = 0, offsetB = 0): T[] | undefined {
+ export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: Comparer): T[] | undefined {
if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB;
const result: T[] = [];
- outer: for (; offsetB < arrayB.length; offsetB++) {
- inner: for (; offsetA < arrayA.length; offsetA++) {
+ loopB: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
+ if (offsetB > 0) {
+ // Ensure `arrayB` is properly sorted.
+ Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), Comparison.EqualTo);
+ }
+
+ loopA: for (const startA = offsetA; offsetA < arrayA.length; offsetA++) {
+ if (offsetA > startA) {
+ // Ensure `arrayA` is properly sorted. We only need to perform this check if
+ // `offsetA` has changed since we entered the loop.
+ Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), Comparison.EqualTo);
+ }
+
switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
- case Comparison.LessThan: break inner;
- case Comparison.EqualTo: continue outer;
- case Comparison.GreaterThan: continue inner;
+ case Comparison.LessThan:
+ // If B is less than A, B does not exist in arrayA. Add B to the result and
+ // move to the next element in arrayB without changing the current position
+ // in arrayA.
+ result.push(arrayB[offsetB]);
+ continue loopB;
+ case Comparison.EqualTo:
+ // If B is equal to A, B exists in arrayA. Move to the next element in
+ // arrayB without adding B to the result or changing the current position
+ // in arrayA.
+ continue loopB;
+ case Comparison.GreaterThan:
+ // If B is greater than A, we need to keep looking for B in arrayA. Move to
+ // the next element in arrayA and recheck.
+ continue loopA;
}
}
- result.push(arrayB[offsetB]);
}
return result;
}
@@ -802,8 +872,7 @@ namespace ts {
start = start === undefined ? 0 : toOffset(from, start);
end = end === undefined ? from.length : toOffset(from, end);
for (let i = start; i < end && i < from.length; i++) {
- const v = from[i];
- if (v !== undefined) {
+ if (from[i] !== undefined) {
to.push(from[i]);
}
}
@@ -813,8 +882,8 @@ namespace ts {
/**
* @return Whether the value was added.
*/
- export function pushIfUnique(array: T[], toAdd: T): boolean {
- if (contains(array, toAdd)) {
+ export function pushIfUnique(array: T[], toAdd: T, equalityComparer?: EqualityComparer): boolean {
+ if (contains(array, toAdd, equalityComparer)) {
return false;
}
else {
@@ -826,9 +895,9 @@ namespace ts {
/**
* Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
*/
- export function appendIfUnique(array: T[] | undefined, toAdd: T): T[] {
+ export function appendIfUnique(array: T[] | undefined, toAdd: T, equalityComparer?: EqualityComparer): T[] {
if (array) {
- pushIfUnique(array, toAdd);
+ pushIfUnique(array, toAdd, equalityComparer);
return array;
}
else {
@@ -836,14 +905,25 @@ namespace ts {
}
}
+ function stableSortIndices(array: ReadonlyArray, indices: number[], comparer: Comparer) {
+ // sort indices by value then position
+ indices.sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y));
+ }
+
+ /**
+ * Returns a new sorted array.
+ */
+ export function sort(array: ReadonlyArray, comparer: Comparer) {
+ return array.slice().sort(comparer);
+ }
+
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
- export function stableSort(array: ReadonlyArray, comparer: Comparer = compareValues) {
- return array
- .map((_, i) => i) // create array of indices
- .sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)) // sort indices by value then position
- .map(i => array[i]); // get sorted array
+ export function stableSort(array: ReadonlyArray, comparer: Comparer) {
+ const indices = array.map((_, i) => i);
+ stableSortIndices(array, indices, comparer);
+ return indices.map(i => array[i]);
}
export function rangeEquals(array1: ReadonlyArray, array2: ReadonlyArray, pos: number, end: number) {
@@ -921,38 +1001,37 @@ namespace ts {
return result;
}
- export type Comparer = (a: T, b: T) => Comparison;
-
/**
- * Performs a binary search, finding the index at which 'value' occurs in 'array'.
+ * Performs a binary search, finding the index at which `value` occurs in `array`.
* If no such index is found, returns the 2's-complement of first index at which
- * number[index] exceeds number.
+ * `array[index]` exceeds `value`.
* @param array A sorted array whose first element must be no larger than number
- * @param number The value to be searched for in the array.
+ * @param value The value to be searched for in the array.
+ * @param keySelector A callback used to select the search key from `value` and each element of
+ * `array`.
+ * @param keyComparer A callback used to compare two keys in a sorted array.
+ * @param offset An offset into `array` at which to start the search.
*/
- export function binarySearch(array: ReadonlyArray, value: T, comparer?: Comparer, offset?: number): number {
+ export function binarySearch(array: ReadonlyArray, value: T, keySelector: (v: T) => U, keyComparer: Comparer, offset?: number): number {
if (!array || array.length === 0) {
return -1;
}
let low = offset || 0;
let high = array.length - 1;
- comparer = comparer !== undefined
- ? comparer
- : (v1, v2) => (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0));
-
+ const key = keySelector(value);
while (low <= high) {
const middle = low + ((high - low) >> 1);
- const midValue = array[middle];
-
- if (comparer(midValue, value) === 0) {
- return middle;
- }
- else if (comparer(midValue, value) > 0) {
- high = middle - 1;
- }
- else {
- low = middle + 1;
+ const midKey = keySelector(array[middle]);
+ switch (keyComparer(midKey, key)) {
+ case Comparison.LessThan:
+ low = middle + 1;
+ break;
+ case Comparison.EqualTo:
+ return middle;
+ case Comparison.GreaterThan:
+ high = middle - 1;
+ break;
}
}
@@ -985,32 +1064,6 @@ namespace ts {
return initial;
}
- export function reduceRight(array: ReadonlyArray, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
- export function reduceRight(array: ReadonlyArray, f: (memo: T, value: T, i: number) => T): T;
- export function reduceRight(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T {
- if (array) {
- const size = array.length;
- if (size > 0) {
- let pos = start === undefined || start > size - 1 ? size - 1 : start;
- const end = count === undefined || pos - count < 0 ? 0 : pos - count;
- let result: T;
- if (arguments.length <= 2) {
- result = array[pos];
- pos--;
- }
- else {
- result = initial;
- }
- while (pos >= end) {
- result = f(result, array[pos], pos);
- pos--;
- }
- return result;
- }
- }
- return initial;
- }
-
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
@@ -1130,13 +1183,13 @@ namespace ts {
* @param left A map-like whose properties should be compared.
* @param right A map-like whose properties should be compared.
*/
- export function equalOwnProperties(left: MapLike, right: MapLike, equalityComparer?: (left: T, right: T) => boolean) {
+ export function equalOwnProperties(left: MapLike, right: MapLike, equalityComparer: EqualityComparer = equateValues) {
if (left === right) return true;
if (!left || !right) return false;
for (const key in left) {
if (hasOwnProperty.call(left, key)) {
if (!hasOwnProperty.call(right, key) === undefined) return false;
- if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false;
+ if (!equalityComparer(left[key], right[key])) return false;
}
}
@@ -1288,7 +1341,7 @@ namespace ts {
}
/** Does nothing. */
- export function noop(): void { }
+ export function noop(_?: {} | null | undefined): void { } // tslint:disable-line no-empty
/** Do nothing and return false */
export function returnFalse(): false { return false; }
@@ -1489,37 +1542,210 @@ namespace ts {
return headChain;
}
- export function compareValues(a: T, b: T): Comparison {
- if (a === b) return Comparison.EqualTo;
- if (a === undefined) return Comparison.LessThan;
- if (b === undefined) return Comparison.GreaterThan;
- return a < b ? Comparison.LessThan : Comparison.GreaterThan;
+ export function equateValues(a: T, b: T) {
+ return a === b;
}
- export function compareStrings(a: string, b: string, ignoreCase?: boolean): Comparison {
+ /**
+ * Compare the equality of two strings using a case-sensitive ordinal comparison.
+ *
+ * Case-sensitive comparisons compare both strings one code-point at a time using the integer
+ * value of each code-point after applying `toUpperCase` to each string. We always map both
+ * strings to their upper-case form as some unicode characters do not properly round-trip to
+ * lowercase (such as `ẞ` (German sharp capital s)).
+ */
+ export function equateStringsCaseInsensitive(a: string, b: string) {
+ return a === b
+ || a !== undefined
+ && b !== undefined
+ && a.toUpperCase() === b.toUpperCase();
+ }
+
+ /**
+ * Compare the equality of two strings using a case-sensitive ordinal comparison.
+ *
+ * Case-sensitive comparisons compare both strings one code-point at a time using the
+ * integer value of each code-point.
+ */
+ export function equateStringsCaseSensitive(a: string, b: string) {
+ return equateValues(a, b);
+ }
+
+ function compareComparableValues(a: string, b: string): Comparison;
+ function compareComparableValues(a: number, b: number): Comparison;
+ function compareComparableValues(a: string | number, b: string | number) {
+ return a === b ? Comparison.EqualTo :
+ a === undefined ? Comparison.LessThan :
+ b === undefined ? Comparison.GreaterThan :
+ a < b ? Comparison.LessThan :
+ Comparison.GreaterThan;
+ }
+
+ /**
+ * Compare two numeric values for their order relative to each other.
+ * To compare strings, use any of the `compareStrings` functions.
+ */
+ export function compareValues(a: number, b: number) {
+ return compareComparableValues(a, b);
+ }
+
+ /**
+ * Compare two strings using a case-insensitive ordinal comparison.
+ *
+ * Ordinal comparisons are based on the difference between the unicode code points of both
+ * strings. Characters with multiple unicode representations are considered unequal. Ordinal
+ * comparisons provide predictable ordering, but place "a" after "B".
+ *
+ * Case-insensitive comparisons compare both strings one code-point at a time using the integer
+ * value of each code-point after applying `toUpperCase` to each string. We always map both
+ * strings to their upper-case form as some unicode characters do not properly round-trip to
+ * lowercase (such as `ẞ` (German sharp capital s)).
+ */
+ export function compareStringsCaseInsensitive(a: string, b: string) {
if (a === b) return Comparison.EqualTo;
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
- if (ignoreCase) {
- // Checking if "collator exists indicates that Intl is available.
- // We still have to check if "collator.compare" is correct. If it is not, use "String.localeComapre"
- if (collator) {
- const result = localeCompareIsCorrect ?
- collator.compare(a, b) :
- a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); // accent means a ≠ b, a ≠ á, a = A
- return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo;
- }
+ a = a.toUpperCase();
+ b = b.toUpperCase();
+ return a < b ? Comparison.LessThan : a > b ? Comparison.GreaterThan : Comparison.EqualTo;
+ }
- a = a.toUpperCase();
- b = b.toUpperCase();
+ /**
+ * Compare two strings using a case-sensitive ordinal comparison.
+ *
+ * Ordinal comparisons are based on the difference between the unicode code points of both
+ * strings. Characters with multiple unicode representations are considered unequal. Ordinal
+ * comparisons provide predictable ordering, but place "a" after "B".
+ *
+ * Case-sensitive comparisons compare both strings one code-point at a time using the integer
+ * value of each code-point.
+ */
+ export function compareStringsCaseSensitive(a: string, b: string) {
+ return compareComparableValues(a, b);
+ }
+
+ /**
+ * Creates a string comparer for use with string collation in the UI.
+ */
+ const createUIStringComparer = (() => {
+ let defaultComparer: Comparer | undefined;
+ let enUSComparer: Comparer | undefined;
+
+ const stringComparerFactory = getStringComparerFactory();
+ return createStringComparer;
+
+ function compareWithCallback(a: string | undefined, b: string | undefined, comparer: (a: string, b: string) => number) {
if (a === b) return Comparison.EqualTo;
+ if (a === undefined) return Comparison.LessThan;
+ if (b === undefined) return Comparison.GreaterThan;
+ const value = comparer(a, b);
+ return value < 0 ? Comparison.LessThan : value > 0 ? Comparison.GreaterThan : Comparison.EqualTo;
}
- return a < b ? Comparison.LessThan : Comparison.GreaterThan;
+ function createIntlCollatorStringComparer(locale: string | undefined): Comparer {
+ // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
+ // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
+ const comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
+ return (a, b) => compareWithCallback(a, b, comparer);
+ }
+
+ function createLocaleCompareStringComparer(locale: string | undefined): Comparer {
+ // if the locale is not the default locale (`undefined`), use the fallback comparer.
+ if (locale !== undefined) return createFallbackStringComparer();
+
+ return (a, b) => compareWithCallback(a, b, compareStrings);
+
+ function compareStrings(a: string, b: string) {
+ return a.localeCompare(b);
+ }
+ }
+
+ function createFallbackStringComparer(): Comparer {
+ // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
+ // We first sort case insensitively. So "Aaa" will come before "baa".
+ // Then we sort case sensitively, so "aaa" will come before "Aaa".
+ //
+ // For case insensitive comparisons we always map both strings to their
+ // upper-case form as some unicode characters do not properly round-trip to
+ // lowercase (such as `ẞ` (German sharp capital s)).
+ return (a, b) => compareWithCallback(a, b, compareDictionaryOrder);
+
+ function compareDictionaryOrder(a: string, b: string) {
+ return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
+ }
+
+ function compareStrings(a: string, b: string) {
+ return a < b ? Comparison.LessThan : a > b ? Comparison.GreaterThan : Comparison.EqualTo;
+ }
+ }
+
+ function getStringComparerFactory() {
+ // If the host supports Intl, we use it for comparisons using the default locale.
+ if (typeof Intl === "object" && typeof Intl.Collator === "function") {
+ return createIntlCollatorStringComparer;
+ }
+
+ // If the host does not support Intl, we fall back to localeCompare.
+ // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
+ if (typeof String.prototype.localeCompare === "function" &&
+ typeof String.prototype.toLocaleUpperCase === "function" &&
+ "a".localeCompare("B") < 0) {
+ return createLocaleCompareStringComparer;
+ }
+
+ // Otherwise, fall back to ordinal comparison:
+ return createFallbackStringComparer;
+ }
+
+ function createStringComparer(locale: string | undefined) {
+ // Hold onto common string comparers. This avoids constantly reallocating comparers during
+ // tests.
+ if (locale === undefined) {
+ return defaultComparer || (defaultComparer = stringComparerFactory(locale));
+ }
+ else if (locale === "en-US") {
+ return enUSComparer || (enUSComparer = stringComparerFactory(locale));
+ }
+ else {
+ return stringComparerFactory(locale);
+ }
+ }
+ })();
+
+ let uiComparerCaseSensitive: Comparer | undefined;
+ let uiLocale: string | undefined;
+
+ export function getUILocale() {
+ return uiLocale;
}
- export function compareStringsCaseInsensitive(a: string, b: string) {
- return compareStrings(a, b, /*ignoreCase*/ true);
+ export function setUILocale(value: string) {
+ if (uiLocale !== value) {
+ uiLocale = value;
+ uiComparerCaseSensitive = undefined;
+ }
+ }
+
+ /**
+ * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
+ *
+ * Ordering is not predictable between different host locales, but is best for displaying
+ * ordered data for UI presentation. Characters with multiple unicode representations may
+ * be considered equal.
+ *
+ * Case-sensitive comparisons compare strings that differ in base characters, or
+ * accents/diacritic marks, or case as unequal.
+ */
+ export function compareStringsCaseSensitiveUI(a: string, b: string) {
+ const comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
+ return comparer(a, b);
+ }
+
+ export function compareProperties(a: T, b: T, key: K, comparer: Comparer) {
+ return a === b ? Comparison.EqualTo :
+ a === undefined ? Comparison.LessThan :
+ b === undefined ? Comparison.GreaterThan :
+ comparer(a[key], b[key]);
}
function getDiagnosticFileName(diagnostic: Diagnostic): string {
@@ -1527,7 +1753,7 @@ namespace ts {
}
export function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison {
- return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -1541,7 +1767,7 @@ namespace ts {
const string1 = isString(text1) ? text1 : text1.messageText;
const string2 = isString(text2) ? text2 : text2.messageText;
- const res = compareValues(string1, string2);
+ const res = compareStringsCaseSensitive(string1, string2);
if (res) {
return res;
}
@@ -1559,27 +1785,8 @@ namespace ts {
return text1 ? Comparison.GreaterThan : Comparison.LessThan;
}
- export function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {
- return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics));
- }
-
- export function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {
- if (diagnostics.length < 2) {
- return diagnostics;
- }
-
- const newDiagnostics = [diagnostics[0]];
- let previousDiagnostic = diagnostics[0];
- for (let i = 1; i < diagnostics.length; i++) {
- const currentDiagnostic = diagnostics[i];
- const isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === Comparison.EqualTo;
- if (!isDupe) {
- newDiagnostics.push(currentDiagnostic);
- previousDiagnostic = currentDiagnostic;
- }
- }
-
- return newDiagnostics;
+ export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[] {
+ return sortAndDeduplicate(diagnostics, compareDiagnostics);
}
export function normalizeSlashes(path: string): string {
@@ -1600,7 +1807,6 @@ namespace ts {
}
if (path.charCodeAt(1) === CharacterCodes.colon) {
if (path.charCodeAt(2) === CharacterCodes.slash) return 3;
- return 2;
}
// Per RFC 1738 'file' URI schema has the shape file:///
// if is omitted then it is assumed that host value is 'localhost',
@@ -1710,6 +1916,19 @@ namespace ts {
return moduleResolution;
}
+ export function getAllowSyntheticDefaultImports(compilerOptions: CompilerOptions) {
+ const moduleKind = getEmitModuleKind(compilerOptions);
+ return compilerOptions.allowSyntheticDefaultImports !== undefined
+ ? compilerOptions.allowSyntheticDefaultImports
+ : moduleKind === ModuleKind.System;
+ }
+
+ export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "alwaysStrict";
+
+ export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean {
+ return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
+ }
+
export function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false;
for (let i = 0; i < str.length; i++) {
@@ -1904,8 +2123,9 @@ namespace ts {
const aComponents = getNormalizedPathComponents(a, currentDirectory);
const bComponents = getNormalizedPathComponents(b, currentDirectory);
const sharedLength = Math.min(aComponents.length, bComponents.length);
+ const comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
for (let i = 0; i < sharedLength; i++) {
- const result = compareStrings(aComponents[i], bComponents[i], ignoreCase);
+ const result = comparer(aComponents[i], bComponents[i]);
if (result !== Comparison.EqualTo) {
return result;
}
@@ -1926,9 +2146,9 @@ namespace ts {
return false;
}
+ const equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (let i = 0; i < parentComponents.length; i++) {
- const result = compareStrings(parentComponents[i], childComponents[i], ignoreCase);
- if (result !== Comparison.EqualTo) {
+ if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
}
@@ -2173,6 +2393,7 @@ namespace ts {
path = normalizePath(path);
currentDirectory = normalizePath(currentDirectory);
+ const comparer = useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive;
const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
const regexFlag = useCaseSensitiveFileNames ? "" : "i";
@@ -2184,7 +2405,6 @@ namespace ts {
// If there are no "includes", then just put everything in results[0].
const results: string[][] = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]];
- const comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive;
for (const basePath of patterns.basePaths) {
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
@@ -2192,10 +2412,9 @@ namespace ts {
return flatten(results);
function visitDirectory(path: string, absolutePath: string, depth: number | undefined) {
- let { files, directories } = getFileSystemEntries(path);
- files = files.slice().sort(comparer);
+ const { files, directories } = getFileSystemEntries(path);
- for (const current of files) {
+ for (const current of sort(files, comparer)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsOneOf(name, extensions)) continue;
@@ -2218,8 +2437,7 @@ namespace ts {
}
}
- directories = directories.slice().sort(comparer);
- for (const current of directories) {
+ for (const current of sort(directories, comparer)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
@@ -2249,7 +2467,7 @@ namespace ts {
}
// Sort the offsets array using either the literal or canonical path representations.
- includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive);
+ includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive);
// Iterate over each include base path and include unique base paths that are not a
// subpath of an existing base path
@@ -2316,7 +2534,11 @@ namespace ts {
if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
- return deduplicate([...allSupportedExtensions, ...extraFileExtensions.map(e => e.extension)]);
+ return deduplicate(
+ [...allSupportedExtensions, ...extraFileExtensions.map(e => e.extension)],
+ equateStringsCaseSensitive,
+ compareStringsCaseSensitive
+ );
}
export function hasJavaScriptFileExtension(fileName: string) {
@@ -2448,8 +2670,7 @@ namespace ts {
}
}
- function Signature() {
- }
+ function Signature() {} // tslint:disable-line no-empty
function Node(this: Node, kind: SyntaxKind, pos: number, end: number) {
this.id = 0;
@@ -2720,7 +2941,7 @@ namespace ts {
return (arg: T) => f(arg) && g(arg);
}
- export function assertTypeIsNever(_: never): void { }
+ export function assertTypeIsNever(_: never): void { } // tslint:disable-line no-empty
export interface FileAndDirectoryExistence {
fileExists: boolean;
@@ -2887,10 +3108,9 @@ namespace ts {
function addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path) {
const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
if (existingResult) {
- // This was a folder already present, remove it if this doesnt exist any more
- if (!host.directoryExists(fileOrDirectory)) {
- cachedReadDirectoryResult.delete(fileOrDirectoryPath);
- }
+ // Just clear the cache for now
+ // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
+ clearCache();
}
else {
// This was earlier a file (hence not in cached directory contents)
@@ -2903,8 +3123,14 @@ namespace ts {
fileExists: host.fileExists(fileOrDirectoryPath),
directoryExists: host.directoryExists(fileOrDirectoryPath)
};
- updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
- updateFileSystemEntry(parentResult.directories, baseName, fsQueryResult.directoryExists);
+ if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
+ // Folder added or removed, clear the cache instead of updating the folder and its structure
+ clearCache();
+ }
+ else {
+ // No need to update the directory structure, just files
+ updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
+ }
return fsQueryResult;
}
}
diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts
index 48b97b048e9..3276e68b2ac 100644
--- a/src/compiler/declarationEmitter.ts
+++ b/src/compiler/declarationEmitter.ts
@@ -1429,45 +1429,40 @@ namespace ts {
function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) {
- // Setters have to have type named and cannot infer it so, the type should always be named
- if (hasModifier(accessorWithTypeAnnotation.parent, ModifierFlags.Static)) {
+ // Getters can infer the return type from the returned expression, but setters cannot, so the
+ // "_from_external_module_1_but_cannot_be_named" case cannot occur.
+ if (hasModifier(accessorWithTypeAnnotation, ModifierFlags.Static)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
- Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
- Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1;
+ Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
+ Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
}
else {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
- Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
- Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1;
+ Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
+ Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
}
- return {
- diagnosticMessage,
- errorNode: accessorWithTypeAnnotation.parameters[0],
- // TODO(jfreeman): Investigate why we are passing node.name instead of node.parameters[0].name
- typeName: accessorWithTypeAnnotation.name
- };
}
else {
if (hasModifier(accessorWithTypeAnnotation, ModifierFlags.Static)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
- Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
- Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
- Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0;
+ Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
+ Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
+ Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
}
else {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
- Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
- Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
- Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0;
+ Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
+ Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
+ Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
}
- return {
- diagnosticMessage,
- errorNode: accessorWithTypeAnnotation.name,
- typeName: undefined
- };
}
+ return {
+ diagnosticMessage,
+ errorNode: accessorWithTypeAnnotation.name,
+ typeName: accessorWithTypeAnnotation.name
+ };
}
}
diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json
index 0f88d5e4ac5..964264ff6e8 100644
--- a/src/compiler/diagnosticMessages.json
+++ b/src/compiler/diagnosticMessages.json
@@ -1716,7 +1716,7 @@
"category": "Error",
"code": 2510
},
- "Cannot create an instance of the abstract class '{0}'.": {
+ "Cannot create an instance of an abstract class.": {
"category": "Error",
"code": 2511
},
@@ -2321,43 +2321,43 @@
"category": "Error",
"code": 4033
},
- "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'.": {
+ "Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'.": {
"category": "Error",
"code": 4034
},
- "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'.": {
+ "Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'.": {
"category": "Error",
"code": 4035
},
- "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'.": {
+ "Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'.": {
"category": "Error",
"code": 4036
},
- "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'.": {
+ "Parameter type of public setter '{0}' from exported class has or is using private name '{1}'.": {
"category": "Error",
"code": 4037
},
- "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named.": {
+ "Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named.": {
"category": "Error",
"code": 4038
},
- "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'.": {
+ "Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'.": {
"category": "Error",
"code": 4039
},
- "Return type of public static property getter from exported class has or is using private name '{0}'.": {
+ "Return type of public static getter '{0}' from exported class has or is using private name '{1}'.": {
"category": "Error",
"code": 4040
},
- "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named.": {
+ "Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named.": {
"category": "Error",
"code": 4041
},
- "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'.": {
+ "Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'.": {
"category": "Error",
"code": 4042
},
- "Return type of public property getter from exported class has or is using private name '{0}'.": {
+ "Return type of public getter '{0}' from exported class has or is using private name '{1}'.": {
"category": "Error",
"code": 4043
},
@@ -3615,6 +3615,18 @@
"category": "Error",
"code": 17013
},
+ "JSX fragment has no corresponding closing tag.": {
+ "category": "Error",
+ "code": 17014
+ },
+ "Expected corresponding closing tag for JSX fragment.": {
+ "category": "Error",
+ "code": 17015
+ },
+ "JSX fragment is not supported when using --jsxFactory": {
+ "category": "Error",
+ "code":17016
+ },
"Circularity detected while resolving configuration: {0}": {
"category": "Error",
@@ -3781,5 +3793,21 @@
"Infer parameter types from usage.": {
"category": "Message",
"code": 95012
+ },
+ "Convert to default import": {
+ "category": "Message",
+ "code": 95013
+ },
+ "Install '{0}'": {
+ "category": "Message",
+ "code": 95014
+ },
+ "Import '{0}' = require(\"{1}\").": {
+ "category": "Message",
+ "code": 95015
+ },
+ "Import * as '{0}' from \"{1}\".": {
+ "category": "Message",
+ "code": 95016
}
}
diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts
index 9ce220e723f..7a1d88d3bfd 100644
--- a/src/compiler/emitter.ts
+++ b/src/compiler/emitter.ts
@@ -699,9 +699,11 @@ namespace ts {
case SyntaxKind.JsxText:
return emitJsxText(node);
case SyntaxKind.JsxOpeningElement:
- return emitJsxOpeningElement(node);
+ case SyntaxKind.JsxOpeningFragment:
+ return emitJsxOpeningElementOrFragment(node);
case SyntaxKind.JsxClosingElement:
- return emitJsxClosingElement(node);
+ case SyntaxKind.JsxClosingFragment:
+ return emitJsxClosingElementOrFragment(node);
case SyntaxKind.JsxAttribute:
return emitJsxAttribute(node);
case SyntaxKind.JsxAttributes:
@@ -836,6 +838,8 @@ namespace ts {
return emitJsxElement(node);
case SyntaxKind.JsxSelfClosingElement:
return emitJsxSelfClosingElement(node);
+ case SyntaxKind.JsxFragment:
+ return emitJsxFragment(node);
// Transformation nodes
case SyntaxKind.PartiallyEmittedExpression:
@@ -1729,26 +1733,15 @@ namespace ts {
increaseIndent();
}
- if (getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) {
- emitSignatureHead(node);
- if (onEmitNode) {
- onEmitNode(EmitHint.Unspecified, body, emitBlockCallback);
- }
- else {
- emitBlockFunctionBody(body);
- }
+ pushNameGenerationScope(node);
+ emitSignatureHead(node);
+ if (onEmitNode) {
+ onEmitNode(EmitHint.Unspecified, body, emitBlockCallback);
}
else {
- pushNameGenerationScope();
- emitSignatureHead(node);
- if (onEmitNode) {
- onEmitNode(EmitHint.Unspecified, body, emitBlockCallback);
- }
- else {
- emitBlockFunctionBody(body);
- }
- popNameGenerationScope();
+ emitBlockFunctionBody(body);
}
+ popNameGenerationScope(node);
if (indentedFlag) {
decreaseIndent();
@@ -1867,11 +1860,9 @@ namespace ts {
emitTypeParameters(node, node.typeParameters);
emitList(node, node.heritageClauses, ListFormat.ClassHeritageClauses);
- pushNameGenerationScope();
write(" {");
emitList(node, node.members, ListFormat.ClassMembers);
write("}");
- popNameGenerationScope();
if (indentedFlag) {
decreaseIndent();
@@ -1905,11 +1896,9 @@ namespace ts {
emitModifiers(node, node.modifiers);
write("enum ");
emit(node.name);
- pushNameGenerationScope();
write(" {");
emitList(node, node.members, ListFormat.EnumMembers);
write("}");
- popNameGenerationScope();
}
function emitModuleDeclaration(node: ModuleDeclaration) {
@@ -1931,11 +1920,11 @@ namespace ts {
}
function emitModuleBlock(node: ModuleBlock) {
- pushNameGenerationScope();
+ pushNameGenerationScope(node);
write("{");
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
write("}");
- popNameGenerationScope();
+ popNameGenerationScope(node);
}
function emitCaseBlock(node: CaseBlock) {
@@ -2060,7 +2049,7 @@ namespace ts {
function emitJsxElement(node: JsxElement) {
emit(node.openingElement);
- emitList(node, node.children, ListFormat.JsxElementChildren);
+ emitList(node, node.children, ListFormat.JsxElementOrFragmentChildren);
emit(node.closingElement);
}
@@ -2075,14 +2064,24 @@ namespace ts {
write("/>");
}
- function emitJsxOpeningElement(node: JsxOpeningElement) {
+ function emitJsxFragment(node: JsxFragment) {
+ emit(node.openingFragment);
+ emitList(node, node.children, ListFormat.JsxElementOrFragmentChildren);
+ emit(node.closingFragment);
+ }
+
+ function emitJsxOpeningElementOrFragment(node: JsxOpeningElement | JsxOpeningFragment) {
write("<");
- emitJsxTagName(node.tagName);
- writeIfAny(node.attributes.properties, " ");
- // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap
- if (node.attributes.properties && node.attributes.properties.length > 0) {
- emit(node.attributes);
+
+ if (isJsxOpeningElement(node)) {
+ emitJsxTagName(node.tagName);
+ // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap
+ if (node.attributes.properties && node.attributes.properties.length > 0) {
+ write(" ");
+ emit(node.attributes);
+ }
}
+
write(">");
}
@@ -2090,9 +2089,11 @@ namespace ts {
writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true));
}
- function emitJsxClosingElement(node: JsxClosingElement) {
+ function emitJsxClosingElementOrFragment(node: JsxClosingElement | JsxClosingFragment) {
write("");
- emitJsxTagName(node.tagName);
+ if (isJsxClosingElement(node)) {
+ emitJsxTagName(node.tagName);
+ }
write(">");
}
@@ -2268,11 +2269,11 @@ namespace ts {
function emitSourceFileWorker(node: SourceFile) {
const statements = node.statements;
- pushNameGenerationScope();
+ pushNameGenerationScope(node);
emitHelpersIndirect(node);
const index = findIndex(statements, statement => !isPrologueDirective(statement));
emitList(node, statements, ListFormat.MultiLine, index === -1 ? statements.length : index);
- popNameGenerationScope();
+ popNameGenerationScope(node);
}
// Transformation nodes
@@ -2611,12 +2612,6 @@ namespace ts {
writer.decreaseIndent();
}
- function writeIfAny(nodes: NodeArray, text: string) {
- if (some(nodes)) {
- write(text);
- }
- }
-
function writeToken(token: SyntaxKind, pos: number, contextNode?: Node) {
return onEmitSourceMapOfToken
? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText)
@@ -2651,8 +2646,8 @@ namespace ts {
function writeLines(text: string): void {
const lines = text.split(/\r\n?|\n/g);
const indentation = guessIndentation(lines);
- for (let i = 0; i < lines.length; i++) {
- const line = indentation ? lines[i].slice(indentation) : lines[i];
+ for (const lineText of lines) {
+ const line = indentation ? lineText.slice(indentation) : lineText;
if (line.length) {
writeLine();
write(line);
@@ -2741,7 +2736,7 @@ namespace ts {
}
}
else {
- return nextNode.startsOnNewLine;
+ return getStartsOnNewLine(nextNode);
}
}
@@ -2772,7 +2767,7 @@ namespace ts {
function synthesizedNodeStartsOnNewLine(node: Node, format?: ListFormat) {
if (nodeIsSynthesized(node)) {
- const startsOnNewLine = node.startsOnNewLine;
+ const startsOnNewLine = getStartsOnNewLine(node);
if (startsOnNewLine === undefined) {
return (format & ListFormat.PreferNewLine) !== 0;
}
@@ -2789,7 +2784,7 @@ namespace ts {
node2 = skipSynthesizedParentheses(node2);
// Always use a newline for synthesized code if the synthesizer desires it.
- if (node2.startsOnNewLine) {
+ if (getStartsOnNewLine(node2)) {
return true;
}
@@ -2848,7 +2843,10 @@ namespace ts {
/**
* Push a new name generation scope.
*/
- function pushNameGenerationScope() {
+ function pushNameGenerationScope(node: Node | undefined) {
+ if (node && getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) {
+ return;
+ }
tempFlagsStack.push(tempFlags);
tempFlags = 0;
}
@@ -2856,7 +2854,10 @@ namespace ts {
/**
* Pop the current name generation scope.
*/
- function popNameGenerationScope() {
+ function popNameGenerationScope(node: Node | undefined) {
+ if (node && getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) {
+ return;
+ }
tempFlags = tempFlagsStack.pop();
}
@@ -2867,8 +2868,17 @@ namespace ts {
if (name.autoGenerateKind === GeneratedIdentifierKind.Node) {
// Node names generate unique names based on their original node
// and are cached based on that node's id.
- const node = getNodeForGeneratedName(name);
- return generateNameCached(node);
+ if (name.skipNameGenerationScope) {
+ const savedTempFlags = tempFlags;
+ popNameGenerationScope(/*node*/ undefined);
+ const result = generateNameCached(getNodeForGeneratedName(name));
+ pushNameGenerationScope(/*node*/ undefined);
+ tempFlags = savedTempFlags;
+ return result;
+ }
+ else {
+ return generateNameCached(getNodeForGeneratedName(name));
+ }
}
else {
// Auto, Loop, and Unique names are cached based on their unique
@@ -3176,7 +3186,7 @@ namespace ts {
EnumMembers = CommaDelimited | Indented | MultiLine,
CaseBlockClauses = Indented | MultiLine,
NamedImportsOrExportsElements = CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | SingleLine | SpaceBetweenBraces,
- JsxElementChildren = SingleLine | NoInterveningComments,
+ JsxElementOrFragmentChildren = SingleLine | NoInterveningComments,
JsxElementAttributes = SingleLine | SpaceBetweenSiblings | NoInterveningComments,
CaseOrDefaultClauseStatements = Indented | MultiLine | NoTrailingNewLine | OptionalIfEmpty,
HeritageClauseTypes = CommaDelimited | SpaceBetweenSiblings | SingleLine,
diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts
index 65c1c92f366..e8dfcbc1e94 100644
--- a/src/compiler/factory.ts
+++ b/src/compiler/factory.ts
@@ -13,9 +13,6 @@ namespace ts {
if (updated !== original) {
setOriginalNode(updated, original);
setTextRange(updated, original);
- if (original.startsOnNewLine) {
- updated.startsOnNewLine = true;
- }
aggregateTransformFlags(updated);
}
return updated;
@@ -73,11 +70,10 @@ namespace ts {
// Literals
- export function createLiteral(value: string): StringLiteral;
+ /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */
+ export function createLiteral(value: string | StringLiteral | NumericLiteral | Identifier): StringLiteral;
export function createLiteral(value: number): NumericLiteral;
export function createLiteral(value: boolean): BooleanLiteral;
- /** Create a string literal whose source text is read from a source node during emit. */
- export function createLiteral(sourceNode: StringLiteral | NumericLiteral | Identifier): StringLiteral;
export function createLiteral(value: string | number | boolean): PrimaryExpression;
export function createLiteral(value: string | number | boolean | StringLiteral | NumericLiteral | Identifier): PrimaryExpression {
if (typeof value === "number") {
@@ -116,6 +112,7 @@ namespace ts {
export function createIdentifier(text: string): Identifier;
/* @internal */
+ // tslint:disable-next-line unified-signatures
export function createIdentifier(text: string, typeArguments: ReadonlyArray): Identifier;
export function createIdentifier(text: string, typeArguments?: ReadonlyArray): Identifier {
const node = createSynthesizedNode(SyntaxKind.Identifier);
@@ -168,11 +165,15 @@ namespace ts {
}
/** Create a unique name generated for a node. */
- export function getGeneratedNameForNode(node: Node): Identifier {
+ export function getGeneratedNameForNode(node: Node): Identifier;
+ // tslint:disable-next-line unified-signatures
+ /*@internal*/ export function getGeneratedNameForNode(node: Node, shouldSkipNameGenerationScope?: boolean): Identifier;
+ export function getGeneratedNameForNode(node: Node, shouldSkipNameGenerationScope?: boolean): Identifier {
const name = createIdentifier("");
name.autoGenerateKind = GeneratedIdentifierKind.Node;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
+ name.skipNameGenerationScope = !!shouldSkipNameGenerationScope;
nextAutoGenerateId++;
return name;
}
@@ -1982,7 +1983,7 @@ namespace ts {
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.isExportEquals = isExportEquals;
- node.expression = expression;
+ node.expression = isExportEquals ? parenthesizeBinaryOperand(SyntaxKind.EqualsToken, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : parenthesizeDefaultExpression(expression);
return node;
}
@@ -2115,6 +2116,22 @@ namespace ts {
: node;
}
+ export function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment) {
+ const node = createSynthesizedNode(SyntaxKind.JsxFragment);
+ node.openingFragment = openingFragment;
+ node.children = createNodeArray(children);
+ node.closingFragment = closingFragment;
+ return node;
+ }
+
+ export function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment) {
+ return node.openingFragment !== openingFragment
+ || node.children !== children
+ || node.closingFragment !== closingFragment
+ ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
+ : node;
+ }
+
export function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression) {
const node = createSynthesizedNode(SyntaxKind.JsxAttribute);
node.name = name;
@@ -2625,7 +2642,7 @@ namespace ts {
/**
* Gets a custom text range to use when emitting source maps.
*/
- export function getSourceMapRange(node: Node) {
+ export function getSourceMapRange(node: Node): SourceMapRange {
const emitNode = node.emitNode;
return (emitNode && emitNode.sourceMapRange) || node;
}
@@ -2638,6 +2655,7 @@ namespace ts {
return node;
}
+ // tslint:disable-next-line variable-name
let SourceMapSource: new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource;
/**
@@ -2666,6 +2684,24 @@ namespace ts {
return node;
}
+ /**
+ * Gets a custom text range to use when emitting comments.
+ */
+ /*@internal*/
+ export function getStartsOnNewLine(node: Node) {
+ const emitNode = node.emitNode;
+ return emitNode && emitNode.startsOnNewLine;
+ }
+
+ /**
+ * Sets a custom text range to use when emitting comments.
+ */
+ /*@internal*/
+ export function setStartsOnNewLine(node: T, newLine: boolean) {
+ getOrCreateEmitNode(node).startsOnNewLine = newLine;
+ return node;
+ }
+
/**
* Gets a custom text range to use when emitting comments.
*/
@@ -2824,7 +2860,8 @@ namespace ts {
sourceMapRange,
tokenSourceMapRanges,
constantValue,
- helpers
+ helpers,
+ startsOnNewLine,
} = sourceEmitNode;
if (!destEmitNode) destEmitNode = {};
// We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
@@ -2836,6 +2873,7 @@ namespace ts {
if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
if (constantValue !== undefined) destEmitNode.constantValue = constantValue;
if (helpers) destEmitNode.helpers = addRange(destEmitNode.helpers, helpers);
+ if (startsOnNewLine !== undefined) destEmitNode.startsOnNewLine = startsOnNewLine;
return destEmitNode;
}
@@ -2951,7 +2989,7 @@ namespace ts {
);
}
- function createReactNamespace(reactNamespace: string, parent: JsxOpeningLikeElement) {
+ function createReactNamespace(reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment) {
// To ensure the emit resolver can properly resolve the namespace, we need to
// treat this identifier as if it were a source tree node by clearing the `Synthesized`
// flag and setting a parent node.
@@ -2963,7 +3001,7 @@ namespace ts {
return react;
}
- function createJsxFactoryExpressionFromEntityName(jsxFactory: EntityName, parent: JsxOpeningLikeElement): Expression {
+ function createJsxFactoryExpressionFromEntityName(jsxFactory: EntityName, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression {
if (isQualifiedName(jsxFactory)) {
const left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
const right = createIdentifier(idText(jsxFactory.right));
@@ -2975,7 +3013,7 @@ namespace ts {
}
}
- function createJsxFactoryExpression(jsxFactoryEntity: EntityName, reactNamespace: string, parent: JsxOpeningLikeElement): Expression {
+ function createJsxFactoryExpression(jsxFactoryEntity: EntityName, reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression {
return jsxFactoryEntity ?
createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
createPropertyAccess(
@@ -2997,7 +3035,38 @@ namespace ts {
if (children.length > 1) {
for (const child of children) {
- child.startsOnNewLine = true;
+ startOnNewLine(child);
+ argumentsList.push(child);
+ }
+ }
+ else {
+ argumentsList.push(children[0]);
+ }
+ }
+
+ return setTextRange(
+ createCall(
+ createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement),
+ /*typeArguments*/ undefined,
+ argumentsList
+ ),
+ location
+ );
+ }
+
+ export function createExpressionForJsxFragment(jsxFactoryEntity: EntityName, reactNamespace: string, children: Expression[], parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression {
+ const tagName = createPropertyAccess(
+ createReactNamespace(reactNamespace, parentElement),
+ "Fragment"
+ );
+
+ const argumentsList = [tagName];
+ argumentsList.push(createNull());
+
+ if (children && children.length > 0) {
+ if (children.length > 1) {
+ for (const child of children) {
+ startOnNewLine(child);
argumentsList.push(child);
}
}
@@ -3572,8 +3641,8 @@ namespace ts {
);
setOriginalNode(updated, node);
setTextRange(updated, node);
- if (node.startsOnNewLine) {
- updated.startsOnNewLine = true;
+ if (getStartsOnNewLine(node)) {
+ setStartsOnNewLine(updated, /*newLine*/ true);
}
aggregateTransformFlags(updated);
return updated;
@@ -3885,6 +3954,27 @@ namespace ts {
: e;
}
+ /**
+ * [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
+ * has a lookahead restriction for `function`, `async function`, and `class`.
+ *
+ * Basically, that means we need to parenthesize in the following cases:
+ *
+ * - BinaryExpression of CommaToken
+ * - CommaList (synthetic list of multiple comma expressions)
+ * - FunctionExpression
+ * - ClassExpression
+ */
+ export function parenthesizeDefaultExpression(e: Expression) {
+ const check = skipPartiallyEmittedExpressions(e);
+ return (check.kind === SyntaxKind.ClassExpression ||
+ check.kind === SyntaxKind.FunctionExpression ||
+ check.kind === SyntaxKind.CommaListExpression ||
+ isBinaryExpression(check) && check.operatorToken.kind === SyntaxKind.CommaToken)
+ ? createParen(e)
+ : e;
+ }
+
/**
* Wraps an expression in parentheses if it is needed in order to use the expression
* as the expression of a NewExpression node.
@@ -4181,8 +4271,7 @@ namespace ts {
}
export function startOnNewLine(node: T): T {
- node.startsOnNewLine = true;
- return node;
+ return setStartsOnNewLine(node, /*newLine*/ true);
}
export function getExternalHelpersModuleName(node: SourceFile) {
@@ -4230,7 +4319,7 @@ namespace ts {
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
const name = namespaceDeclaration.name;
- return isGeneratedIdentifier(name) ? name : createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name));
+ return isGeneratedIdentifier(name) ? name : createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name));
}
if (node.kind === SyntaxKind.ImportDeclaration && (node).importClause) {
return getGeneratedNameForNode(node);
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts
index b27d4811ecb..79b5eb30c49 100644
--- a/src/compiler/parser.ts
+++ b/src/compiler/parser.ts
@@ -12,10 +12,12 @@ namespace ts {
JSDoc = 1 << 5,
}
+ // tslint:disable variable-name
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
+ // tslint:enable variable-name
export function createNode(kind: SyntaxKind, pos?: number, end?: number): Node {
if (kind === SyntaxKind.SourceFile) {
@@ -377,6 +379,10 @@ namespace ts {
return visitNode(cbNode, (node).openingElement) ||
visitNodes(cbNode, cbNodes, (node).children) ||
visitNode(cbNode, (node).closingElement);
+ case SyntaxKind.JsxFragment:
+ return visitNode(cbNode, (node).openingFragment) ||
+ visitNodes(cbNode, cbNodes, (node).children) ||
+ visitNode(cbNode, (node).closingFragment);
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
return visitNode(cbNode, (node).tagName) ||
@@ -520,10 +526,12 @@ namespace ts {
const disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext;
// capture constructors in 'initializeState' to avoid null checks
+ // tslint:disable variable-name
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
+ // tslint:enable variable-name
let sourceFile: SourceFile;
let parseDiagnostics: Diagnostic[];
@@ -627,6 +635,7 @@ namespace ts {
}
export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName {
+ // Choice of `isDeclarationFile` should be arbitrary
initializeState(content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS);
// Prime the scanner.
nextToken();
@@ -639,7 +648,7 @@ namespace ts {
export function parseJsonText(fileName: string, sourceText: string): JsonSourceFile {
initializeState(sourceText, ScriptTarget.ES2015, /*syntaxCursor*/ undefined, ScriptKind.JSON);
// Set source file so that errors will be reported with this file name
- sourceFile = createSourceFile(fileName, ScriptTarget.ES2015, ScriptKind.JSON);
+ sourceFile = createSourceFile(fileName, ScriptTarget.ES2015, ScriptKind.JSON, /*isDeclaration*/ false);
const result = sourceFile;
// Prime the scanner.
@@ -681,7 +690,16 @@ namespace ts {
identifierCount = 0;
nodeCount = 0;
- contextFlags = scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JSON ? NodeFlags.JavaScriptFile : NodeFlags.None;
+ switch (scriptKind) {
+ case ScriptKind.JS:
+ case ScriptKind.JSX:
+ case ScriptKind.JSON:
+ contextFlags = NodeFlags.JavaScriptFile;
+ break;
+ default:
+ contextFlags = NodeFlags.None;
+ break;
+ }
parseErrorBeforeNextFinishedNode = false;
// Initialize and prime the scanner before parsing the source elements.
@@ -705,7 +723,12 @@ namespace ts {
}
function parseSourceFileWorker(fileName: string, languageVersion: ScriptTarget, setParentNodes: boolean, scriptKind: ScriptKind): SourceFile {
- sourceFile = createSourceFile(fileName, languageVersion, scriptKind);
+ const isDeclarationFile = isDeclarationFileName(fileName);
+ if (isDeclarationFile) {
+ contextFlags |= NodeFlags.Ambient;
+ }
+
+ sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
sourceFile.flags = contextFlags;
// Prime the scanner.
@@ -782,7 +805,7 @@ namespace ts {
}
}
- function createSourceFile(fileName: string, languageVersion: ScriptTarget, scriptKind: ScriptKind): SourceFile {
+ function createSourceFile(fileName: string, languageVersion: ScriptTarget, scriptKind: ScriptKind, isDeclarationFile: boolean): SourceFile {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
const sourceFile = new SourceFileConstructor(SyntaxKind.SourceFile, /*pos*/ 0, /* end */ sourceText.length);
@@ -793,7 +816,7 @@ namespace ts {
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = normalizePath(fileName);
sourceFile.languageVariant = getLanguageVariant(scriptKind);
- sourceFile.isDeclarationFile = fileExtensionIs(sourceFile.fileName, Extension.Dts);
+ sourceFile.isDeclarationFile = isDeclarationFile;
sourceFile.scriptKind = scriptKind;
return sourceFile;
@@ -1423,6 +1446,11 @@ namespace ts {
return tokenIsIdentifierOrKeyword(token());
}
+ function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
+ nextToken();
+ return tokenIsIdentifierOrKeywordOrGreaterThan(token());
+ }
+
function isHeritageClauseExtendsOrImplementsKeyword(): boolean {
if (token() === SyntaxKind.ImplementsKeyword ||
token() === SyntaxKind.ExtendsKeyword) {
@@ -3802,9 +3830,9 @@ namespace ts {
node.operand = parseLeftHandSideExpressionOrHigher();
return finishNode(node);
}
- else if (sourceFile.languageVariant === LanguageVariant.JSX && token() === SyntaxKind.LessThanToken && lookAhead(nextTokenIsIdentifierOrKeyword)) {
+ else if (sourceFile.languageVariant === LanguageVariant.JSX && token() === SyntaxKind.LessThanToken && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
// JSXElement is part of primaryExpression
- return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true);
+ return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
}
const expression = parseLeftHandSideExpressionOrHigher();
@@ -3959,14 +3987,14 @@ namespace ts {
}
- function parseJsxElementOrSelfClosingElement(inExpressionContext: boolean): JsxElement | JsxSelfClosingElement {
- const opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext);
- let result: JsxElement | JsxSelfClosingElement;
+ function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext: boolean): JsxElement | JsxSelfClosingElement | JsxFragment {
+ const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
+ let result: JsxElement | JsxSelfClosingElement | JsxFragment;
if (opening.kind === SyntaxKind.JsxOpeningElement) {
const node = createNode(SyntaxKind.JsxElement, opening.pos);
node.openingElement = opening;
- node.children = parseJsxChildren(node.openingElement.tagName);
+ node.children = parseJsxChildren(node.openingElement);
node.closingElement = parseJsxClosingElement(inExpressionContext);
if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
@@ -3975,6 +4003,14 @@ namespace ts {
result = finishNode(node);
}
+ else if (opening.kind === SyntaxKind.JsxOpeningFragment) {
+ const node = createNode(SyntaxKind.JsxFragment, opening.pos);
+ node.openingFragment = opening;
+ node.children = parseJsxChildren(node.openingFragment);
+ node.closingFragment = parseJsxClosingFragment(inExpressionContext);
+
+ result = finishNode(node);
+ }
else {
Debug.assert(opening.kind === SyntaxKind.JsxSelfClosingElement);
// Nothing else to do for self-closing elements
@@ -3989,7 +4025,7 @@ namespace ts {
// Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
// of one sort or another.
if (inExpressionContext && token() === SyntaxKind.LessThanToken) {
- const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true));
+ const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true));
if (invalidElement) {
parseErrorAtCurrentToken(Diagnostics.JSX_expressions_must_have_one_parent_element);
const badNode = createNode(SyntaxKind.BinaryExpression, result.pos);
@@ -4020,12 +4056,12 @@ namespace ts {
case SyntaxKind.OpenBraceToken:
return parseJsxExpression(/*inExpressionContext*/ false);
case SyntaxKind.LessThanToken:
- return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false);
+ return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
}
Debug.fail("Unknown JSX child kind " + token());
}
- function parseJsxChildren(openingTagName: LeftHandSideExpression): NodeArray {
+ function parseJsxChildren(openingTag: JsxOpeningElement | JsxOpeningFragment): NodeArray {
const list = [];
const listPos = getNodePos();
const saveParsingContext = parsingContext;
@@ -4040,7 +4076,13 @@ namespace ts {
else if (token() === SyntaxKind.EndOfFileToken) {
// If we hit EOF, issue the error at the tag that lacks the closing element
// rather than at the end of the file (which is useless)
- parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTagName));
+ if (isJsxOpeningFragment(openingTag)) {
+ parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
+ }
+ else {
+ const openingTagName = openingTag.tagName;
+ 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) {
@@ -4063,11 +4105,17 @@ namespace ts {
return finishNode(jsxAttributes);
}
- function parseJsxOpeningOrSelfClosingElement(inExpressionContext: boolean): JsxOpeningElement | JsxSelfClosingElement {
+ function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext: boolean): JsxOpeningElement | JsxSelfClosingElement | JsxOpeningFragment {
const fullStart = scanner.getStartPos();
parseExpected(SyntaxKind.LessThanToken);
+ if (token() === SyntaxKind.GreaterThanToken) {
+ parseExpected(SyntaxKind.GreaterThanToken);
+ const node: JsxOpeningFragment = createNode(SyntaxKind.JsxOpeningFragment, fullStart);
+ return finishNode(node);
+ }
+
const tagName = parseJsxElementName();
const attributes = parseJsxAttributes();
@@ -4179,6 +4227,23 @@ namespace ts {
return finishNode(node);
}
+ function parseJsxClosingFragment(inExpressionContext: boolean): JsxClosingFragment {
+ const node = createNode(SyntaxKind.JsxClosingFragment);
+ parseExpected(SyntaxKind.LessThanSlashToken);
+ if (tokenIsIdentifierOrKeyword(token())) {
+ const unexpectedTagName = parseJsxElementName();
+ parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
+ }
+ if (inExpressionContext) {
+ parseExpected(SyntaxKind.GreaterThanToken);
+ }
+ else {
+ parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
+ scanJsxText();
+ }
+ return finishNode(node);
+ }
+
function parseTypeAssertion(): TypeAssertion {
const node = createNode(SyntaxKind.TypeAssertionExpression);
parseExpected(SyntaxKind.LessThanToken);
@@ -5089,6 +5154,18 @@ namespace ts {
const fullStart = getNodePos();
const decorators = parseDecorators();
const modifiers = parseModifiers();
+ if (some(modifiers, m => m.kind === SyntaxKind.DeclareKeyword)) {
+ for (const m of modifiers) {
+ m.flags |= NodeFlags.Ambient;
+ }
+ return doInsideOfContext(NodeFlags.Ambient, () => parseDeclarationWorker(fullStart, decorators, modifiers));
+ }
+ else {
+ return parseDeclarationWorker(fullStart, decorators, modifiers);
+ }
+ }
+
+ function parseDeclarationWorker(fullStart: number, decorators: NodeArray | undefined, modifiers: NodeArray | undefined): Statement {
switch (token()) {
case SyntaxKind.VarKeyword:
case SyntaxKind.LetKeyword:
@@ -5446,8 +5523,8 @@ namespace ts {
return false;
}
- function parseDecorators(): NodeArray {
- let list: Decorator[];
+ function parseDecorators(): NodeArray | undefined {
+ let list: Decorator[] | undefined;
const listPos = getNodePos();
while (true) {
const decoratorStart = getNodePos();
@@ -6069,7 +6146,7 @@ namespace ts {
const checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment);
if (checkJsDirectiveMatchResult) {
checkJsDirective = {
- enabled: compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", /*ignoreCase*/ true) === Comparison.EqualTo,
+ enabled: equateStringsCaseInsensitive(checkJsDirectiveMatchResult[1], "@ts-check"),
end: range.end,
pos: range.pos
};
@@ -6131,7 +6208,7 @@ namespace ts {
export namespace JSDocParser {
export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number): { jsDocTypeExpression: JSDocTypeExpression, diagnostics: Diagnostic[] } | undefined {
initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS);
- sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS);
+ sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS, /*isDeclarationFile*/ false);
scanner.setText(content, start, length);
currentToken = scanner.scan();
const jsDocTypeExpression = parseJSDocTypeExpression();
@@ -7461,4 +7538,8 @@ namespace ts {
Value = -1
}
}
+
+ function isDeclarationFileName(fileName: string): boolean {
+ return fileExtensionIs(fileName, Extension.Dts);
+ }
}
diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts
index 8c24b3b9f1b..225b34de9cf 100644
--- a/src/compiler/performance.ts
+++ b/src/compiler/performance.ts
@@ -10,9 +10,7 @@ namespace ts {
namespace ts.performance {
declare const onProfilerEvent: { (markName: string): void; profiler: boolean; };
- const profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true
- ? onProfilerEvent
- : (_markName: string) => { };
+ const profilerEvent: (markName: string) => void = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : noop;
let enabled = false;
let profilerStart = 0;
diff --git a/src/compiler/program.ts b/src/compiler/program.ts
index 0ff78a77ecd..cf7c03556f1 100755
--- a/src/compiler/program.ts
+++ b/src/compiler/program.ts
@@ -7,18 +7,10 @@ namespace ts {
const ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string {
- while (true) {
- const fileName = combinePaths(searchPath, configName);
- if (fileExists(fileName)) {
- return fileName;
- }
- const parentPath = getDirectoryPath(searchPath);
- if (parentPath === searchPath) {
- break;
- }
- searchPath = parentPath;
- }
- return undefined;
+ return forEachAncestorDirectory(searchPath, ancestor => {
+ const fileName = combinePaths(ancestor, configName);
+ return fileExists(fileName) ? fileName : undefined;
+ });
}
export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
@@ -1101,11 +1093,12 @@ namespace ts {
// If '--lib' is not specified, include default library file according to '--target'
// otherwise, using options specified in '--lib' instead of '--target' default library file
+ const equalityComparer = host.useCaseSensitiveFileNames() ? equateStringsCaseSensitive : equateStringsCaseInsensitive;
if (!options.lib) {
- return compareStrings(file.fileName, getDefaultLibraryFileName(), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === Comparison.EqualTo;
+ return equalityComparer(file.fileName, getDefaultLibraryFileName());
}
else {
- return forEach(options.lib, libFileName => compareStrings(file.fileName, combinePaths(defaultLibraryPath, libFileName), /*ignoreCase*/ !host.useCaseSensitiveFileNames()) === Comparison.EqualTo);
+ return forEach(options.lib, libFileName => equalityComparer(file.fileName, combinePaths(defaultLibraryPath, libFileName)));
}
}
@@ -1186,11 +1179,11 @@ namespace ts {
return emitResult;
}
- function getSourceFile(fileName: string): SourceFile {
+ function getSourceFile(fileName: string): SourceFile | undefined {
return getSourceFileByPath(toPath(fileName));
}
- function getSourceFileByPath(path: Path): SourceFile {
+ function getSourceFileByPath(path: Path): SourceFile | undefined {
return filesByName.get(path);
}
@@ -2131,7 +2124,7 @@ namespace ts {
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
}
- if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) {
+ if (options.noImplicitUseStrict && getStrictOptionValue(options, "alwaysStrict")) {
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
}
@@ -2360,7 +2353,7 @@ namespace ts {
return options.jsx ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
}
function needAllowJs() {
- return options.allowJs || !options.noImplicitAny ? undefined : Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
+ return options.allowJs || !getStrictOptionValue(options, "noImplicitAny") ? undefined : Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
}
}
diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts
index b988da0fd5f..e21e81a2e88 100644
--- a/src/compiler/resolutionCache.ts
+++ b/src/compiler/resolutionCache.ts
@@ -69,9 +69,8 @@ namespace ts {
export const maxNumberOfFilesToIterateForInvalidation = 256;
- interface GetResolutionWithResolvedFileName {
- (resolution: T): R;
- }
+ type GetResolutionWithResolvedFileName =
+ (resolution: T) => R;
export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string): ResolutionCache {
let filesWithChangedSetOfUnresolvedImports: Path[] | undefined;
@@ -320,6 +319,10 @@ namespace ts {
return endsWith(dirPath, "/node_modules");
}
+ function isNodeModulesAtTypesDirectory(dirPath: Path) {
+ return endsWith(dirPath, "/node_modules/@types");
+ }
+
function isDirectoryAtleastAtLevelFromFSRoot(dirPath: Path, minLevels: number) {
for (let searchIndex = getRootLength(dirPath); minLevels > 0; minLevels--) {
searchIndex = dirPath.indexOf(directorySeparator, searchIndex) + 1;
@@ -560,11 +563,21 @@ namespace ts {
else {
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
- if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
- return false;
+ const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath);
+ if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) {
+ // Invalidate any resolution from this directory
+ isChangedFailedLookupLocation = location => {
+ const locationPath = resolutionHost.toPath(location);
+ return locationPath === fileOrDirectoryPath || startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
+ };
+ }
+ else {
+ if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
+ return false;
+ }
+ // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
+ isChangedFailedLookupLocation = location => resolutionHost.toPath(location) === fileOrDirectoryPath;
}
- // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
- isChangedFailedLookupLocation = location => resolutionHost.toPath(location) === fileOrDirectoryPath;
}
const hasChangedFailedLookupLocation = (resolution: ResolutionWithFailedLookupLocations) => some(resolution.failedLookupLocations, isChangedFailedLookupLocation);
const invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size;
diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts
index 6dab127ca33..fd8c54a18cc 100644
--- a/src/compiler/scanner.ts
+++ b/src/compiler/scanner.ts
@@ -2,15 +2,18 @@
///
namespace ts {
- export interface ErrorCallback {
- (message: DiagnosticMessage, length: number): void;
- }
+ export type ErrorCallback = (message: DiagnosticMessage, length: number) => void;
/* @internal */
export function tokenIsIdentifierOrKeyword(token: SyntaxKind): boolean {
return token >= SyntaxKind.Identifier;
}
+ /* @internal */
+ export function tokenIsIdentifierOrKeywordOrGreaterThan(token: SyntaxKind): boolean {
+ return token === SyntaxKind.GreaterThanToken || tokenIsIdentifierOrKeyword(token);
+ }
+
export interface Scanner {
getStartPos(): number;
getToken(): SyntaxKind;
@@ -352,7 +355,7 @@ namespace ts {
* We assume the first line starts at position 0 and 'position' is non-negative.
*/
export function computeLineAndCharacterOfPosition(lineStarts: ReadonlyArray, position: number): LineAndCharacter {
- let lineNumber = binarySearch(lineStarts, position);
+ let lineNumber = binarySearch(lineStarts, position, identity, compareValues);
if (lineNumber < 0) {
// If the actual position was not found,
// the binary search returns the 2's-complement of the next line start
diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts
index 1169af191b8..529ece36fa6 100644
--- a/src/compiler/sys.ts
+++ b/src/compiler/sys.ts
@@ -124,7 +124,7 @@ namespace ts {
getEnvironmentVariable?(name: string): string;
};
- export let sys: System = (function() {
+ export let sys: System = (() => {
function getNodeSystem(): System {
const _fs = require("fs");
const _path = require("path");
@@ -511,7 +511,7 @@ namespace ts {
return stat.size;
}
}
- catch (e) { }
+ catch { /*ignore*/ }
return 0;
},
exit(exitCode?: number): void {
@@ -525,7 +525,7 @@ namespace ts {
try {
require("source-map-support").install();
}
- catch (e) {
+ catch {
// Could not enable source maps.
}
},
@@ -594,7 +594,7 @@ namespace ts {
if (sys) {
// patch writefile to create folder before writing the file
const originalWriteFile = sys.writeFile;
- sys.writeFile = function(path, data, writeBom) {
+ sys.writeFile = (path, data, writeBom) => {
const directoryPath = getDirectoryPath(normalizeSlashes(path));
if (directoryPath && !sys.directoryExists(directoryPath)) {
recursiveCreateDirectory(directoryPath, sys);
diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts
index a1e52480172..989b0827570 100644
--- a/src/compiler/transformers/es2015.ts
+++ b/src/compiler/transformers/es2015.ts
@@ -787,9 +787,7 @@ namespace ts {
// To preserve the behavior of the old emitter, we explicitly indent
// the body of the function here if it was requested in an earlier
// transformation.
- if (getEmitFlags(node) & EmitFlags.Indented) {
- setEmitFlags(classFunction, EmitFlags.Indented);
- }
+ setEmitFlags(classFunction, (getEmitFlags(node) & EmitFlags.Indented) | EmitFlags.ReuseTempVariableScope);
// "inner" and "outer" below are added purely to preserve source map locations from
// the old emitter
@@ -1327,7 +1325,8 @@ namespace ts {
EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps
)
);
- statement.startsOnNewLine = true;
+
+ startOnNewLine(statement);
setTextRange(statement, parameter);
setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.CustomPrologue);
statements.push(statement);
@@ -1683,7 +1682,7 @@ namespace ts {
]
);
if (startsOnNewLine) {
- call.startsOnNewLine = true;
+ startOnNewLine(call);
}
exitSubtree(ancestorFacts, HierarchyFacts.PropagateNewTargetMask, hierarchyFacts & HierarchyFacts.PropagateNewTargetMask ? HierarchyFacts.NewTarget : HierarchyFacts.None);
@@ -2602,7 +2601,7 @@ namespace ts {
);
if (node.multiLine) {
- assignment.startsOnNewLine = true;
+ startOnNewLine(assignment);
}
expressions.push(assignment);
@@ -3083,7 +3082,7 @@ namespace ts {
);
setTextRange(expression, property);
if (startsOnNewLine) {
- expression.startsOnNewLine = true;
+ startOnNewLine(expression);
}
return expression;
}
@@ -3105,7 +3104,7 @@ namespace ts {
);
setTextRange(expression, property);
if (startsOnNewLine) {
- expression.startsOnNewLine = true;
+ startOnNewLine(expression);
}
return expression;
}
@@ -3128,7 +3127,7 @@ namespace ts {
);
setTextRange(expression, method);
if (startsOnNewLine) {
- expression.startsOnNewLine = true;
+ startOnNewLine(expression);
}
exitSubtree(ancestorFacts, HierarchyFacts.PropagateNewTargetMask, hierarchyFacts & HierarchyFacts.PropagateNewTargetMask ? HierarchyFacts.NewTarget : HierarchyFacts.None);
return expression;
diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts
index 7ede62b1540..bd2a4ef554d 100644
--- a/src/compiler/transformers/generators.ts
+++ b/src/compiler/transformers/generators.ts
@@ -1077,7 +1077,7 @@ namespace ts {
const visited = visitNode(expression, visitor, isExpression);
if (visited) {
if (multiLine) {
- visited.startsOnNewLine = true;
+ startOnNewLine(visited);
}
expressions.push(visited);
}
@@ -2683,8 +2683,7 @@ namespace ts {
if (clauses) {
const labelExpression = createPropertyAccess(state, "label");
const switchStatement = createSwitch(labelExpression, createCaseBlock(clauses));
- switchStatement.startsOnNewLine = true;
- return [switchStatement];
+ return [startOnNewLine(switchStatement)];
}
if (statements) {
diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts
index bbe05afe878..ab44db8ef4b 100644
--- a/src/compiler/transformers/jsx.ts
+++ b/src/compiler/transformers/jsx.ts
@@ -41,6 +41,9 @@ namespace ts {
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(node, /*isChild*/ false);
+ case SyntaxKind.JsxFragment:
+ return visitJsxFragment(node, /*isChild*/ false);
+
case SyntaxKind.JsxExpression:
return visitJsxExpression(node);
@@ -63,6 +66,9 @@ namespace ts {
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(node, /*isChild*/ true);
+ case SyntaxKind.JsxFragment:
+ return visitJsxFragment(node, /*isChild*/ true);
+
default:
Debug.failBadSyntaxKind(node);
return undefined;
@@ -77,6 +83,10 @@ namespace ts {
return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
}
+ function visitJsxFragment(node: JsxFragment, isChild: boolean) {
+ return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
+ }
+
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: ReadonlyArray, isChild: boolean, location: TextRange) {
const tagName = getTagName(node);
let objectProperties: Expression;
@@ -126,6 +136,22 @@ namespace ts {
return element;
}
+ function visitJsxOpeningFragment(node: JsxOpeningFragment, children: ReadonlyArray, isChild: boolean, location: TextRange) {
+ const element = createExpressionForJsxFragment(
+ context.getEmitResolver().getJsxFactoryEntity(),
+ compilerOptions.reactNamespace,
+ mapDefined(children, transformJsxChildToExpression),
+ node,
+ location
+ );
+
+ if (isChild) {
+ startOnNewLine(element);
+ }
+
+ return element;
+ }
+
function transformJsxSpreadAttributeToExpression(node: JsxSpreadAttribute) {
return visitNode(node.expression, visitor, isExpression);
}
@@ -283,258 +309,258 @@ namespace ts {
}
const entities = createMapFromTemplate({
- "quot": 0x0022,
- "amp": 0x0026,
- "apos": 0x0027,
- "lt": 0x003C,
- "gt": 0x003E,
- "nbsp": 0x00A0,
- "iexcl": 0x00A1,
- "cent": 0x00A2,
- "pound": 0x00A3,
- "curren": 0x00A4,
- "yen": 0x00A5,
- "brvbar": 0x00A6,
- "sect": 0x00A7,
- "uml": 0x00A8,
- "copy": 0x00A9,
- "ordf": 0x00AA,
- "laquo": 0x00AB,
- "not": 0x00AC,
- "shy": 0x00AD,
- "reg": 0x00AE,
- "macr": 0x00AF,
- "deg": 0x00B0,
- "plusmn": 0x00B1,
- "sup2": 0x00B2,
- "sup3": 0x00B3,
- "acute": 0x00B4,
- "micro": 0x00B5,
- "para": 0x00B6,
- "middot": 0x00B7,
- "cedil": 0x00B8,
- "sup1": 0x00B9,
- "ordm": 0x00BA,
- "raquo": 0x00BB,
- "frac14": 0x00BC,
- "frac12": 0x00BD,
- "frac34": 0x00BE,
- "iquest": 0x00BF,
- "Agrave": 0x00C0,
- "Aacute": 0x00C1,
- "Acirc": 0x00C2,
- "Atilde": 0x00C3,
- "Auml": 0x00C4,
- "Aring": 0x00C5,
- "AElig": 0x00C6,
- "Ccedil": 0x00C7,
- "Egrave": 0x00C8,
- "Eacute": 0x00C9,
- "Ecirc": 0x00CA,
- "Euml": 0x00CB,
- "Igrave": 0x00CC,
- "Iacute": 0x00CD,
- "Icirc": 0x00CE,
- "Iuml": 0x00CF,
- "ETH": 0x00D0,
- "Ntilde": 0x00D1,
- "Ograve": 0x00D2,
- "Oacute": 0x00D3,
- "Ocirc": 0x00D4,
- "Otilde": 0x00D5,
- "Ouml": 0x00D6,
- "times": 0x00D7,
- "Oslash": 0x00D8,
- "Ugrave": 0x00D9,
- "Uacute": 0x00DA,
- "Ucirc": 0x00DB,
- "Uuml": 0x00DC,
- "Yacute": 0x00DD,
- "THORN": 0x00DE,
- "szlig": 0x00DF,
- "agrave": 0x00E0,
- "aacute": 0x00E1,
- "acirc": 0x00E2,
- "atilde": 0x00E3,
- "auml": 0x00E4,
- "aring": 0x00E5,
- "aelig": 0x00E6,
- "ccedil": 0x00E7,
- "egrave": 0x00E8,
- "eacute": 0x00E9,
- "ecirc": 0x00EA,
- "euml": 0x00EB,
- "igrave": 0x00EC,
- "iacute": 0x00ED,
- "icirc": 0x00EE,
- "iuml": 0x00EF,
- "eth": 0x00F0,
- "ntilde": 0x00F1,
- "ograve": 0x00F2,
- "oacute": 0x00F3,
- "ocirc": 0x00F4,
- "otilde": 0x00F5,
- "ouml": 0x00F6,
- "divide": 0x00F7,
- "oslash": 0x00F8,
- "ugrave": 0x00F9,
- "uacute": 0x00FA,
- "ucirc": 0x00FB,
- "uuml": 0x00FC,
- "yacute": 0x00FD,
- "thorn": 0x00FE,
- "yuml": 0x00FF,
- "OElig": 0x0152,
- "oelig": 0x0153,
- "Scaron": 0x0160,
- "scaron": 0x0161,
- "Yuml": 0x0178,
- "fnof": 0x0192,
- "circ": 0x02C6,
- "tilde": 0x02DC,
- "Alpha": 0x0391,
- "Beta": 0x0392,
- "Gamma": 0x0393,
- "Delta": 0x0394,
- "Epsilon": 0x0395,
- "Zeta": 0x0396,
- "Eta": 0x0397,
- "Theta": 0x0398,
- "Iota": 0x0399,
- "Kappa": 0x039A,
- "Lambda": 0x039B,
- "Mu": 0x039C,
- "Nu": 0x039D,
- "Xi": 0x039E,
- "Omicron": 0x039F,
- "Pi": 0x03A0,
- "Rho": 0x03A1,
- "Sigma": 0x03A3,
- "Tau": 0x03A4,
- "Upsilon": 0x03A5,
- "Phi": 0x03A6,
- "Chi": 0x03A7,
- "Psi": 0x03A8,
- "Omega": 0x03A9,
- "alpha": 0x03B1,
- "beta": 0x03B2,
- "gamma": 0x03B3,
- "delta": 0x03B4,
- "epsilon": 0x03B5,
- "zeta": 0x03B6,
- "eta": 0x03B7,
- "theta": 0x03B8,
- "iota": 0x03B9,
- "kappa": 0x03BA,
- "lambda": 0x03BB,
- "mu": 0x03BC,
- "nu": 0x03BD,
- "xi": 0x03BE,
- "omicron": 0x03BF,
- "pi": 0x03C0,
- "rho": 0x03C1,
- "sigmaf": 0x03C2,
- "sigma": 0x03C3,
- "tau": 0x03C4,
- "upsilon": 0x03C5,
- "phi": 0x03C6,
- "chi": 0x03C7,
- "psi": 0x03C8,
- "omega": 0x03C9,
- "thetasym": 0x03D1,
- "upsih": 0x03D2,
- "piv": 0x03D6,
- "ensp": 0x2002,
- "emsp": 0x2003,
- "thinsp": 0x2009,
- "zwnj": 0x200C,
- "zwj": 0x200D,
- "lrm": 0x200E,
- "rlm": 0x200F,
- "ndash": 0x2013,
- "mdash": 0x2014,
- "lsquo": 0x2018,
- "rsquo": 0x2019,
- "sbquo": 0x201A,
- "ldquo": 0x201C,
- "rdquo": 0x201D,
- "bdquo": 0x201E,
- "dagger": 0x2020,
- "Dagger": 0x2021,
- "bull": 0x2022,
- "hellip": 0x2026,
- "permil": 0x2030,
- "prime": 0x2032,
- "Prime": 0x2033,
- "lsaquo": 0x2039,
- "rsaquo": 0x203A,
- "oline": 0x203E,
- "frasl": 0x2044,
- "euro": 0x20AC,
- "image": 0x2111,
- "weierp": 0x2118,
- "real": 0x211C,
- "trade": 0x2122,
- "alefsym": 0x2135,
- "larr": 0x2190,
- "uarr": 0x2191,
- "rarr": 0x2192,
- "darr": 0x2193,
- "harr": 0x2194,
- "crarr": 0x21B5,
- "lArr": 0x21D0,
- "uArr": 0x21D1,
- "rArr": 0x21D2,
- "dArr": 0x21D3,
- "hArr": 0x21D4,
- "forall": 0x2200,
- "part": 0x2202,
- "exist": 0x2203,
- "empty": 0x2205,
- "nabla": 0x2207,
- "isin": 0x2208,
- "notin": 0x2209,
- "ni": 0x220B,
- "prod": 0x220F,
- "sum": 0x2211,
- "minus": 0x2212,
- "lowast": 0x2217,
- "radic": 0x221A,
- "prop": 0x221D,
- "infin": 0x221E,
- "ang": 0x2220,
- "and": 0x2227,
- "or": 0x2228,
- "cap": 0x2229,
- "cup": 0x222A,
- "int": 0x222B,
- "there4": 0x2234,
- "sim": 0x223C,
- "cong": 0x2245,
- "asymp": 0x2248,
- "ne": 0x2260,
- "equiv": 0x2261,
- "le": 0x2264,
- "ge": 0x2265,
- "sub": 0x2282,
- "sup": 0x2283,
- "nsub": 0x2284,
- "sube": 0x2286,
- "supe": 0x2287,
- "oplus": 0x2295,
- "otimes": 0x2297,
- "perp": 0x22A5,
- "sdot": 0x22C5,
- "lceil": 0x2308,
- "rceil": 0x2309,
- "lfloor": 0x230A,
- "rfloor": 0x230B,
- "lang": 0x2329,
- "rang": 0x232A,
- "loz": 0x25CA,
- "spades": 0x2660,
- "clubs": 0x2663,
- "hearts": 0x2665,
- "diams": 0x2666
+ quot: 0x0022,
+ amp: 0x0026,
+ apos: 0x0027,
+ lt: 0x003C,
+ gt: 0x003E,
+ nbsp: 0x00A0,
+ iexcl: 0x00A1,
+ cent: 0x00A2,
+ pound: 0x00A3,
+ curren: 0x00A4,
+ yen: 0x00A5,
+ brvbar: 0x00A6,
+ sect: 0x00A7,
+ uml: 0x00A8,
+ copy: 0x00A9,
+ ordf: 0x00AA,
+ laquo: 0x00AB,
+ not: 0x00AC,
+ shy: 0x00AD,
+ reg: 0x00AE,
+ macr: 0x00AF,
+ deg: 0x00B0,
+ plusmn: 0x00B1,
+ sup2: 0x00B2,
+ sup3: 0x00B3,
+ acute: 0x00B4,
+ micro: 0x00B5,
+ para: 0x00B6,
+ middot: 0x00B7,
+ cedil: 0x00B8,
+ sup1: 0x00B9,
+ ordm: 0x00BA,
+ raquo: 0x00BB,
+ frac14: 0x00BC,
+ frac12: 0x00BD,
+ frac34: 0x00BE,
+ iquest: 0x00BF,
+ Agrave: 0x00C0,
+ Aacute: 0x00C1,
+ Acirc: 0x00C2,
+ Atilde: 0x00C3,
+ Auml: 0x00C4,
+ Aring: 0x00C5,
+ AElig: 0x00C6,
+ Ccedil: 0x00C7,
+ Egrave: 0x00C8,
+ Eacute: 0x00C9,
+ Ecirc: 0x00CA,
+ Euml: 0x00CB,
+ Igrave: 0x00CC,
+ Iacute: 0x00CD,
+ Icirc: 0x00CE,
+ Iuml: 0x00CF,
+ ETH: 0x00D0,
+ Ntilde: 0x00D1,
+ Ograve: 0x00D2,
+ Oacute: 0x00D3,
+ Ocirc: 0x00D4,
+ Otilde: 0x00D5,
+ Ouml: 0x00D6,
+ times: 0x00D7,
+ Oslash: 0x00D8,
+ Ugrave: 0x00D9,
+ Uacute: 0x00DA,
+ Ucirc: 0x00DB,
+ Uuml: 0x00DC,
+ Yacute: 0x00DD,
+ THORN: 0x00DE,
+ szlig: 0x00DF,
+ agrave: 0x00E0,
+ aacute: 0x00E1,
+ acirc: 0x00E2,
+ atilde: 0x00E3,
+ auml: 0x00E4,
+ aring: 0x00E5,
+ aelig: 0x00E6,
+ ccedil: 0x00E7,
+ egrave: 0x00E8,
+ eacute: 0x00E9,
+ ecirc: 0x00EA,
+ euml: 0x00EB,
+ igrave: 0x00EC,
+ iacute: 0x00ED,
+ icirc: 0x00EE,
+ iuml: 0x00EF,
+ eth: 0x00F0,
+ ntilde: 0x00F1,
+ ograve: 0x00F2,
+ oacute: 0x00F3,
+ ocirc: 0x00F4,
+ otilde: 0x00F5,
+ ouml: 0x00F6,
+ divide: 0x00F7,
+ oslash: 0x00F8,
+ ugrave: 0x00F9,
+ uacute: 0x00FA,
+ ucirc: 0x00FB,
+ uuml: 0x00FC,
+ yacute: 0x00FD,
+ thorn: 0x00FE,
+ yuml: 0x00FF,
+ OElig: 0x0152,
+ oelig: 0x0153,
+ Scaron: 0x0160,
+ scaron: 0x0161,
+ Yuml: 0x0178,
+ fnof: 0x0192,
+ circ: 0x02C6,
+ tilde: 0x02DC,
+ Alpha: 0x0391,
+ Beta: 0x0392,
+ Gamma: 0x0393,
+ Delta: 0x0394,
+ Epsilon: 0x0395,
+ Zeta: 0x0396,
+ Eta: 0x0397,
+ Theta: 0x0398,
+ Iota: 0x0399,
+ Kappa: 0x039A,
+ Lambda: 0x039B,
+ Mu: 0x039C,
+ Nu: 0x039D,
+ Xi: 0x039E,
+ Omicron: 0x039F,
+ Pi: 0x03A0,
+ Rho: 0x03A1,
+ Sigma: 0x03A3,
+ Tau: 0x03A4,
+ Upsilon: 0x03A5,
+ Phi: 0x03A6,
+ Chi: 0x03A7,
+ Psi: 0x03A8,
+ Omega: 0x03A9,
+ alpha: 0x03B1,
+ beta: 0x03B2,
+ gamma: 0x03B3,
+ delta: 0x03B4,
+ epsilon: 0x03B5,
+ zeta: 0x03B6,
+ eta: 0x03B7,
+ theta: 0x03B8,
+ iota: 0x03B9,
+ kappa: 0x03BA,
+ lambda: 0x03BB,
+ mu: 0x03BC,
+ nu: 0x03BD,
+ xi: 0x03BE,
+ omicron: 0x03BF,
+ pi: 0x03C0,
+ rho: 0x03C1,
+ sigmaf: 0x03C2,
+ sigma: 0x03C3,
+ tau: 0x03C4,
+ upsilon: 0x03C5,
+ phi: 0x03C6,
+ chi: 0x03C7,
+ psi: 0x03C8,
+ omega: 0x03C9,
+ thetasym: 0x03D1,
+ upsih: 0x03D2,
+ piv: 0x03D6,
+ ensp: 0x2002,
+ emsp: 0x2003,
+ thinsp: 0x2009,
+ zwnj: 0x200C,
+ zwj: 0x200D,
+ lrm: 0x200E,
+ rlm: 0x200F,
+ ndash: 0x2013,
+ mdash: 0x2014,
+ lsquo: 0x2018,
+ rsquo: 0x2019,
+ sbquo: 0x201A,
+ ldquo: 0x201C,
+ rdquo: 0x201D,
+ bdquo: 0x201E,
+ dagger: 0x2020,
+ Dagger: 0x2021,
+ bull: 0x2022,
+ hellip: 0x2026,
+ permil: 0x2030,
+ prime: 0x2032,
+ Prime: 0x2033,
+ lsaquo: 0x2039,
+ rsaquo: 0x203A,
+ oline: 0x203E,
+ frasl: 0x2044,
+ euro: 0x20AC,
+ image: 0x2111,
+ weierp: 0x2118,
+ real: 0x211C,
+ trade: 0x2122,
+ alefsym: 0x2135,
+ larr: 0x2190,
+ uarr: 0x2191,
+ rarr: 0x2192,
+ darr: 0x2193,
+ harr: 0x2194,
+ crarr: 0x21B5,
+ lArr: 0x21D0,
+ uArr: 0x21D1,
+ rArr: 0x21D2,
+ dArr: 0x21D3,
+ hArr: 0x21D4,
+ forall: 0x2200,
+ part: 0x2202,
+ exist: 0x2203,
+ empty: 0x2205,
+ nabla: 0x2207,
+ isin: 0x2208,
+ notin: 0x2209,
+ ni: 0x220B,
+ prod: 0x220F,
+ sum: 0x2211,
+ minus: 0x2212,
+ lowast: 0x2217,
+ radic: 0x221A,
+ prop: 0x221D,
+ infin: 0x221E,
+ ang: 0x2220,
+ and: 0x2227,
+ or: 0x2228,
+ cap: 0x2229,
+ cup: 0x222A,
+ int: 0x222B,
+ there4: 0x2234,
+ sim: 0x223C,
+ cong: 0x2245,
+ asymp: 0x2248,
+ ne: 0x2260,
+ equiv: 0x2261,
+ le: 0x2264,
+ ge: 0x2265,
+ sub: 0x2282,
+ sup: 0x2283,
+ nsub: 0x2284,
+ sube: 0x2286,
+ supe: 0x2287,
+ oplus: 0x2295,
+ otimes: 0x2297,
+ perp: 0x22A5,
+ sdot: 0x22C5,
+ lceil: 0x2308,
+ rceil: 0x2309,
+ lfloor: 0x230A,
+ rfloor: 0x230B,
+ lang: 0x2329,
+ rang: 0x232A,
+ loz: 0x25CA,
+ spades: 0x2660,
+ clubs: 0x2663,
+ hearts: 0x2665,
+ diams: 0x2666
});
}
\ No newline at end of file
diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts
index bd360fdffe4..f60e50ea365 100644
--- a/src/compiler/transformers/module/module.ts
+++ b/src/compiler/transformers/module/module.ts
@@ -91,7 +91,7 @@ namespace ts {
startLexicalEnvironment();
const statements: Statement[] = [];
- const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
+ const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
if (shouldEmitUnderscoreUnderscoreESModule()) {
diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts
index d674546efb9..e5d638cf04d 100644
--- a/src/compiler/transformers/module/system.ts
+++ b/src/compiler/transformers/module/system.ts
@@ -146,8 +146,7 @@ namespace ts {
function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) {
const groupIndices = createMap();
const dependencyGroups: DependencyGroup[] = [];
- for (let i = 0; i < externalImports.length; i++) {
- const externalImport = externalImports[i];
+ for (const externalImport of externalImports) {
const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
if (externalModuleName) {
const text = externalModuleName.text;
@@ -225,7 +224,7 @@ namespace ts {
startLexicalEnvironment();
// Add any prologue directives.
- const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
+ const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
// var __moduleName = context_1 && context_1.id;
diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts
index ba4b5fcdf52..39a4cc83bda 100644
--- a/src/compiler/transformers/ts.ts
+++ b/src/compiler/transformers/ts.ts
@@ -45,7 +45,7 @@ namespace ts {
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
- const strictNullChecks = typeof compilerOptions.strictNullChecks === "undefined" ? compilerOptions.strict : compilerOptions.strictNullChecks;
+ const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
@@ -86,6 +86,12 @@ namespace ts {
*/
let applicableSubstitutions: TypeScriptSubstitutionFlags;
+ /**
+ * Tracks what computed name expressions originating from elided names must be inlined
+ * at the next execution site, in document order
+ */
+ let pendingExpressions: Expression[] | undefined;
+
return transformSourceFile;
/**
@@ -225,6 +231,13 @@ namespace ts {
if (parsed !== node) {
// If the node has been transformed by a `before` transformer, perform no ellision on it
// As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
+ // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
+ // and will trigger debug failures when debug verbosity is turned up
+ if (node.transformFlags & TransformFlags.ContainsTypeScript) {
+ // This node contains TypeScript, so we should visit its children.
+ return visitEachChild(node, visitor, context);
+ }
+ // Otherwise, we can just return the node
return node;
}
switch (node.kind) {
@@ -388,9 +401,11 @@ namespace ts {
case SyntaxKind.TypeAliasDeclaration:
// TypeScript type-only declarations are elided.
+ return undefined;
case SyntaxKind.PropertyDeclaration:
- // TypeScript property declarations are elided.
+ // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
+ return visitPropertyDeclaration(node as PropertyDeclaration);
case SyntaxKind.NamespaceExportDeclaration:
// TypeScript namespace export declarations are elided.
@@ -521,7 +536,7 @@ namespace ts {
}
function visitSourceFile(node: SourceFile) {
- const alwaysStrict = (compilerOptions.alwaysStrict === undefined ? compilerOptions.strict : compilerOptions.alwaysStrict) &&
+ const alwaysStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") &&
!(isExternalModule(node) && moduleKind >= ModuleKind.ES2015);
return updateSourceFileNode(
node,
@@ -577,6 +592,9 @@ namespace ts {
* @param node The node to transform.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult {
+ const savedPendingExpressions = pendingExpressions;
+ pendingExpressions = undefined;
+
const staticProperties = getInitializedProperties(node, /*isStatic*/ true);
const facts = getClassFacts(node, staticProperties);
@@ -591,6 +609,12 @@ namespace ts {
let statements: Statement[] = [classStatement];
+ // Write any pending expressions from elided or moved computed property names
+ if (some(pendingExpressions)) {
+ statements.push(createStatement(inlineExpressions(pendingExpressions)));
+ }
+ pendingExpressions = savedPendingExpressions;
+
// Emit static property assignment. Because classDeclaration is lexically evaluated,
// it is safe to emit static property assignment after classDeclaration
// From ES6 specification:
@@ -849,6 +873,9 @@ namespace ts {
* @param node The node to transform.
*/
function visitClassExpression(node: ClassExpression): Expression {
+ const savedPendingExpressions = pendingExpressions;
+ pendingExpressions = undefined;
+
const staticProperties = getInitializedProperties(node, /*isStatic*/ true);
const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause);
const members = transformClassMembers(node, some(heritageClauses, c => c.token === SyntaxKind.ExtendsKeyword));
@@ -864,7 +891,7 @@ namespace ts {
setOriginalNode(classExpression, node);
setTextRange(classExpression, node);
- if (staticProperties.length > 0) {
+ if (some(staticProperties) || some(pendingExpressions)) {
const expressions: Expression[] = [];
const temp = createTempVariable(hoistVariableDeclaration);
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference) {
@@ -877,11 +904,15 @@ namespace ts {
// the body of a class with static initializers.
setEmitFlags(classExpression, EmitFlags.Indented | getEmitFlags(classExpression));
expressions.push(startOnNewLine(createAssignment(temp, classExpression)));
+ // Add any pending expressions leftover from elided or relocated computed property names
+ addRange(expressions, map(pendingExpressions, startOnNewLine));
+ pendingExpressions = savedPendingExpressions;
addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
expressions.push(startOnNewLine(temp));
return inlineExpressions(expressions);
}
+ pendingExpressions = savedPendingExpressions;
return classExpression;
}
@@ -1195,7 +1226,7 @@ namespace ts {
const expressions: Expression[] = [];
for (const property of properties) {
const expression = transformInitializedProperty(property, receiver);
- expression.startsOnNewLine = true;
+ startOnNewLine(expression);
setSourceMapRange(expression, moveRangePastModifiers(property));
setCommentRange(expression, property);
expressions.push(expression);
@@ -1211,7 +1242,10 @@ namespace ts {
* @param receiver The object receiving the property assignment.
*/
function transformInitializedProperty(property: PropertyDeclaration, receiver: LeftHandSideExpression) {
- const propertyName = visitPropertyNameOfClassElement(property);
+ // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
+ const propertyName = isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
+ ? updateComputedPropertyName(property.name, getGeneratedNameForNode(property.name, !hasModifier(property, ModifierFlags.Static)))
+ : property.name;
const initializer = visitNode(property.initializer, visitor, isExpression);
const memberAccess = createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
@@ -2034,6 +2068,16 @@ namespace ts {
);
}
+ /**
+ * A simple inlinable expression is an expression which can be copied into multiple locations
+ * without risk of repeating any sideeffects and whose value could not possibly change between
+ * any such locations
+ */
+ function isSimpleInlineableExpression(expression: Expression) {
+ return !isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
+ isWellKnownSymbolSyntactically(expression);
+ }
+
/**
* Gets an expression that represents a property name. For a computed property, a
* name is generated for the node.
@@ -2043,7 +2087,7 @@ namespace ts {
function getExpressionForPropertyName(member: ClassElement | EnumMember, generateNameForComputedPropertyName: boolean): Expression {
const name = member.name;
if (isComputedPropertyName(name)) {
- return generateNameForComputedPropertyName
+ return generateNameForComputedPropertyName && !isSimpleInlineableExpression((name).expression)
? getGeneratedNameForNode(name)
: (name).expression;
}
@@ -2055,6 +2099,26 @@ namespace ts {
}
}
+ /**
+ * If the name is a computed property, this function transforms it, then either returns an expression which caches the
+ * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
+ * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
+ * @param omitSimple Should expressions with no observable side-effects be elided? (ie, the expression is not hoisted for a decorator or initializer and is a literal)
+ */
+ function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean, omitSimple: boolean): Expression {
+ if (isComputedPropertyName(name)) {
+ const expression = visitNode(name.expression, visitor, isExpression);
+ const innerExpression = skipPartiallyEmittedExpressions(expression);
+ const inlinable = isSimpleInlineableExpression(innerExpression);
+ if (!inlinable && shouldHoist) {
+ const generatedName = getGeneratedNameForNode(name);
+ hoistVariableDeclaration(generatedName);
+ return createAssignment(generatedName, expression);
+ }
+ return (omitSimple && (inlinable || isIdentifier(innerExpression))) ? undefined : expression;
+ }
+ }
+
/**
* Visits the property name of a class element, for use when emitting property
* initializers. For a computed property on a node with decorators, a temporary
@@ -2064,15 +2128,14 @@ namespace ts {
*/
function visitPropertyNameOfClassElement(member: ClassElement): PropertyName {
const name = member.name;
- if (isComputedPropertyName(name)) {
- let expression = visitNode(name.expression, visitor, isExpression);
- if (member.decorators) {
- const generatedName = getGeneratedNameForNode(name);
- hoistVariableDeclaration(generatedName);
- expression = createAssignment(generatedName, expression);
+ let expr = getPropertyNameExpressionIfNeeded(name, some(member.decorators), /*omitSimple*/ false);
+ if (expr) { // expr only exists if `name` is a computed property name
+ // Inline any pending expressions from previous elided or relocated computed property name expressions in order to preserve execution order
+ if (some(pendingExpressions)) {
+ expr = inlineExpressions([...pendingExpressions, expr]);
+ pendingExpressions.length = 0;
}
-
- return updateComputedPropertyName(name, expression);
+ return updateComputedPropertyName(name as ComputedPropertyName, expr);
}
else {
return name;
@@ -2129,6 +2192,14 @@ namespace ts {
return !nodeIsMissing(node.body);
}
+ function visitPropertyDeclaration(node: PropertyDeclaration): undefined {
+ const expr = getPropertyNameExpressionIfNeeded(node.name, some(node.decorators) || !!node.initializer, /*omitSimple*/ true);
+ if (expr && !isSimpleInlineableExpression(expr)) {
+ (pendingExpressions || (pendingExpressions = [])).push(expr);
+ }
+ return undefined;
+ }
+
function visitConstructor(node: ConstructorDeclaration) {
if (!shouldEmitFunctionLikeDeclaration(node)) {
return undefined;
@@ -2149,7 +2220,7 @@ namespace ts {
* This function will be called when one of the following conditions are met:
* - The node is an overload
* - The node is marked as abstract, public, private, protected, or readonly
- * - The node has both a decorator and a computed property name
+ * - The node has a computed property name
*
* @param node The method node.
*/
@@ -2193,7 +2264,7 @@ namespace ts {
*
* This function will be called when one of the following conditions are met:
* - The node is marked as abstract, public, private, or protected
- * - The node has both a decorator and a computed property name
+ * - The node has a computed property name
*
* @param node The get accessor node.
*/
@@ -2224,7 +2295,7 @@ namespace ts {
*
* This function will be called when one of the following conditions are met:
* - The node is marked as abstract, public, private, or protected
- * - The node has both a decorator and a computed property name
+ * - The node has a computed property name
*
* @param node The set accessor node.
*/
diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts
index 680daeeb485..01fb45e4f7d 100644
--- a/src/compiler/tsc.ts
+++ b/src/compiler/tsc.ts
@@ -43,20 +43,12 @@ namespace ts {
return s;
}
- function isJSONSupported() {
- return typeof JSON === "object" && typeof JSON.parse === "function";
- }
-
export function executeCommandLine(args: string[]): void {
const commandLine = parseCommandLine(args);
// Configuration file name (if any)
let configFileName: string;
if (commandLine.options.locale) {
- if (!isJSONSupported()) {
- reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"));
- return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
- }
validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors);
}
@@ -84,10 +76,6 @@ namespace ts {
}
if (commandLine.options.project) {
- if (!isJSONSupported()) {
- reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--project"));
- return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
- }
if (commandLine.fileNames.length !== 0) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line));
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -109,7 +97,7 @@ namespace ts {
}
}
}
- else if (commandLine.fileNames.length === 0 && isJSONSupported()) {
+ else if (commandLine.fileNames.length === 0) {
const searchPath = normalizePath(sys.getCurrentDirectory());
configFileName = findConfigFile(searchPath, sys.fileExists);
}
@@ -306,7 +294,7 @@ namespace ts {
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
const optsList = showAllOptions ?
- optionDeclarations.slice().sort((a, b) => compareValues(a.name.toLowerCase(), b.name.toLowerCase())) :
+ sort(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) :
filter(optionDeclarations.slice(), v => v.showInSimplifiedHelpView);
// We want our descriptions to align at the same column in our output,
@@ -317,9 +305,7 @@ namespace ts {
const optionsDescriptionMap = createMap(); // Map between option.description and list of option.type if it is a kind
- for (let i = 0; i < optsList.length; i++) {
- const option = optsList[i];
-
+ for (const option of optsList) {
// If an option lacks a description,
// it is not officially supported.
if (!option.description) {
diff --git a/src/compiler/types.ts b/src/compiler/types.ts
index ff2a33266ed..d2107572ab4 100644
--- a/src/compiler/types.ts
+++ b/src/compiler/types.ts
@@ -36,6 +36,19 @@ namespace ts {
push(...values: T[]): void;
}
+ /* @internal */
+ export type EqualityComparer = (a: T, b: T) => boolean;
+
+ /* @internal */
+ export type Comparer = (a: T, b: T) => Comparison;
+
+ /* @internal */
+ export const enum Comparison {
+ LessThan = -1,
+ EqualTo = 0,
+ GreaterThan = 1
+ }
+
// branded string type used to store absolute, normalized and canonicalized paths
// arbitrary file name can be converted to Path via toPath function
export type Path = string & { __pathBrand: any };
@@ -328,6 +341,9 @@ namespace ts {
JsxSelfClosingElement,
JsxOpeningElement,
JsxClosingElement,
+ JsxFragment,
+ JsxOpeningFragment,
+ JsxClosingFragment,
JsxAttribute,
JsxAttributes,
JsxSpreadAttribute,
@@ -362,6 +378,7 @@ namespace ts {
JSDocFunctionType,
JSDocVariadicType,
JSDocComment,
+ JSDocTypeLiteral,
JSDocTag,
JSDocAugmentsTag,
JSDocClassTag,
@@ -371,7 +388,6 @@ namespace ts {
JSDocTemplateTag,
JSDocTypedefTag,
JSDocPropertyTag,
- JSDocTypeLiteral,
// Synthesized list
SyntaxList,
@@ -413,9 +429,9 @@ namespace ts {
LastBinaryOperator = CaretEqualsToken,
FirstNode = QualifiedName,
FirstJSDocNode = JSDocTypeExpression,
- LastJSDocNode = JSDocTypeLiteral,
+ LastJSDocNode = JSDocPropertyTag,
FirstJSDocTagNode = JSDocTag,
- LastJSDocTagNode = JSDocTypeLiteral
+ LastJSDocTagNode = JSDocPropertyTag
}
export const enum NodeFlags {
@@ -451,7 +467,8 @@ namespace ts {
/* @internal */
PossiblyContainsDynamicImport = 1 << 19,
JSDoc = 1 << 20, // If node was parsed inside jsdoc
- /* @internal */ InWithStatement = 1 << 21, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`)
+ /* @internal */ Ambient = 1 << 21, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier.
+ /* @internal */ InWithStatement = 1 << 22, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`)
BlockScoped = Let | Const,
@@ -459,7 +476,7 @@ namespace ts {
ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions,
// Parsing context flags
- ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile | InWithStatement,
+ ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile | InWithStatement | Ambient,
// Exclude these flags when parsing a Type
TypeExcludesFlags = YieldContext | AwaitContext,
@@ -516,7 +533,6 @@ namespace ts {
/* @internal */ id?: number; // Unique id (used to look up NodeLinks)
parent?: Node; // Parent node (initialized by binding)
/* @internal */ original?: Node; // The original node if this is an updated node.
- /* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms).
/* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding)
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
@@ -626,6 +642,7 @@ namespace ts {
isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace
/*@internal*/ typeArguments?: NodeArray; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics.
/*@internal*/ jsdocDotPos?: number; // Identifier occurs in JSDoc-style generic: Id.
+ /*@internal*/ skipNameGenerationScope?: boolean; // Should skip a name generation scope when generating the name for this identifier
}
// Transient identifier node (marked by id === -1)
@@ -1620,7 +1637,7 @@ namespace ts {
closingElement: JsxClosingElement;
}
- /// Either the opening tag in a ... pair, or the lone in a self-closing form
+ /// Either the opening tag in a ... pair or the lone in a self-closing form
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
export type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute;
@@ -1646,6 +1663,26 @@ namespace ts {
attributes: JsxAttributes;
}
+ /// A JSX expression of the form <>...>
+ export interface JsxFragment extends PrimaryExpression {
+ kind: SyntaxKind.JsxFragment;
+ openingFragment: JsxOpeningFragment;
+ children: NodeArray;
+ closingFragment: JsxClosingFragment;
+ }
+
+ /// The opening element of a <>...> JsxFragment
+ export interface JsxOpeningFragment extends Expression {
+ kind: SyntaxKind.JsxOpeningFragment;
+ parent?: JsxFragment;
+ }
+
+ /// The closing element of a <>...> JsxFragment
+ export interface JsxClosingFragment extends Expression {
+ kind: SyntaxKind.JsxClosingFragment;
+ parent?: JsxFragment;
+ }
+
export interface JsxAttribute extends ObjectLiteralElement {
kind: SyntaxKind.JsxAttribute;
parent?: JsxAttributes;
@@ -1679,7 +1716,7 @@ namespace ts {
parent?: JsxElement;
}
- export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement;
+ export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment;
export interface Statement extends Node {
_statementBrand: any;
@@ -2429,8 +2466,8 @@ namespace ts {
export interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
- getSourceFile(fileName: string): SourceFile;
- getSourceFileByPath(path: Path): SourceFile;
+ getSourceFile(fileName: string): SourceFile | undefined;
+ getSourceFileByPath(path: Path): SourceFile | undefined;
getCurrentDirectory(): string;
}
@@ -2448,9 +2485,13 @@ namespace ts {
readFile(path: string): string | undefined;
}
- export interface WriteFileCallback {
- (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray