merge branch 'transforms-fixMoreSourceMaps' into transforms-transformer-es6-generators

This commit is contained in:
Ron Buckton
2016-05-17 22:09:15 -07:00
3735 changed files with 134691 additions and 80709 deletions
+7 -3
View File
@@ -7,12 +7,14 @@ tests/cases/perf/*
test-args.txt
~*.docx
tests/baselines/local/*
tests/baselines/local.old/*
tests/services/baselines/local/*
tests/baselines/prototyping/local/*
tests/baselines/rwc/*
tests/baselines/test262/*
tests/baselines/reference/projectOutput/*
tests/baselines/local/projectOutput/*
tests/baselines/reference/testresults.tap
tests/services/baselines/prototyping/local/*
tests/services/browser/typescriptServices.js
scripts/configureNightly.js
@@ -26,11 +28,13 @@ rwc-report.html
*.swp
build.json
*.actual
tests/webTestServer.js
tests/webTestServer.js.map
tests/webhost/*.d.ts
tests/webhost/webtsc.js
tests/*.js
tests/*.js.map
tests/*.d.ts
tests/cases/**/*.js
tests/cases/**/*.js.map
tests/cases/**/*.d.ts
*.config
scripts/debug.bat
scripts/run.bat
+1 -1
View File
@@ -13,7 +13,7 @@ Issues that ask questions answered in the FAQ will be closed without elaboration
## 3. Do you have a question?
The issue tracker is for **issues**, in other words, bugs and suggestions.
If you have a *question*, please use [http://stackoverflow.com/questions/tagged/typescript](Stack Overflow), [https://gitter.im/Microsoft/TypeScript](Gitter), your favorite search engine, or other resources.
If you have a *question*, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources.
Due to increased traffic, we can no longer answer questions in the issue tracker.
## 4. Did you find a bug?
+370 -83
View File
@@ -5,6 +5,7 @@ var os = require("os");
var path = require("path");
var child_process = require("child_process");
var Linter = require("tslint");
var readline = require("readline");
// Variables
var compilerDirectory = "src/compiler/";
@@ -178,30 +179,73 @@ var harnessSources = harnessCoreSources.concat([
"reuseProgramStructure.ts",
"cachingInServerLSHost.ts",
"moduleResolution.ts",
"tsconfigParsing.ts"
"tsconfigParsing.ts",
"commandLineParsing.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts"
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
"protocol.d.ts",
"session.ts",
"client.ts",
"editorServices.ts",
"editorServices.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}));
var librarySourceMap = [
{ target: "lib.core.d.ts", sources: ["header.d.ts", "core.d.ts"] },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], },
{ target: "lib.d.ts", sources: ["header.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.core.es6.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts"]},
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"]},
{ target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
{ target: "lib.core.d.ts", sources: ["header.d.ts", "core.d.ts"] },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"] },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"] },
{ target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"] },
{ target: "lib.d.ts", sources: ["header.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es6.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts"] },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"] },
{ target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
];
var es2015LibrarySources = [
"es2015.core.d.ts",
"es2015.collection.d.ts",
"es2015.generator.d.ts",
"es2015.iterable.d.ts",
"es2015.promise.d.ts",
"es2015.proxy.d.ts",
"es2015.reflect.d.ts",
"es2015.symbol.d.ts",
"es2015.symbol.wellknown.d.ts",
];
var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
var es2016LibrarySource = [ "es2016.array.include.d.ts" ];
var es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
})
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]
var librarySourceMap = [
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"], },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"], },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
{ target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] },
// 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), },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap);
var libraryTargets = librarySourceMap.map(function (f) {
return path.join(builtLocalDirectory, f.target);
});
@@ -240,8 +284,7 @@ function concatenateFiles(destinationFile, sourceFiles) {
}
var useDebugMode = true;
var useTransforms = process.env.USE_TRANSFORMS || false;
var host = (process.env.host || process.env.TYPESCRIPT_HOST || "node");
var host = (process.env.TYPESCRIPT_HOST || process.env.host || "node");
var compilerFilename = "tsc.js";
var LKGCompiler = path.join(LKGDirectory, compilerFilename);
var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
@@ -252,56 +295,64 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
* @param prereqs: prerequisite tasks to compiling the file
* @param prefixes: a list of files to prepend to the target file
* @param useBuiltCompiler: true to use the built compiler, false to use the LKG
* @param noOutFile: true to compile without using --out
* @param generateDeclarations: true to compile using --declaration
* @param outDir: true to compile using --outDir
* @param keepComments: false to compile using --removeComments
* @parap {Object} opts - property bag containing auxiliary options
* @param {boolean} opts.noOutFile: true to compile without using --out
* @param {boolean} opts.generateDeclarations: true to compile using --declaration
* @param {string} opts.outDir: value for '--outDir' command line option
* @param {boolean} opts.keepComments: false to compile using --removeComments
* @param {boolean} opts.preserveConstEnums: true if compiler should keep const enums in code
* @param {boolean} opts.noResolve: true if compiler should not include non-rooted files in compilation
* @param {boolean} opts.stripInternal: true if compiler should remove declarations marked as @internal
* @param {boolean} opts.noMapRoot: true if compiler omit mapRoot option
* @param callback: a function to execute after the compilation process ends
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) {
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) {
file(outFile, prereqs, function() {
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--noImplicitAny --noEmitOnError --pretty";
opts = opts || {};
// Keep comments when specifically requested
// or when in debug mode.
if (!(keepComments || useDebugMode)) {
if (!(opts.keepComments || useDebugMode)) {
options += " --removeComments";
}
if (generateDeclarations) {
if (opts.generateDeclarations) {
options += " --declaration";
}
if (preserveConstEnums || useDebugMode) {
if (opts.preserveConstEnums || useDebugMode) {
options += " --preserveConstEnums";
}
if (outDir) {
options += " --outDir " + outDir;
if (opts.outDir) {
options += " --outDir " + opts.outDir;
}
if (!noOutFile) {
if (!opts.noOutFile) {
options += " --out " + outFile;
}
else {
options += " --module commonjs"
options += " --module commonjs";
}
if(noResolve) {
if(opts.noResolve) {
options += " --noResolve";
}
if (useDebugMode) {
options += " -sourcemap -mapRoot file:///" + path.resolve(path.dirname(outFile));
options += " -sourcemap";
if (!opts.noMapRoot) {
options += " -mapRoot file:///" + path.resolve(path.dirname(outFile));
}
}
if (stripInternal) {
options += " --stripInternal"
if (opts.stripInternal) {
options += " --stripInternal";
}
if (useBuiltCompiler && useTransforms) {
options += " --experimentalTransforms"
if (useBuiltCompiler && !environmentVariableIsDisabled("USE_TRANSFORMS")) {
console.warn("\u001b[93mwarning: 'USE_TRANSFORMS' environment variable is not set to 'false'. Experimental transforms will be enabled by default.\u001b[0m");
}
var cmd = host + " " + compilerPath + " " + options + " ";
@@ -415,22 +466,12 @@ compileFile(/*outfile*/configureNightlyJs,
/*prereqs*/ [configureNightlyTs],
/*prefixes*/ [],
/*useBuiltCompiler*/ false,
/*noOutFile*/ false,
/*generateDeclarations*/ false,
/*outDir*/ undefined,
/*preserveConstEnums*/ undefined,
/*keepComments*/ false,
/*noResolve*/ false,
/*stripInternal*/ false);
{ noOutFile: false, generateDeclarations: false, keepComments: false, noResolve: false, stripInternal: false });
task("setDebugMode", function() {
useDebugMode = true;
});
task("setTransforms", function() {
useTransforms = true;
});
task("configure-nightly", [configureNightlyJs], function() {
var cmd = host + " " + configureNightlyJs + " " + packageJson + " " + programTs;
console.log(cmd);
@@ -449,9 +490,9 @@ file(scriptsTsdJson);
task("tsd-scripts", [scriptsTsdJson], function () {
var cmd = "tsd --config " + scriptsTsdJson + " install";
console.log(cmd)
console.log(cmd);
exec(cmd);
}, { async: true })
}, { async: true });
var importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importDefinitelyTypedTests");
var importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js");
@@ -475,6 +516,7 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js");
var servicesFileInBrowserTest = path.join(builtLocalDirectory, "typescriptServicesInBrowserTest.js");
var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts");
var nodePackageFile = path.join(builtLocalDirectory, "typescript.js");
var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts");
@@ -483,13 +525,7 @@ var nodeStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescript_s
compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ true,
/*outDir*/ undefined,
/*preserveConstEnums*/ true,
/*keepComments*/ true,
/*noResolve*/ false,
/*stripInternal*/ true,
{ noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true },
/*callback*/ function () {
jake.cpR(servicesFile, nodePackageFile, {silent: true});
@@ -512,6 +548,16 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
fs.writeFileSync(nodeStandaloneDefinitionsFile, nodeStandaloneDefinitionsFileContents);
});
compileFile(servicesFileInBrowserTest, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
{ noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true, noMapRoot: true },
/*callback*/ function () {
var content = fs.readFileSync(servicesFileInBrowserTest).toString();
var i = content.lastIndexOf("\n");
fs.writeFileSync(servicesFileInBrowserTest, content.substring(0, i) + "\r\n//# sourceURL=../built/local/typeScriptServices.js" + content.substring(i));
});
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
@@ -523,8 +569,7 @@ compileFile(
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ true);
{ noOutFile: false, generateDeclarations: true });
// Local target to build the language service server library
desc("Builds language service server library");
@@ -614,7 +659,7 @@ directory(builtLocalDirectory);
var run = path.join(builtLocalDirectory, "run.js");
compileFile(run, harnessSources, [builtLocalDirectory, tscFile].concat(libraryTargets).concat(harnessSources), [], /*useBuiltCompiler:*/ true);
var internalTests = "internal/"
var internalTests = "internal/";
var localBaseline = "tests/baselines/local/";
var refBaseline = "tests/baselines/reference/";
@@ -671,10 +716,25 @@ function cleanTestDirs() {
}
// used to pass data from jake command line directly to run.js
function writeTestConfigFile(tests, light, testConfigFile) {
console.log('Running test(s): ' + tests);
var testConfigContents = JSON.stringify({ test: [tests], light: light });
fs.writeFileSync('test.config', testConfigContents);
function writeTestConfigFile(testConfigFile, tests, light, stackTraceLimit) {
var testConfig;
if (tests) {
console.log('Running test(s): ' + tests);
(testConfig || (testConfig = {})).tests = [tests];
}
if (light) {
(testConfig || (testConfig = {})).light = light;
}
if (/^(\d+|full)$/.test(stackTraceLimit)) {
(testConfig || (testConfig = {})).stackTraceLimit = stackTraceLimit;
}
if (testConfig) {
var testConfigContents = JSON.stringify(testConfig);
fs.writeFileSync(testConfigFile, testConfigContents);
}
}
function deleteTemporaryProjectOutput() {
@@ -683,25 +743,154 @@ function deleteTemporaryProjectOutput() {
}
}
function runConsoleTests(defaultReporter, defaultSubsets, postLint) {
function runTestsAndWriteOutput(file) {
cleanTestDirs();
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);
}
writeTestConfigFile(testConfigFile, tests, light, 10);
if (tests && tests.toLocaleLowerCase() === "rwc") {
testTimeout = 100000;
}
var args = [];
args.push("-R", "tap");
args.push("--no-colors");
args.push("-t", testTimeout);
if (tests) {
args.push("-g", '"' + tests + '"');
}
args.push(run);
var cmd = "mocha " + args.join(" ");
console.log(cmd);
var p = child_process.spawn(
process.platform === "win32" ? "cmd" : "/bin/sh",
process.platform === "win32" ? ["/c", cmd] : ["-c", cmd], {
windowsVerbatimArguments: true
});
var out = fs.createWriteStream(file);
var tapRange = /^(\d+)\.\.(\d+)(?:$|\r\n?|\n)/;
var tapOk = /^ok\s/;
var tapNotOk = /^not\sok\s/;
var tapComment = /^#/;
var typeError = /^\s+TypeError:/;
var debugError = /^\s+Error:\sDebug\sFailure\./;
var progress = new ProgressBar("Running tests...");
var expectedTestCount = 0;
var testCount = 0;
var failureCount = 0;
var successCount = 0;
var comments = [];
var typeErrorCount = 0;
var debugErrorCount = 0;
var rl = readline.createInterface({
input: p.stdout,
terminal: false
});
function updateProgress(percentComplete) {
progress.update(percentComplete,
/*foregroundColor*/ failureCount > 0
? "red"
: successCount === expectedTestCount
? "green"
: "cyan",
/*backgroundColor*/ "gray"
);
}
rl.on("line", function (line) {
var m = tapRange.exec(line);
if (m) {
expectedTestCount = parseInt(m[2]);
return;
}
if (tapOk.test(line)) {
out.write(line.replace(/^ok\s+\d+\s+/, "ok ") + os.EOL);
successCount++;
}
else if (tapNotOk.test(line)) {
out.write(line.replace(/^not\s+ok\s+\d+\s+/, "not ok ") + os.EOL);
failureCount++;
}
else {
out.write(line + os.EOL);
if (tapComment.test(line)) {
comments.push(line);
}
else if (typeError.test(line)) {
typeErrorCount++;
}
else if (debugError.test(line)) {
debugErrorCount++;
}
return;
}
testCount++;
var percentComplete = testCount * 100 / expectedTestCount;
updateProgress(percentComplete);
});
p.on("exit", function (status) {
if (progress.visible) {
updateProgress(100);
process.stdout.write("done." + os.EOL);
}
console.log(comments.join(os.EOL));
if (typeErrorCount) {
console.log("# type errors: %s", typeErrorCount);
}
if (debugErrorCount) {
console.log("# debug errors: %s", debugErrorCount);
}
deleteTemporaryProjectOutput();
if (status) {
fail("Process exited with code " + status);
}
else {
complete();
}
});
}
function runConsoleTests(defaultReporter, defaultSubsets, dirty) {
if (!dirty) {
cleanTestDirs();
}
var debug = process.env.debug || process.env.d;
tests = process.env.test || process.env.tests || process.env.t;
var light = process.env.light || false;
var stackTraceLimit = process.env.stackTraceLimit || 1;
var testConfigFile = 'test.config';
if(fs.existsSync(testConfigFile)) {
if (fs.existsSync(testConfigFile)) {
fs.unlinkSync(testConfigFile);
}
if (tests || light) {
writeTestConfigFile(tests, light, testConfigFile);
writeTestConfigFile(testConfigFile, tests, light, stackTraceLimit);
}
if (tests && tests.toLocaleLowerCase() === "rwc") {
testTimeout = 100000;
}
colors = process.env.colors || process.env.color
colors = process.env.colors || process.env.color;
colors = colors ? ' --no-colors ' : ' --colors ';
reporter = process.env.reporter || process.env.r || defaultReporter;
@@ -709,20 +898,20 @@ function runConsoleTests(defaultReporter, defaultSubsets, postLint) {
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
var subsetRegexes;
if(defaultSubsets.length === 0) {
subsetRegexes = [tests]
subsetRegexes = [tests];
}
else {
var subsets = tests ? tests.split("|") : defaultSubsets;
subsetRegexes = subsets.map(function (sub) { return "^" + sub + ".*$"; });
subsetRegexes.push("^(?!" + subsets.join("|") + ").*$");
}
subsetRegexes.forEach(function (subsetRegex) {
subsetRegexes.forEach(function (subsetRegex, i) {
tests = subsetRegex ? ' -g "' + subsetRegex + '"' : '';
var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd, function () {
deleteTemporaryProjectOutput();
if (postLint) {
if (i === 0 && !dirty) {
var lint = jake.Task['lint'];
lint.addListener('complete', function () {
complete();
@@ -744,9 +933,16 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function() {
runConsoleTests('mocha-fivemat-progress-reporter', [], /*postLint*/ true);
runConsoleTests('mocha-fivemat-progress-reporter', []);
}, {async: true});
task("runtests-file", ["build-rules", "tests", builtLocalDirectory], function () {
runTestsAndWriteOutput("tests/baselines/local/testresults.tap");
}, { async: true });
task("runtests-dirty", ["build-rules", "tests", builtLocalDirectory], function () {
runConsoleTests("mocha-fivemat-progress-reporter", [], /*dirty*/ true);
}, { async: true });
desc("Generates code coverage data via instanbul");
task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run;
@@ -755,20 +951,20 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
}, { async: true });
// Browser tests
var nodeServerOutFile = 'tests/webTestServer.js'
var nodeServerInFile = 'tests/webTestServer.ts'
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, /*noOutFile*/ true);
var nodeServerOutFile = 'tests/webTestServer.js';
var nodeServerInFile = 'tests/webTestServer.ts';
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true });
desc("Runs browserify on run.js to produce a file suitable for running tests in the browser");
task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() {
var cmd = 'browserify built/local/run.js -o built/local/bundle.js';
var cmd = 'browserify built/local/run.js -t ./scripts/browserify-optional -o built/local/bundle.js';
exec(cmd);
}, {async: true});
desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], port=, browser=[chrome|IE]");
task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function() {
task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFileInBrowserTest], function() {
cleanTestDirs();
host = "node"
host = "node";
port = process.env.port || process.env.p || '8888';
browser = process.env.browser || process.env.b || "IE";
tests = process.env.test || process.env.tests || process.env.t;
@@ -778,17 +974,17 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function(
fs.unlinkSync(testConfigFile);
}
if(tests || light) {
writeTestConfigFile(tests, light, testConfigFile);
writeTestConfigFile(testConfigFile, tests, light);
}
tests = tests ? tests : '';
var cmd = host + " tests/webTestServer.js " + port + " " + browser + " " + tests
var cmd = host + " tests/webTestServer.js " + port + " " + browser + " " + tests;
console.log(cmd);
exec(cmd);
}, {async: true});
function getDiffTool() {
var program = process.env['DIFF']
var program = process.env['DIFF'];
if (!program) {
fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
}
@@ -817,11 +1013,11 @@ task("tests-debug", ["setDebugMode", "tests"]);
// Makes the test results the new baseline
desc("Makes the most recent test results the new baseline, overwriting the old baseline");
task("baseline-accept", function(hardOrSoft) {
if (!hardOrSoft || hardOrSoft == "hard") {
if (!hardOrSoft || hardOrSoft === "hard") {
jake.rmRf(refBaseline);
fs.renameSync(localBaseline, refBaseline);
}
else if (hardOrSoft == "soft") {
else if (hardOrSoft === "soft") {
var files = jake.readdirR(localBaseline);
for (var i in files) {
jake.cpR(files[i], refBaseline);
@@ -900,15 +1096,14 @@ task("update-sublime", ["local", serverFile], function() {
});
var tslintRuleDir = "scripts/tslint";
var tslintRules = ([
var tslintRules = [
"nextLineRule",
"noNullRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule",
"noInOperatorRule",
"noIncrementDecrementRule"
]);
];
var tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
});
@@ -918,7 +1113,8 @@ var tslintRulesOutFiles = tslintRules.map(function(p) {
desc("Compiles tslint rules to js");
task("build-rules", tslintRulesOutFiles);
tslintRulesFiles.forEach(function(ruleFile, i) {
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false,
{ noOutFile: true, generateDeclarations: false, outDir: path.join(builtLocalDirectory, "tslint")});
});
function getLinterOptions() {
@@ -932,7 +1128,7 @@ function getLinterOptions() {
function lintFileContents(options, path, contents) {
var ll = new Linter(path, contents, options);
console.log("Linting '" + path + "'.")
console.log("Linting '" + path + "'.");
return ll.lint();
}
@@ -957,6 +1153,7 @@ var servicesLintTargets = [
"patternMatcher.ts",
"services.ts",
"shims.ts",
"jsTyping.ts"
].map(function (s) {
return path.join(servicesDirectory, s);
});
@@ -1027,3 +1224,93 @@ task("lint-server", ["build-rules"], function() {
lintWatchFile(lintTargets[i]);
}
});
function ProgressBar(title) {
this.title = title;
}
ProgressBar.prototype = {
progressChars: ["\u0020", "\u2591", "\u2592", "\u2593", "\u2588"],
colors: {
foreground: {
black: "\u001b[90m",
red: "\u001b[91m",
green: "\u001b[92m",
yellow: "\u001b[93m",
blue: "\u001b[94m",
magenta: "\u001b[95m",
cyan: "\u001b[96m",
white: "\u001b[97m",
gray: "\u001b[37m"
},
background: {
black: "\u001b[40m",
red: "\u001b[41m",
green: "\u001b[42m",
yellow: "\u001b[43m",
blue: "\u001b[44m",
magenta: "\u001b[45m",
cyan: "\u001b[46m",
white: "\u001b[47m",
gray: "\u001b[100m"
},
reset: "\u001b[0m"
},
update: function (percentComplete, foregroundColor, backgroundColor) {
var progress = "";
for (var i = 0; i < 100; i += 4) {
progress += this.progressChars[Math.floor(Math.max(0, Math.min(4, percentComplete - i)))];
}
foregroundColor = foregroundColor && this.colors.foreground[foregroundColor];
backgroundColor = backgroundColor && this.colors.background[backgroundColor];
if (foregroundColor || backgroundColor) {
if (foregroundColor) {
progress = foregroundColor + progress;
}
if (backgroundColor) {
progress = backgroundColor + progress;
}
progress += this.colors.reset;
}
if (this._lastProgress !== progress || !this.visible) {
this._print(progress);
}
},
hide: function () {
if (this.visible) {
this._savedProgress = this._lastProgress;
this.clear();
}
},
show: function () {
if (this._savedProgress && !this.visible) {
this._print(this._savedProgress);
this._savedProgress = undefined;
}
},
clear: function () {
if (this._lastProgress) {
readline.moveCursor(process.stdout, -process.stdout.columns, 0);
readline.clearLine(process.stdout, 1);
this._lastProgress = undefined;
this.visible = false;
}
},
_print: function (progress) {
readline.moveCursor(process.stdout, -process.stdout.columns, 0);
process.stdout.write(this.title ? progress + " " + this.title : progress);
readline.clearLine(process.stdout, 1);
this._lastProgress = progress;
this.visible = true;
}
};
function environmentVariableIsEnabled(name) {
return /^(y(es)?|t(rue)?|on|enabled?|1|\+)$/.test(process.env[name]);
}
function environmentVariableIsDisabled(name) {
return /^(no?|f(alse)?|off|disabled?|0|-)$/.test(process.env[name]);
}
+4
View File
@@ -0,0 +1,4 @@
# The TypeScript Handbook
The contents of the TypeScript Handbook can be read from [its GitHub repository](https://github.com/Microsoft/TypeScript-Handbook).
Issues and pull requests should be directed there.
+6
View File
@@ -0,0 +1,6 @@
# The TypeScript Wiki
To read the wiki, [visit the wiki on GitHub](https://github.com/Microsoft/TypeScript/wiki).
To contribute by filing an issue or sending a pull request, [visit the wiki repository](https://github.com/Microsoft/TypeScript-wiki).
+27
View File
@@ -0,0 +1,27 @@
<!--
Thank you for contributing to TypeScript! Please review this checklist
before submitting your issue.
[ ] Many common issues and suggestions are addressed in the FAQ
https://github.com/Microsoft/TypeScript/wiki/FAQ
[ ] Search for duplicates before logging new issues
https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue
[ ] Questions are best asked and answered at Stack Overflow
http://stackoverflow.com/questions/tagged/typescript
For bug reports, please include the information below.
__________________________________________________________ -->
**TypeScript Version:**
1.7.5 / 1.8.0-beta / nightly (1.9.0-dev.20160217)
**Code**
```ts
// A self-contained demonstration of the problem follows...
```
**Expected behavior:**
**Actual behavior:**
-5172
View File
File diff suppressed because it is too large Load Diff
+4278 -3130
View File
File diff suppressed because it is too large Load Diff
+4010 -3149
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.dom.generated.d.ts" />
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}
interface NodeList {
[Symbol.iterator](): IterableIterator<Node>
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>
}
+86
View File
@@ -0,0 +1,86 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
+499
View File
@@ -0,0 +1,499 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 10‍‍16.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
big(): string;
/** Returns a <blink> HTML element */
blink(): string;
/** Returns a <b> HTML element */
bold(): string;
/** Returns a <tt> HTML element */
fixed(): string
/** Returns a <font> HTML element and sets the color attribute value */
fontcolor(color: string): string
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an <i> HTML element */
italics(): string;
/** Returns an <a> HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a <small> HTML element */
small(): string;
/** Returns a <strike> HTML element */
strike(): string;
/** Returns a <sub> HTML element */
sub(): string;
/** Returns a <sup> HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
+26
View File
@@ -0,0 +1,26 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />
+28
View File
@@ -0,0 +1,28 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;
+389
View File
@@ -0,0 +1,389 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface IteratorResult<T> {
done: boolean;
value?: T;
}
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface IterableIterator<T> extends Iterator<T> { }
interface Array<T> {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
interface Map<K, V> {
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
}
interface MapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
}
interface WeakMap<K, V> { }
interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Promise<T> { }
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
+97
View File
@@ -0,0 +1,97 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject(reason: any): Promise<void>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;
+38
View File
@@ -0,0 +1,38 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
deleteProperty? (target: T, p: PropertyKey): boolean;
defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
+32
View File
@@ -0,0 +1,32 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
+52
View File
@@ -0,0 +1,52 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string|number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;
+372
View File
@@ -0,0 +1,372 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
interface Symbol {
readonly [Symbol.toStringTag]: "Symbol";
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
[Symbol.unscopables](): {
copyWithin: boolean;
entries: boolean;
fill: boolean;
find: boolean;
findIndex: boolean;
keys: boolean;
values: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
interface Promise<T> {
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
readonly [Symbol.species]: Function;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
[Symbol.species](): RegExpConstructor;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
readonly [Symbol.toStringTag]: "DataView";
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}
+105
View File
@@ -0,0 +1,105 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
+18
View File
@@ -0,0 +1,18 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />
+470 -183
View File
File diff suppressed because it is too large Load Diff
+5720 -4474
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -13,7 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference path="lib.core.d.ts" />
/// <reference no-default-lib="true"/>
/////////////////////////////
+272 -472
View File
File diff suppressed because it is too large Load Diff
+7253 -4659
View File
File diff suppressed because it is too large Load Diff
+9009 -5911
View File
File diff suppressed because it is too large Load Diff
+312 -211
View File
@@ -160,169 +160,173 @@ declare namespace ts {
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
RequireKeyword = 127,
NumberKeyword = 128,
SetKeyword = 129,
StringKeyword = 130,
SymbolKeyword = 131,
TypeKeyword = 132,
FromKeyword = 133,
GlobalKeyword = 134,
OfKeyword = 135,
QualifiedName = 136,
ComputedPropertyName = 137,
TypeParameter = 138,
Parameter = 139,
Decorator = 140,
PropertySignature = 141,
PropertyDeclaration = 142,
MethodSignature = 143,
MethodDeclaration = 144,
Constructor = 145,
GetAccessor = 146,
SetAccessor = 147,
CallSignature = 148,
ConstructSignature = 149,
IndexSignature = 150,
TypePredicate = 151,
TypeReference = 152,
FunctionType = 153,
ConstructorType = 154,
TypeQuery = 155,
TypeLiteral = 156,
ArrayType = 157,
TupleType = 158,
UnionType = 159,
IntersectionType = 160,
ParenthesizedType = 161,
ThisType = 162,
StringLiteralType = 163,
ObjectBindingPattern = 164,
ArrayBindingPattern = 165,
BindingElement = 166,
ArrayLiteralExpression = 167,
ObjectLiteralExpression = 168,
PropertyAccessExpression = 169,
ElementAccessExpression = 170,
CallExpression = 171,
NewExpression = 172,
TaggedTemplateExpression = 173,
TypeAssertionExpression = 174,
ParenthesizedExpression = 175,
FunctionExpression = 176,
ArrowFunction = 177,
DeleteExpression = 178,
TypeOfExpression = 179,
VoidExpression = 180,
AwaitExpression = 181,
PrefixUnaryExpression = 182,
PostfixUnaryExpression = 183,
BinaryExpression = 184,
ConditionalExpression = 185,
TemplateExpression = 186,
YieldExpression = 187,
SpreadElementExpression = 188,
ClassExpression = 189,
OmittedExpression = 190,
ExpressionWithTypeArguments = 191,
AsExpression = 192,
TemplateSpan = 193,
SemicolonClassElement = 194,
Block = 195,
VariableStatement = 196,
EmptyStatement = 197,
ExpressionStatement = 198,
IfStatement = 199,
DoStatement = 200,
WhileStatement = 201,
ForStatement = 202,
ForInStatement = 203,
ForOfStatement = 204,
ContinueStatement = 205,
BreakStatement = 206,
ReturnStatement = 207,
WithStatement = 208,
SwitchStatement = 209,
LabeledStatement = 210,
ThrowStatement = 211,
TryStatement = 212,
DebuggerStatement = 213,
VariableDeclaration = 214,
VariableDeclarationList = 215,
FunctionDeclaration = 216,
ClassDeclaration = 217,
InterfaceDeclaration = 218,
TypeAliasDeclaration = 219,
EnumDeclaration = 220,
ModuleDeclaration = 221,
ModuleBlock = 222,
CaseBlock = 223,
ImportEqualsDeclaration = 224,
ImportDeclaration = 225,
ImportClause = 226,
NamespaceImport = 227,
NamedImports = 228,
ImportSpecifier = 229,
ExportAssignment = 230,
ExportDeclaration = 231,
NamedExports = 232,
ExportSpecifier = 233,
MissingDeclaration = 234,
ExternalModuleReference = 235,
JsxElement = 236,
JsxSelfClosingElement = 237,
JsxOpeningElement = 238,
JsxText = 239,
JsxClosingElement = 240,
JsxAttribute = 241,
JsxSpreadAttribute = 242,
JsxExpression = 243,
CaseClause = 244,
DefaultClause = 245,
HeritageClause = 246,
CatchClause = 247,
PropertyAssignment = 248,
ShorthandPropertyAssignment = 249,
EnumMember = 250,
SourceFile = 251,
JSDocTypeExpression = 252,
JSDocAllType = 253,
JSDocUnknownType = 254,
JSDocArrayType = 255,
JSDocUnionType = 256,
JSDocTupleType = 257,
JSDocNullableType = 258,
JSDocNonNullableType = 259,
JSDocRecordType = 260,
JSDocRecordMember = 261,
JSDocTypeReference = 262,
JSDocOptionalType = 263,
JSDocFunctionType = 264,
JSDocVariadicType = 265,
JSDocConstructorType = 266,
JSDocThisType = 267,
JSDocComment = 268,
JSDocTag = 269,
JSDocParameterTag = 270,
JSDocReturnTag = 271,
JSDocTypeTag = 272,
JSDocTemplateTag = 273,
SyntaxList = 274,
Count = 275,
ReadonlyKeyword = 127,
RequireKeyword = 128,
NumberKeyword = 129,
SetKeyword = 130,
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 135,
LastKeyword = 137,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 151,
LastTypeNode = 163,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 135,
LastToken = 137,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -331,40 +335,48 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 136,
FirstNode = 138,
}
enum NodeFlags {
None = 0,
Export = 2,
Ambient = 4,
Public = 8,
Private = 16,
Protected = 32,
Static = 64,
Export = 1,
Ambient = 2,
Public = 4,
Private = 8,
Protected = 16,
Static = 32,
Readonly = 64,
Abstract = 128,
Async = 256,
Default = 512,
MultiLine = 1024,
Synthetic = 2048,
DeclarationFile = 4096,
Let = 8192,
Const = 16384,
OctalLiteral = 32768,
Namespace = 65536,
ExportContext = 131072,
ContainsThis = 262144,
HasImplicitReturn = 524288,
HasExplicitReturn = 1048576,
GlobalAugmentation = 2097152,
HasClassExtends = 4194304,
HasDecorators = 8388608,
HasParamDecorators = 16777216,
HasAsyncFunctions = 33554432,
Modifier = 1022,
AccessibilityModifier = 56,
BlockScoped = 24576,
ReachabilityCheckFlags = 1572864,
EmitHelperFlags = 62914560,
Let = 1024,
Const = 2048,
Namespace = 4096,
ExportContext = 8192,
ContainsThis = 16384,
HasImplicitReturn = 32768,
HasExplicitReturn = 65536,
GlobalAugmentation = 131072,
HasClassExtends = 262144,
HasDecorators = 524288,
HasParamDecorators = 1048576,
HasAsyncFunctions = 2097152,
DisallowInContext = 4194304,
YieldContext = 8388608,
DecoratorContext = 16777216,
AwaitContext = 33554432,
ThisNodeHasError = 67108864,
JavaScriptFile = 134217728,
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
AccessibilityModifier = 28,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
ContextFlags = 197132288,
TypeExcludesFlags = 41943040,
}
enum JsxFlags {
None = 0,
@@ -372,10 +384,6 @@ declare namespace ts {
IntrinsicNamedElement = 1,
/** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 2,
/** An element backed by a class, class-like, or function value */
ValueElement = 4,
/** Element resolution failed */
UnknownElement = 16,
IntrinsicElement = 3,
}
interface Node extends TextRange {
@@ -397,6 +405,9 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@@ -698,11 +709,12 @@ declare namespace ts {
dotToken: Node;
name: Identifier;
}
type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
}
interface CallExpression extends LeftHandSideExpression {
interface CallExpression extends LeftHandSideExpression, Declaration {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
arguments: NodeArray<Expression>;
@@ -727,6 +739,9 @@ declare namespace ts {
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
@@ -850,6 +865,7 @@ declare namespace ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@@ -919,6 +935,10 @@ declare namespace ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
@@ -1000,6 +1020,7 @@ declare namespace ts {
interface JSDocThisType extends JSDocType {
type: JSDocType;
}
type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType;
interface JSDocRecordMember extends PropertySignature {
name: Identifier | LiteralExpression;
type?: JSDocType;
@@ -1039,7 +1060,9 @@ declare namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
/**
* lib.d.ts should have a reference comment like
*
@@ -1060,7 +1083,7 @@ declare namespace ts {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
class OperationCanceledException {
}
@@ -1133,7 +1156,9 @@ declare namespace ts {
}
interface EmitResult {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[];
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
@@ -1177,8 +1202,9 @@ declare namespace ts {
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@@ -1217,17 +1243,18 @@ declare namespace ts {
This = 0,
Identifier = 1,
}
interface TypePredicate {
interface TypePredicateBase {
kind: TypePredicateKind;
type: Type;
}
interface ThisTypePredicate extends TypePredicate {
interface ThisTypePredicate extends TypePredicateBase {
_thisTypePredicateBrand: any;
}
interface IdentifierTypePredicate extends TypePredicate {
interface IdentifierTypePredicate extends TypePredicateBase {
parameterName: string;
parameterIndex: number;
}
type TypePredicate = IdentifierTypePredicate | ThisTypePredicate;
enum SymbolFlags {
None = 0,
FunctionScopedVariable = 1,
@@ -1301,6 +1328,7 @@ declare namespace ts {
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
}
interface SymbolTable {
[index: string]: Symbol;
@@ -1328,7 +1356,6 @@ declare namespace ts {
ESSymbol = 16777216,
ThisType = 33554432,
ObjectLiteralPatternWithComputedProperties = 67108864,
PredicateType = 134217728,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
@@ -1341,9 +1368,6 @@ declare namespace ts {
symbol?: Symbol;
pattern?: DestructuringPattern;
}
interface PredicateType extends Type {
predicate: ThisTypePredicate | IdentifierTypePredicate;
}
interface StringLiteralType extends Type {
text: string;
}
@@ -1359,8 +1383,8 @@ declare namespace ts {
declaredProperties: Symbol[];
declaredCallSignatures: Signature[];
declaredConstructSignatures: Signature[];
declaredStringIndexType: Type;
declaredNumberIndexType: Type;
declaredStringIndexInfo: IndexInfo;
declaredNumberIndexInfo: IndexInfo;
}
interface TypeReference extends ObjectType {
target: GenericType;
@@ -1389,11 +1413,17 @@ declare namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType?: Type;
}
enum IndexKind {
String = 0,
Number = 1,
}
interface IndexInfo {
type: Type;
isReadonly: boolean;
declaration?: SignatureDeclaration;
}
interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
@@ -1429,10 +1459,15 @@ declare namespace ts {
Classic = 1,
NodeJs = 2,
}
type RootPaths = string[];
type PathSubstitutions = Map<string[]>;
type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@@ -1442,6 +1477,7 @@ declare namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@@ -1451,6 +1487,7 @@ declare namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@@ -1476,9 +1513,33 @@ declare namespace ts {
noImplicitReturns?: boolean;
noFallthroughCasesInSwitch?: boolean;
forceConsistentCasingInFileNames?: boolean;
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
[option: string]: string | number | boolean;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
interface DiscoverTypingsInfo {
fileNames: string[];
projectRootPath: string;
safeListPath: string;
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
}
enum ModuleKind {
None = 0,
@@ -1502,6 +1563,13 @@ declare namespace ts {
line: number;
character: number;
}
enum ScriptKind {
Unknown = 0,
JS = 1,
JSX = 2,
TS = 3,
TSX = 4,
}
enum ScriptTarget {
ES3 = 0,
ES5 = 1,
@@ -1515,12 +1583,14 @@ declare namespace ts {
}
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
}
interface ResolvedModule {
@@ -1531,16 +1601,29 @@ declare namespace ts {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
primary: boolean;
resolvedFileName?: string;
}
interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
}
interface TextSpan {
start: number;
@@ -1552,8 +1635,8 @@ declare namespace ts {
}
}
declare namespace ts {
type FileWatcherCallback = (path: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (path: string) => void;
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface System {
args: string[];
newLine: string;
@@ -1561,7 +1644,7 @@ declare namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@@ -1570,6 +1653,8 @@ declare namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@@ -1577,7 +1662,7 @@ declare namespace ts {
close(): void;
}
interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
var sys: System;
@@ -1604,6 +1689,7 @@ declare namespace ts {
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scanJSDocToken(): SyntaxKind;
scan(): SyntaxKind;
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
@@ -1611,6 +1697,7 @@ declare namespace ts {
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
lookAhead<T>(callback: () => T): T;
scanRange<T>(start: number, length: number, callback: () => T): T;
tryScan<T>(callback: () => T): T;
}
function tokenToString(t: SyntaxKind): string;
@@ -1657,17 +1744,26 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
const version: string;
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
@@ -1677,7 +1773,6 @@ declare namespace ts {
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -1702,8 +1797,12 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): {
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
@@ -1784,6 +1883,7 @@ declare namespace ts {
}
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@@ -1796,6 +1896,7 @@ declare namespace ts {
getNewLine?(): string;
getProjectVersion?(): string;
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getLocalizedDiagnosticMessages?(): any;
@@ -1807,6 +1908,7 @@ declare namespace ts {
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
interface LanguageService {
@@ -1851,7 +1953,6 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {
@@ -2164,7 +2265,7 @@ declare namespace ts {
* @parm version Current version of the file. Only used if the file was not found
* in the registry and a new one was created.
*/
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile;
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -2177,7 +2278,7 @@ declare namespace ts {
* @param scriptSnapshot Text of the file.
* @param version Current version of the file.
*/
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile;
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -2301,7 +2402,7 @@ declare namespace ts {
}
function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput;
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry;
+10082 -6528
View File
File diff suppressed because it is too large Load Diff
+312 -211
View File
@@ -160,169 +160,173 @@ declare namespace ts {
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
RequireKeyword = 127,
NumberKeyword = 128,
SetKeyword = 129,
StringKeyword = 130,
SymbolKeyword = 131,
TypeKeyword = 132,
FromKeyword = 133,
GlobalKeyword = 134,
OfKeyword = 135,
QualifiedName = 136,
ComputedPropertyName = 137,
TypeParameter = 138,
Parameter = 139,
Decorator = 140,
PropertySignature = 141,
PropertyDeclaration = 142,
MethodSignature = 143,
MethodDeclaration = 144,
Constructor = 145,
GetAccessor = 146,
SetAccessor = 147,
CallSignature = 148,
ConstructSignature = 149,
IndexSignature = 150,
TypePredicate = 151,
TypeReference = 152,
FunctionType = 153,
ConstructorType = 154,
TypeQuery = 155,
TypeLiteral = 156,
ArrayType = 157,
TupleType = 158,
UnionType = 159,
IntersectionType = 160,
ParenthesizedType = 161,
ThisType = 162,
StringLiteralType = 163,
ObjectBindingPattern = 164,
ArrayBindingPattern = 165,
BindingElement = 166,
ArrayLiteralExpression = 167,
ObjectLiteralExpression = 168,
PropertyAccessExpression = 169,
ElementAccessExpression = 170,
CallExpression = 171,
NewExpression = 172,
TaggedTemplateExpression = 173,
TypeAssertionExpression = 174,
ParenthesizedExpression = 175,
FunctionExpression = 176,
ArrowFunction = 177,
DeleteExpression = 178,
TypeOfExpression = 179,
VoidExpression = 180,
AwaitExpression = 181,
PrefixUnaryExpression = 182,
PostfixUnaryExpression = 183,
BinaryExpression = 184,
ConditionalExpression = 185,
TemplateExpression = 186,
YieldExpression = 187,
SpreadElementExpression = 188,
ClassExpression = 189,
OmittedExpression = 190,
ExpressionWithTypeArguments = 191,
AsExpression = 192,
TemplateSpan = 193,
SemicolonClassElement = 194,
Block = 195,
VariableStatement = 196,
EmptyStatement = 197,
ExpressionStatement = 198,
IfStatement = 199,
DoStatement = 200,
WhileStatement = 201,
ForStatement = 202,
ForInStatement = 203,
ForOfStatement = 204,
ContinueStatement = 205,
BreakStatement = 206,
ReturnStatement = 207,
WithStatement = 208,
SwitchStatement = 209,
LabeledStatement = 210,
ThrowStatement = 211,
TryStatement = 212,
DebuggerStatement = 213,
VariableDeclaration = 214,
VariableDeclarationList = 215,
FunctionDeclaration = 216,
ClassDeclaration = 217,
InterfaceDeclaration = 218,
TypeAliasDeclaration = 219,
EnumDeclaration = 220,
ModuleDeclaration = 221,
ModuleBlock = 222,
CaseBlock = 223,
ImportEqualsDeclaration = 224,
ImportDeclaration = 225,
ImportClause = 226,
NamespaceImport = 227,
NamedImports = 228,
ImportSpecifier = 229,
ExportAssignment = 230,
ExportDeclaration = 231,
NamedExports = 232,
ExportSpecifier = 233,
MissingDeclaration = 234,
ExternalModuleReference = 235,
JsxElement = 236,
JsxSelfClosingElement = 237,
JsxOpeningElement = 238,
JsxText = 239,
JsxClosingElement = 240,
JsxAttribute = 241,
JsxSpreadAttribute = 242,
JsxExpression = 243,
CaseClause = 244,
DefaultClause = 245,
HeritageClause = 246,
CatchClause = 247,
PropertyAssignment = 248,
ShorthandPropertyAssignment = 249,
EnumMember = 250,
SourceFile = 251,
JSDocTypeExpression = 252,
JSDocAllType = 253,
JSDocUnknownType = 254,
JSDocArrayType = 255,
JSDocUnionType = 256,
JSDocTupleType = 257,
JSDocNullableType = 258,
JSDocNonNullableType = 259,
JSDocRecordType = 260,
JSDocRecordMember = 261,
JSDocTypeReference = 262,
JSDocOptionalType = 263,
JSDocFunctionType = 264,
JSDocVariadicType = 265,
JSDocConstructorType = 266,
JSDocThisType = 267,
JSDocComment = 268,
JSDocTag = 269,
JSDocParameterTag = 270,
JSDocReturnTag = 271,
JSDocTypeTag = 272,
JSDocTemplateTag = 273,
SyntaxList = 274,
Count = 275,
ReadonlyKeyword = 127,
RequireKeyword = 128,
NumberKeyword = 129,
SetKeyword = 130,
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 135,
LastKeyword = 137,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 151,
LastTypeNode = 163,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 135,
LastToken = 137,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -331,40 +335,48 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 136,
FirstNode = 138,
}
enum NodeFlags {
None = 0,
Export = 2,
Ambient = 4,
Public = 8,
Private = 16,
Protected = 32,
Static = 64,
Export = 1,
Ambient = 2,
Public = 4,
Private = 8,
Protected = 16,
Static = 32,
Readonly = 64,
Abstract = 128,
Async = 256,
Default = 512,
MultiLine = 1024,
Synthetic = 2048,
DeclarationFile = 4096,
Let = 8192,
Const = 16384,
OctalLiteral = 32768,
Namespace = 65536,
ExportContext = 131072,
ContainsThis = 262144,
HasImplicitReturn = 524288,
HasExplicitReturn = 1048576,
GlobalAugmentation = 2097152,
HasClassExtends = 4194304,
HasDecorators = 8388608,
HasParamDecorators = 16777216,
HasAsyncFunctions = 33554432,
Modifier = 1022,
AccessibilityModifier = 56,
BlockScoped = 24576,
ReachabilityCheckFlags = 1572864,
EmitHelperFlags = 62914560,
Let = 1024,
Const = 2048,
Namespace = 4096,
ExportContext = 8192,
ContainsThis = 16384,
HasImplicitReturn = 32768,
HasExplicitReturn = 65536,
GlobalAugmentation = 131072,
HasClassExtends = 262144,
HasDecorators = 524288,
HasParamDecorators = 1048576,
HasAsyncFunctions = 2097152,
DisallowInContext = 4194304,
YieldContext = 8388608,
DecoratorContext = 16777216,
AwaitContext = 33554432,
ThisNodeHasError = 67108864,
JavaScriptFile = 134217728,
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
AccessibilityModifier = 28,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
ContextFlags = 197132288,
TypeExcludesFlags = 41943040,
}
enum JsxFlags {
None = 0,
@@ -372,10 +384,6 @@ declare namespace ts {
IntrinsicNamedElement = 1,
/** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 2,
/** An element backed by a class, class-like, or function value */
ValueElement = 4,
/** Element resolution failed */
UnknownElement = 16,
IntrinsicElement = 3,
}
interface Node extends TextRange {
@@ -397,6 +405,9 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@@ -698,11 +709,12 @@ declare namespace ts {
dotToken: Node;
name: Identifier;
}
type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
}
interface CallExpression extends LeftHandSideExpression {
interface CallExpression extends LeftHandSideExpression, Declaration {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
arguments: NodeArray<Expression>;
@@ -727,6 +739,9 @@ declare namespace ts {
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
@@ -850,6 +865,7 @@ declare namespace ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@@ -919,6 +935,10 @@ declare namespace ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
@@ -1000,6 +1020,7 @@ declare namespace ts {
interface JSDocThisType extends JSDocType {
type: JSDocType;
}
type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType;
interface JSDocRecordMember extends PropertySignature {
name: Identifier | LiteralExpression;
type?: JSDocType;
@@ -1039,7 +1060,9 @@ declare namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
/**
* lib.d.ts should have a reference comment like
*
@@ -1060,7 +1083,7 @@ declare namespace ts {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
class OperationCanceledException {
}
@@ -1133,7 +1156,9 @@ declare namespace ts {
}
interface EmitResult {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[];
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
@@ -1177,8 +1202,9 @@ declare namespace ts {
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@@ -1217,17 +1243,18 @@ declare namespace ts {
This = 0,
Identifier = 1,
}
interface TypePredicate {
interface TypePredicateBase {
kind: TypePredicateKind;
type: Type;
}
interface ThisTypePredicate extends TypePredicate {
interface ThisTypePredicate extends TypePredicateBase {
_thisTypePredicateBrand: any;
}
interface IdentifierTypePredicate extends TypePredicate {
interface IdentifierTypePredicate extends TypePredicateBase {
parameterName: string;
parameterIndex: number;
}
type TypePredicate = IdentifierTypePredicate | ThisTypePredicate;
enum SymbolFlags {
None = 0,
FunctionScopedVariable = 1,
@@ -1301,6 +1328,7 @@ declare namespace ts {
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
}
interface SymbolTable {
[index: string]: Symbol;
@@ -1328,7 +1356,6 @@ declare namespace ts {
ESSymbol = 16777216,
ThisType = 33554432,
ObjectLiteralPatternWithComputedProperties = 67108864,
PredicateType = 134217728,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
@@ -1341,9 +1368,6 @@ declare namespace ts {
symbol?: Symbol;
pattern?: DestructuringPattern;
}
interface PredicateType extends Type {
predicate: ThisTypePredicate | IdentifierTypePredicate;
}
interface StringLiteralType extends Type {
text: string;
}
@@ -1359,8 +1383,8 @@ declare namespace ts {
declaredProperties: Symbol[];
declaredCallSignatures: Signature[];
declaredConstructSignatures: Signature[];
declaredStringIndexType: Type;
declaredNumberIndexType: Type;
declaredStringIndexInfo: IndexInfo;
declaredNumberIndexInfo: IndexInfo;
}
interface TypeReference extends ObjectType {
target: GenericType;
@@ -1389,11 +1413,17 @@ declare namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType?: Type;
}
enum IndexKind {
String = 0,
Number = 1,
}
interface IndexInfo {
type: Type;
isReadonly: boolean;
declaration?: SignatureDeclaration;
}
interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
@@ -1429,10 +1459,15 @@ declare namespace ts {
Classic = 1,
NodeJs = 2,
}
type RootPaths = string[];
type PathSubstitutions = Map<string[]>;
type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@@ -1442,6 +1477,7 @@ declare namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@@ -1451,6 +1487,7 @@ declare namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@@ -1476,9 +1513,33 @@ declare namespace ts {
noImplicitReturns?: boolean;
noFallthroughCasesInSwitch?: boolean;
forceConsistentCasingInFileNames?: boolean;
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
[option: string]: string | number | boolean;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
interface DiscoverTypingsInfo {
fileNames: string[];
projectRootPath: string;
safeListPath: string;
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
}
enum ModuleKind {
None = 0,
@@ -1502,6 +1563,13 @@ declare namespace ts {
line: number;
character: number;
}
enum ScriptKind {
Unknown = 0,
JS = 1,
JSX = 2,
TS = 3,
TSX = 4,
}
enum ScriptTarget {
ES3 = 0,
ES5 = 1,
@@ -1515,12 +1583,14 @@ declare namespace ts {
}
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
}
interface ResolvedModule {
@@ -1531,16 +1601,29 @@ declare namespace ts {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
primary: boolean;
resolvedFileName?: string;
}
interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
}
interface TextSpan {
start: number;
@@ -1552,8 +1635,8 @@ declare namespace ts {
}
}
declare namespace ts {
type FileWatcherCallback = (path: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (path: string) => void;
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface System {
args: string[];
newLine: string;
@@ -1561,7 +1644,7 @@ declare namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@@ -1570,6 +1653,8 @@ declare namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@@ -1577,7 +1662,7 @@ declare namespace ts {
close(): void;
}
interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
var sys: System;
@@ -1604,6 +1689,7 @@ declare namespace ts {
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scanJSDocToken(): SyntaxKind;
scan(): SyntaxKind;
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
@@ -1611,6 +1697,7 @@ declare namespace ts {
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
lookAhead<T>(callback: () => T): T;
scanRange<T>(start: number, length: number, callback: () => T): T;
tryScan<T>(callback: () => T): T;
}
function tokenToString(t: SyntaxKind): string;
@@ -1657,17 +1744,26 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
const version: string;
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
@@ -1677,7 +1773,6 @@ declare namespace ts {
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -1702,8 +1797,12 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): {
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
@@ -1784,6 +1883,7 @@ declare namespace ts {
}
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@@ -1796,6 +1896,7 @@ declare namespace ts {
getNewLine?(): string;
getProjectVersion?(): string;
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getLocalizedDiagnosticMessages?(): any;
@@ -1807,6 +1908,7 @@ declare namespace ts {
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
interface LanguageService {
@@ -1851,7 +1953,6 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {
@@ -2164,7 +2265,7 @@ declare namespace ts {
* @parm version Current version of the file. Only used if the file was not found
* in the registry and a new one was created.
*/
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile;
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -2177,7 +2278,7 @@ declare namespace ts {
* @param scriptSnapshot Text of the file.
* @param version Current version of the file.
*/
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string): SourceFile;
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -2301,7 +2402,7 @@ declare namespace ts {
}
function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput;
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry;
+10082 -6528
View File
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
<!--
Thank you for submitting a pull request!
Here's a checklist you might find useful.
[ ] There is an associated issue that is labelled
'Bug' or 'Accepting PRs' or is in the Community milestone
[ ] Code is up-to-date with the `master` branch
[ ] You've successfully run `jake runtests` locally
[ ] You've signed the CLA
[ ] There are new or updated unit tests validating the change
Refer to CONTRIBUTING.MD for more details.
https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md
-->
Fixes #
+24
View File
@@ -0,0 +1,24 @@
// simple script to optionally elide source-map-support (or other optional modules) when running browserify.
var stream = require("stream"),
Transform = stream.Transform,
resolve = require("browser-resolve");
var requirePattern = /require\s*\(\s*['"](source-map-support)['"]\s*\)/;
module.exports = function (file) {
return new Transform({
transform: function (data, encoding, cb) {
var text = encoding === "buffer" ? data.toString("utf8") : data;
this.push(new Buffer(text.replace(requirePattern, function (originalText, moduleName) {
try {
resolve.sync(moduleName, { filename: file });
return originalText;
}
catch (e) {
return "(function () { throw new Error(\"module '" + moduleName + "' not found.\"); })()";
}
}), "utf8"));
cb();
}
});
};
+5 -2
View File
@@ -76,8 +76,11 @@ module Commands {
fs.mkdirSync(directoryPath);
}
}
function normalizeSlashes(path: string): string {
return path.replace(/\\/g, "/");
}
function transalatePath(outputFolder:string, path: string): string {
return outputFolder + directorySeparator + path.replace(":", "");
return normalizeSlashes(outputFolder + directorySeparator + path.replace(":", ""));
}
function fileExists(path: string): boolean {
return fs.existsSync(path);
@@ -86,7 +89,7 @@ module Commands {
var filename = transalatePath(outputFolder, f.path);
ensureDirectoriesExist(getDirectoryPath(filename));
console.log("writing filename: " + filename);
fs.writeFile(filename, f.result.contents, (err) => { });
fs.writeFileSync(filename, f.result.contents);
});
console.log("Command: tsc ");
-20
View File
@@ -1,20 +0,0 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Don't use the 'null' keyword - use 'undefined' for missing values instead";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NullWalker(sourceFile, this.getOptions()));
}
}
class NullWalker extends Lint.RuleWalker {
visitNode(node: ts.Node) {
super.visitNode(node);
if (node.kind === ts.SyntaxKind.NullKeyword) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
}
}
+468 -249
View File
File diff suppressed because it is too large Load Diff
+2342 -1126
View File
File diff suppressed because it is too large Load Diff
+268 -98
View File
@@ -17,6 +17,12 @@ namespace ts {
type: "boolean",
description: Diagnostics.Generates_corresponding_d_ts_file,
},
{
name: "declarationDir",
type: "string",
isFilePath: true,
paramType: Diagnostics.DIRECTORY,
},
{
name: "diagnostics",
type: "boolean",
@@ -52,12 +58,11 @@ namespace ts {
},
paramType: Diagnostics.KIND,
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
error: Diagnostics.Argument_for_jsx_must_be_preserve_or_react
},
{
name: "reactNamespace",
type: "string",
description: Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
},
{
name: "listFiles",
@@ -71,13 +76,14 @@ namespace ts {
name: "mapRoot",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
paramType: Diagnostics.LOCATION,
},
{
name: "module",
shortName: "m",
type: {
"none": ModuleKind.None,
"commonjs": ModuleKind.CommonJS,
"amd": ModuleKind.AMD,
"system": ModuleKind.System,
@@ -87,7 +93,6 @@ namespace ts {
},
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
paramType: Diagnostics.KIND,
error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015
},
{
name: "newLine",
@@ -95,9 +100,8 @@ namespace ts {
"crlf": NewLineKind.CarriageReturnLineFeed,
"lf": NewLineKind.LineFeed
},
description: Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
paramType: Diagnostics.NEWLINE,
error: Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF
},
{
name: "noEmit",
@@ -118,6 +122,11 @@ namespace ts {
type: "boolean",
description: Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
},
{
name: "noImplicitThis",
type: "boolean",
description: Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
},
{
name: "noLib",
type: "boolean",
@@ -158,7 +167,6 @@ namespace ts {
},
{
name: "pretty",
paramType: Diagnostics.KIND,
description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental,
type: "boolean"
},
@@ -179,8 +187,8 @@ namespace ts {
name: "rootDir",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
paramType: Diagnostics.LOCATION,
description: Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
{
name: "isolatedModules",
@@ -195,7 +203,7 @@ namespace ts {
name: "sourceRoot",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
description: Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
paramType: Diagnostics.LOCATION,
},
{
@@ -224,9 +232,8 @@ namespace ts {
"es6": ScriptTarget.ES6,
"es2015": ScriptTarget.ES2015,
},
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental,
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
paramType: Diagnostics.VERSION,
error: Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES2015
},
{
name: "version",
@@ -257,8 +264,7 @@ namespace ts {
"node": ModuleResolutionKind.NodeJs,
"classic": ModuleResolutionKind.Classic,
},
description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
error: Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic,
description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
},
{
name: "allowUnusedLabels",
@@ -302,14 +308,41 @@ namespace ts {
// this option can only be specified in tsconfig.json
// use type = object to copy the value as-is
name: "rootDirs",
type: "object",
type: "list",
isTSConfigOnly: true,
isFilePath: true
element: {
name: "rootDirs",
type: "string",
isFilePath: true
}
},
{
name: "traceModuleResolution",
name: "typesSearchPaths",
type: "list",
isTSConfigOnly: true,
element: {
name: "typesSearchPaths",
type: "string",
isFilePath: true
}
},
{
name: "typesRoot",
type: "string"
},
{
name: "types",
type: "list",
element: {
name: "types",
type: "string"
},
description: Diagnostics.Type_declaration_files_to_be_included_in_compilation
},
{
name: "traceResolution",
type: "boolean",
description: Diagnostics.Enable_tracing_of_the_module_resolution_process
description: Diagnostics.Enable_tracing_of_the_name_resolution_process
},
{
name: "allowJs",
@@ -322,11 +355,79 @@ namespace ts {
description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
},
{
// this option will be removed when this is merged with master and exists solely
// to enable the tree transforming emitter side-by-side with the existing emitter.
name: "experimentalTransforms",
name: "noImplicitUseStrict",
type: "boolean",
experimental: true
description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
},
{
name: "useLegacyEmitter",
type: "boolean",
experimental: true,
description: Diagnostics.Use_the_legacy_emitter_instead_of_the_transforming_emitter
},
{
name: "listEmittedFiles",
type: "boolean"
},
{
name: "lib",
type: "list",
element: {
name: "lib",
type: {
// JavaScript only
"es5": "lib.es5.d.ts",
"es6": "lib.es2015.d.ts",
"es2015": "lib.es2015.d.ts",
"es7": "lib.es2016.d.ts",
"es2016": "lib.es2016.d.ts",
// Host only
"dom": "lib.dom.d.ts",
"webworker": "lib.webworker.d.ts",
"scripthost": "lib.scripthost.d.ts",
// ES2015 Or ESNext By-feature options
"es2015.core": "lib.es2015.core.d.ts",
"es2015.collection": "lib.es2015.collection.d.ts",
"es2015.generator": "lib.es2015.generator.d.ts",
"es2015.iterable": "lib.es2015.iterable.d.ts",
"es2015.promise": "lib.es2015.promise.d.ts",
"es2015.proxy": "lib.es2015.proxy.d.ts",
"es2015.reflect": "lib.es2015.reflect.d.ts",
"es2015.symbol": "lib.es2015.symbol.d.ts",
"es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts",
"es2016.array.include": "lib.es2016.array.include.d.ts"
},
},
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
},
{
name: "strictNullChecks",
type: "boolean",
description: Diagnostics.Enable_strict_null_checks
}
];
/* @internal */
export let typingOptionDeclarations: CommandLineOption[] = [
{
name: "enableAutoDiscovery",
type: "boolean",
},
{
name: "include",
type: "list",
element: {
name: "include",
type: "string"
}
},
{
name: "exclude",
type: "list",
element: {
name: "exclude",
type: "string"
}
}
];
@@ -337,6 +438,7 @@ namespace ts {
}
let optionNameMapCache: OptionNameMap;
/* @internal */
export function getOptionNameMap(): OptionNameMap {
if (optionNameMapCache) {
@@ -356,6 +458,42 @@ namespace ts {
return optionNameMapCache;
}
/* @internal */
export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic {
const namesOfType: string[] = [];
forEachKey(opt.type, key => {
namesOfType.push(` '${key}'`);
});
return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType);
}
/* @internal */
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = (value || "").trim().toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
return map[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
/* @internal */
export function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] {
const values = (value || "").trim().split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
case "string":
return ts.map(values, v => v || "");
default:
return filter(map(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v, errors)), v => !!v);
}
}
/* @internal */
export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine {
const options: CompilerOptions = {};
const fileNames: string[] = [];
@@ -409,17 +547,15 @@ namespace ts {
options[opt.name] = args[i] || "";
i++;
break;
case "list":
options[opt.name] = parseListTypeOption(<CommandLineOptionOfListType>opt, args[i], errors);
i++;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
let map = <Map<number>>opt.type;
let key = (args[i] || "").toLowerCase();
options[opt.name] = parseCustomTypeOption(<CommandLineOptionOfCustomType>opt, args[i], errors);
i++;
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
}
break;
}
}
}
@@ -497,7 +633,6 @@ namespace ts {
}
}
/**
* Remove the comments from a json like text.
* Comments can be single line comments (starting with # or //) or multiline comments using / * * /
@@ -531,20 +666,25 @@ namespace ts {
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string): ParsedCommandLine {
const { options: optionsFromJsonConfigFile, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName);
const errors: Diagnostic[] = [];
const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const options = extend(existingOptions, compilerOptions);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
options.configFilePath = configFileName;
const options = extend(existingOptions, optionsFromJsonConfigFile);
const fileNames = getFileNames(errors);
return {
options,
fileNames: getFileNames(),
fileNames,
typingOptions,
errors
};
function getFileNames(): string[] {
function getFileNames(errors: Diagnostic[]): string[] {
let fileNames: string[] = [];
if (hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
if (isArray(json["files"])) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
else {
@@ -553,7 +693,21 @@ namespace ts {
}
else {
const filesSeen: Map<boolean> = {};
const exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let exclude: string[] = [];
if (isArray(json["exclude"])) {
exclude = json["exclude"];
}
else {
// by default exclude node_modules, and any specificied output directory
exclude = ["node_modules"];
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
}
}
exclude = map(exclude, normalizeSlashes);
const supportedExtensions = getSupportedExtensions(options);
Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick");
@@ -567,6 +721,11 @@ namespace ts {
continue;
}
// Skip over any minified JavaScript files (ending in ".min.js")
if (/\.min\.js$/.test(fileName)) {
continue;
}
// If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files)
// do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation
if (extension === ".d.ts" || (options.allowJs && contains(supportedJavascriptExtensions, extension))) {
@@ -581,21 +740,48 @@ namespace ts {
}
}
}
if (hasProperty(json, "excludes") && !hasProperty(json, "exclude")) {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
return fileNames;
}
}
export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
const options: CompilerOptions = {};
const errors: Diagnostic[] = [];
const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
if (configFileName && getBaseFileName(configFileName) === "jsconfig.json") {
options.module = ModuleKind.CommonJS;
options.allowJs = true;
}
export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
const errors: Diagnostic[] = [];
const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
function convertCompilerOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions {
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {};
convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
function convertTypingOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions {
const options: TypingOptions = getBaseFileName(configFileName) === "jsconfig.json"
? { enableAutoDiscovery: true, include: [], exclude: [] }
: { enableAutoDiscovery: false, include: [], exclude: [] };
convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors);
return options;
}
function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
if (!jsonOptions) {
return { options, errors };
return ;
}
const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name);
@@ -603,66 +789,50 @@ namespace ts {
for (const id in jsonOptions) {
if (hasProperty(optionNameMap, id)) {
const opt = optionNameMap[id];
const optType = opt.type;
let value = jsonOptions[id];
const expectedType = typeof optType === "string" ? optType : "string";
if (typeof value === expectedType) {
if (typeof optType !== "string") {
const key = value.toLowerCase();
if (hasProperty(optType, key)) {
value = optType[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
value = 0;
}
}
if (opt.isFilePath) {
switch (typeof value) {
case "string":
value = normalizePath(combinePaths(basePath, value));
break;
case "object":
// "object" options with 'isFilePath' = true expected to be string arrays
let paths: string[] = [];
let invalidOptionType = false;
if (!isArray(value)) {
invalidOptionType = true;
}
else {
for (const element of <any[]>value) {
if (typeof element === "string") {
paths.push(normalizePath(combinePaths(basePath, element)));
}
else {
invalidOptionType = true;
break;
}
}
}
if (invalidOptionType) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name));
}
else {
value = paths;
}
break;
}
if (value === "") {
value = ".";
}
}
options[opt.name] = value;
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType));
}
defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, id));
errors.push(createCompilerDiagnostic(diagnosticMessage, id));
}
}
}
return { options, errors };
function convertJsonOption(opt: CommandLineOption, value: any, basePath: string, errors: Diagnostic[]): CompilerOptionsValue {
const optType = opt.type;
const expectedType = typeof optType === "string" ? optType : "string";
if (optType === "list" && isArray(value)) {
return convertJsonOptionOfListType(<CommandLineOptionOfListType>opt, value, basePath, errors);
}
else if (typeof value === expectedType) {
if (typeof optType !== "string") {
return convertJsonOptionOfCustomType(<CommandLineOptionOfCustomType>opt, value, errors);
}
else {
if (opt.isFilePath) {
value = normalizePath(combinePaths(basePath, value));
if (value === "") {
value = ".";
}
}
}
return value;
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType));
}
}
function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = value.toLowerCase();
if (hasProperty(opt.type, key)) {
return opt.type[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: any[], basePath: string, errors: Diagnostic[]): any[] {
return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v);
}
}
+101 -40
View File
@@ -5,15 +5,19 @@ namespace ts {
export interface CommentWriter {
reset(): void;
setSourceFile(sourceFile: SourceFile): void;
getLeadingComments(range: Node, getAdditionalRange?: (range: Node) => Node): CommentRange[];
getLeadingComments(range: TextRange): CommentRange[];
getLeadingComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (contextNode: Node) => boolean, getTextRangeCallback: (contextNode: Node) => TextRange): CommentRange[];
getLeadingCommentsOfPosition(pos: number): CommentRange[];
getTrailingComments(range: Node, getAdditionalRange?: (range: Node) => Node): CommentRange[];
getTrailingComments(range: TextRange): CommentRange[];
getTrailingComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (contextNode: Node) => boolean, getTextRangeCallback: (contextNode: Node) => TextRange): CommentRange[];
getTrailingCommentsOfPosition(pos: number): CommentRange[];
emitLeadingComments(range: TextRange, comments?: CommentRange[]): void;
emitTrailingComments(range: TextRange, comments?: CommentRange[]): void;
emitDetachedComments(range: TextRange): void;
emitLeadingComments(range: TextRange, comments: CommentRange[]): void;
emitLeadingComments(range: TextRange, comments: CommentRange[], contextNode: Node, getTextRangeCallback: (contextNode: Node) => TextRange): void;
emitTrailingComments(range: TextRange, comments: CommentRange[]): void;
emitLeadingDetachedComments(range: TextRange): void;
emitLeadingDetachedComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (contextNode: Node) => boolean): void;
emitTrailingDetachedComments(range: TextRange): void;
emitTrailingDetachedComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (contextNode: Node) => boolean): void;
}
export function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter {
@@ -40,16 +44,21 @@ namespace ts {
return {
reset,
setSourceFile,
getLeadingComments(range: TextRange, getAdditionalRange?: (range: TextRange) => TextRange): CommentRange[] { return undefined; },
getLeadingComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (contextNode: Node) => boolean, getTextRangeCallback?: (contextNode: Node) => TextRange): CommentRange[] { return undefined; },
getLeadingCommentsOfPosition(pos: number): CommentRange[] { return undefined; },
getTrailingComments(range: TextRange, getAdditionalRange?: (range: TextRange) => TextRange): CommentRange[] { return undefined; },
getTrailingComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (contextNode: Node) => boolean, getTextRangeCallback?: (contextNode: Node) => TextRange): CommentRange[] { return undefined; },
getTrailingCommentsOfPosition(pos: number): CommentRange[] { return undefined; },
emitLeadingComments(range: TextRange, comments?: CommentRange[]): void { },
emitTrailingComments(range: TextRange, comments?: CommentRange[]): void { },
emitDetachedComments,
emitLeadingComments(range: TextRange, comments: CommentRange[], contextNode?: Node, getTextRangeCallback?: (contextNode: Node) => TextRange): void { },
emitTrailingComments(range: TextRange, comments: CommentRange[]): void { },
emitLeadingDetachedComments,
emitTrailingDetachedComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (contextNode: Node) => boolean): void {}
};
function emitDetachedComments(node: TextRange): void {
function emitLeadingDetachedComments(node: TextRange, contextNode?: Node, ignoreNodeCallback?: (contextNode: Node) => boolean): void {
if (ignoreNodeCallback && ignoreNodeCallback(contextNode)) {
return;
}
emitDetachedCommentsAndUpdateCommentsInfo(node, /*removeComments*/ true);
}
}
@@ -65,41 +74,68 @@ namespace ts {
getTrailingCommentsOfPosition,
emitLeadingComments,
emitTrailingComments,
emitDetachedComments,
emitLeadingDetachedComments,
emitTrailingDetachedComments
};
function getLeadingComments(range: TextRange | Node, getAdditionalRange?: (range: Node) => Node) {
let comments = getLeadingCommentsOfPosition(range.pos);
if (getAdditionalRange) {
let additionalRange = getAdditionalRange(<Node>range);
while (additionalRange) {
comments = concatenate(
getLeadingCommentsOfPosition(additionalRange.pos),
comments
);
function getLeadingComments(range: TextRange): CommentRange[];
function getLeadingComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (contextNode: Node) => boolean, getTextRangeCallback: (contextNode: Node) => TextRange): CommentRange[];
function getLeadingComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (contextNode: Node) => boolean, getTextRangeCallback?: (contextNode: Node) => TextRange) {
if (contextNode) {
range = getTextRangeCallback(contextNode) || range;
if (ignoreNodeCallback(contextNode)) {
// If the node will not be emitted in JS, remove all the comments (normal,
// pinned and `///`) associated with the node, unless it is a triple slash
// comment at the top of the file.
//
// For Example:
// /// <reference-path ...>
// declare var x;
// /// <reference-path ...>
// interface F {}
//
// The first `///` will NOT be removed while the second one will be removed
// even though both nodes will not be emitted.
if (range.pos === 0) {
return filter(getLeadingCommentsOfPosition(0), isTripleSlashComment);
}
additionalRange = getAdditionalRange(additionalRange);
return undefined;
}
}
return comments;
return getLeadingCommentsOfPosition(range.pos);
}
function getTrailingComments(range: TextRange | Node, getAdditionalRange?: (range: Node) => Node) {
let comments = getTrailingCommentsOfPosition(range.end);
if (getAdditionalRange) {
let additionalRange = getAdditionalRange(<Node>range);
while (additionalRange) {
comments = concatenate(
comments,
getTrailingCommentsOfPosition(additionalRange.end)
);
/**
* Determine if the given comment is a triple-slash
**/
function isTripleSlashComment(comment: CommentRange) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
if (currentText.charCodeAt(comment.pos + 1) === CharacterCodes.slash &&
comment.pos + 2 < comment.end &&
currentText.charCodeAt(comment.pos + 2) === CharacterCodes.slash) {
const textSubStr = currentText.substring(comment.pos, comment.end);
return fullTripleSlashReferencePathRegEx.test(textSubStr)
|| fullTripleSlashAMDReferencePathRegEx.test(textSubStr);
}
return false;
}
additionalRange = getAdditionalRange(additionalRange);
function getTrailingComments(range: TextRange): CommentRange[];
function getTrailingComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (contextNode: Node) => boolean, getTextRangeCallback: (contextNode: Node) => TextRange): CommentRange[];
function getTrailingComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (contextNode: Node) => boolean, getTextRangeCallback?: (contextNode: Node) => TextRange) {
if (contextNode) {
if (ignoreNodeCallback(contextNode)) {
return undefined;
}
range = getTextRangeCallback(contextNode) || range;
}
return comments;
return getTrailingCommentsOfPosition(range.end);
}
function getLeadingCommentsOfPosition(pos: number) {
@@ -124,22 +160,47 @@ namespace ts {
return consumeCommentRanges(comments);
}
function emitLeadingComments(range: TextRange, comments = getLeadingComments(range)) {
emitNewLineBeforeLeadingComments(currentLineMap, writer, range, comments);
function emitLeadingComments(range: TextRange, comments: CommentRange[]): void;
function emitLeadingComments(range: TextRange, comments: CommentRange[], contextNode: Node, getTextRangeCallback: (contextNode: Node) => TextRange): void;
function emitLeadingComments(range: TextRange, comments: CommentRange[], contextNode?: Node, getTextRangeCallback?: (contextNode: Node) => TextRange) {
if (comments && comments.length > 0) {
if (contextNode) {
range = getTextRangeCallback(contextNode) || range;
}
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentText, currentLineMap, writer, comments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
emitNewLineBeforeLeadingComments(currentLineMap, writer, range, comments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentText, currentLineMap, writer, comments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
}
}
function emitTrailingComments(range: TextRange, comments = getTrailingComments(range)) {
function emitTrailingComments(range: TextRange, comments: CommentRange[]) {
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentText, currentLineMap, writer, comments, /*leadingSeparator*/ true, /*trailingSeparator*/ false, newLine, writeComment);
}
function emitDetachedComments(range: TextRange) {
function emitLeadingDetachedComments(range: TextRange): void;
function emitLeadingDetachedComments(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean): void;
function emitLeadingDetachedComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean): void {
if (contextNode && ignoreNodeCallback(contextNode)) {
return;
}
emitDetachedCommentsAndUpdateCommentsInfo(range, /*removeComments*/ false);
}
function emitTrailingDetachedComments(range: TextRange): void;
function emitTrailingDetachedComments(range: TextRange, contextNode: Node, ignoreNodeCallback?: (node: Node) => boolean): void;
function emitTrailingDetachedComments(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean): void {
if (contextNode && ignoreNodeCallback(contextNode)) {
return;
}
range = collapseRangeToEnd(range);
emitLeadingComments(range, getLeadingComments(range));
}
function hasConsumedCommentRange(comment: CommentRange) {
return comment.end === consumedCommentRanges[comment.pos];
}
+69 -8
View File
@@ -244,7 +244,7 @@ namespace ts {
* @param keyfn A callback used to select the key for an element.
* @param mapfn A callback used to map a contiguous chunk of values to a single value.
*/
export function spanMap<T, K, U>(array: T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K) => U): U[] {
export function spanMap<T, K, U>(array: T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] {
let result: U[];
if (array) {
result = [];
@@ -268,7 +268,7 @@ namespace ts {
}
if (start < pos) {
const v = mapfn(array.slice(start, pos), previousKey);
const v = mapfn(array.slice(start, pos), previousKey, start, pos);
if (v) {
result.push(v);
}
@@ -362,6 +362,12 @@ namespace ts {
: undefined;
}
export function singleOrMany<T>(array: T[]): T | T[] {
return array && array.length === 1
? array[0]
: array;
}
/**
* Returns the last element of an array if non-empty, undefined otherwise.
*/
@@ -458,6 +464,14 @@ namespace ts {
return hasOwnProperty.call(map, key);
}
export function getKeys<T>(map: Map<T>): string[] {
const keys: string[] = [];
for (const key in map) {
keys.push(key);
}
return keys;
}
export function getProperty<T>(map: Map<T>, key: string): T {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
}
@@ -847,7 +861,7 @@ namespace ts {
}
function getNormalizedPathComponentsOfUrl(url: string) {
// Get root length of http://www.website.com/folder1/foler2/
// Get root length of http://www.website.com/folder1/folder2/
// In this example the root is: http://www.website.com/
// normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
@@ -875,7 +889,7 @@ namespace ts {
const indexOfNextSlash = url.indexOf(directorySeparator, rootLength);
if (indexOfNextSlash !== -1) {
// Found the "/" after the website.com so the root is length of http://www.website.com/
// and get components afetr the root normally like any other folder components
// and get components after the root normally like any other folder components
rootLength = indexOfNextSlash + 1;
return normalizedPathComponents(url, rootLength);
}
@@ -958,6 +972,32 @@ namespace ts {
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
export function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind {
// Using scriptKind as a condition handles both:
// - 'scriptKind' is unspecified and thus it is `undefined`
// - 'scriptKind' is set and it is `Unknown` (0)
// If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
// to get the ScriptKind from the file name. If it cannot be resolved
// from the file name then the default 'TS' script kind is returned.
return (scriptKind || getScriptKindFromFileName(fileName)) || ScriptKind.TS;
}
export function getScriptKindFromFileName(fileName: string): ScriptKind {
const ext = fileName.substr(fileName.lastIndexOf("."));
switch (ext.toLowerCase()) {
case ".js":
return ScriptKind.JS;
case ".jsx":
return ScriptKind.JSX;
case ".ts":
return ScriptKind.TS;
case ".tsx":
return ScriptKind.TSX;
default:
return ScriptKind.Unknown;
}
}
/**
* List of supported extensions in order of file resolution precedence.
*/
@@ -1016,8 +1056,9 @@ namespace ts {
this.pos = pos;
this.end = end;
this.flags = NodeFlags.None;
this.transformFlags = undefined;
this.excludeTransformFlags = undefined;
this.modifierFlagsCache = ModifierFlags.None;
this.transformFlags = TransformFlags.None;
this.excludeTransformFlags = TransformFlags.None;
this.parent = undefined;
this.original = undefined;
}
@@ -1038,10 +1079,13 @@ namespace ts {
}
export namespace Debug {
const currentAssertionLevel = AssertionLevel.None;
declare var process: any;
declare var require: any;
let currentAssertionLevel: AssertionLevel;
export function shouldAssert(level: AssertionLevel): boolean {
return currentAssertionLevel >= level;
return getCurrentAssertionLevel() >= level;
}
export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void {
@@ -1058,6 +1102,23 @@ namespace ts {
export function fail(message?: string): void {
Debug.assert(/*expression*/ false, message);
}
function getCurrentAssertionLevel() {
if (currentAssertionLevel !== undefined) {
return currentAssertionLevel;
}
if (sys === undefined) {
return AssertionLevel.None;
}
const developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV"));
currentAssertionLevel = developmentMode
? AssertionLevel.Normal
: AssertionLevel.None;
return currentAssertionLevel;
}
}
export function copyListRemovingItem<T>(item: T, list: T[]) {
+141 -107
View File
@@ -15,10 +15,10 @@ namespace ts {
reportedDeclarationError: boolean;
moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[];
synchronousDeclarationOutput: string;
referencePathsOutput: string;
referencesOutput: string;
}
type GetSymbolAccessibilityDiagnostic = (symbolAccesibilityResult: SymbolAccessiblityResult) => SymbolAccessibilityDiagnostic;
type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic;
interface EmitTextWriterWithSymbolWriter extends EmitTextWriter, SymbolWriter {
getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic;
@@ -33,9 +33,9 @@ namespace ts {
export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {
const declarationDiagnostics = createDiagnosticCollection();
forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName);
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {
function getDeclarationDiagnosticsFromFile({ declarationFilePath }: EmitFileNames, sources: SourceFile[], isBundledEmit: boolean) {
emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
@@ -51,7 +51,9 @@ namespace ts {
let decreaseIndent: () => void;
let writeTextOfNode: (text: string, node: Node) => void;
let writer = createAndSetNewTextWriterWithSymbolWriter();
let writer: EmitTextWriterWithSymbolWriter;
createAndSetNewTextWriterWithSymbolWriter();
let enclosingDeclaration: Node;
let resultHasExternalModuleIndicator: boolean;
@@ -71,7 +73,9 @@ namespace ts {
// Contains the reference paths that needs to go in the declaration file.
// Collecting this separately because reference paths need to be first thing in the declaration file
// and we could be collecting these paths from multiple files into single one with --out option
let referencePathsOutput = "";
let referencesOutput = "";
let usedTypeDirectiveReferences: Map<string>;
// Emit references corresponding to each file
const emittedReferencedFiles: SourceFile[] = [];
@@ -151,11 +155,19 @@ namespace ts {
}
});
if (usedTypeDirectiveReferences) {
for (const directive in usedTypeDirectiveReferences) {
if (hasProperty(usedTypeDirectiveReferences, directive)) {
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
}
}
}
return {
reportedDeclarationError,
moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo,
synchronousDeclarationOutput: writer.getText(),
referencePathsOutput,
referencesOutput,
};
function hasInternalAnnotation(range: CommentRange) {
@@ -174,7 +186,7 @@ namespace ts {
}
}
function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter {
function createAndSetNewTextWriterWithSymbolWriter(): void {
const writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine);
writer.trackSymbol = trackSymbol;
writer.reportInaccessibleThisError = reportInaccessibleThisError;
@@ -186,7 +198,6 @@ namespace ts {
writer.writeParameter = writer.write;
writer.writeSymbol = writer.write;
setWriter(writer);
return writer;
}
function setWriter(newWriter: EmitTextWriterWithSymbolWriter) {
@@ -252,30 +263,45 @@ namespace ts {
setWriter(oldWriter);
}
function handleSymbolAccessibilityError(symbolAccesibilityResult: SymbolAccessiblityResult) {
if (symbolAccesibilityResult.accessibility === SymbolAccessibility.Accessible) {
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[]): void {
if (!typeReferenceDirectives) {
return;
}
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = {};
}
for (const directive of typeReferenceDirectives) {
if (!hasProperty(usedTypeDirectiveReferences, directive)) {
usedTypeDirectiveReferences[directive] = directive;
}
}
}
function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) {
// write the aliases
if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) {
writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible);
if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible);
}
}
else {
// Report error
reportedDeclarationError = true;
const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult);
const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
if (errorInfo) {
if (errorInfo.typeName) {
emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
getTextOfNodeFromSourceText(currentText, errorInfo.typeName),
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
symbolAccessibilityResult.errorSymbolName,
symbolAccessibilityResult.errorModuleName));
}
else {
emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
symbolAccessibilityResult.errorSymbolName,
symbolAccessibilityResult.errorModuleName));
}
}
}
@@ -283,6 +309,7 @@ namespace ts {
function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
function reportInaccessibleThisError() {
@@ -366,6 +393,8 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.StringLiteralType:
return writeTextOfNode(currentText, type);
@@ -417,6 +446,7 @@ namespace ts {
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
handleSymbolAccessibilityError(visibilityResult);
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
writeEntityName(entityName);
}
@@ -527,7 +557,10 @@ namespace ts {
else {
// Expression
const tempVarName = getExportDefaultTempVariableName();
write("declare var ");
if (!noDeclare) {
write("declare ");
}
write("var ");
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
@@ -548,7 +581,7 @@ namespace ts {
writeAsynchronousModuleElements(nodes);
}
function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getDefaultExportAccessibilityDiagnostic(diagnostic: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
errorNode: node
@@ -623,12 +656,13 @@ namespace ts {
function emitModuleElementDeclarationFlags(node: Node) {
// If the node is parented in the current source file we need to emit export declare or just export
if (node.parent.kind === SyntaxKind.SourceFile) {
const modifiers = getModifierFlags(node);
// If the node is exported
if (node.flags & NodeFlags.Export) {
if (modifiers & ModifierFlags.Export) {
write("export ");
}
if (node.flags & NodeFlags.Default) {
if (modifiers & ModifierFlags.Default) {
write("default ");
}
else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) {
@@ -637,21 +671,21 @@ namespace ts {
}
}
function emitClassMemberDeclarationFlags(flags: NodeFlags) {
if (flags & NodeFlags.Private) {
function emitClassMemberDeclarationFlags(flags: ModifierFlags) {
if (flags & ModifierFlags.Private) {
write("private ");
}
else if (flags & NodeFlags.Protected) {
else if (flags & ModifierFlags.Protected) {
write("protected ");
}
if (flags & NodeFlags.Static) {
if (flags & ModifierFlags.Static) {
write("static ");
}
if (flags & NodeFlags.Readonly) {
if (flags & ModifierFlags.Readonly) {
write("readonly ");
}
if (flags & NodeFlags.Abstract) {
if (flags & ModifierFlags.Abstract) {
write("abstract ");
}
}
@@ -660,7 +694,7 @@ namespace ts {
// note usage of writer. methods instead of aliases created, just to make sure we are using
// correct writer especially to handle asynchronous alias writing
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
if (hasModifier(node, ModifierFlags.Export)) {
write("export ");
}
write("import ");
@@ -677,7 +711,7 @@ namespace ts {
}
writer.writeLine();
function getImportEntityNameVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getImportEntityNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1,
errorNode: node,
@@ -698,12 +732,8 @@ namespace ts {
}
function writeImportDeclaration(node: ImportDeclaration) {
if (!node.importClause && !(node.flags & NodeFlags.Export)) {
// do not write non-exported import declarations that don't have import clauses
return;
}
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
if (hasModifier(node, ModifierFlags.Export)) {
write("export ");
}
write("import ");
@@ -737,7 +767,7 @@ namespace ts {
function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration) {
// emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations).
// the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered
// external modules since they are indistingushable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}'
// external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}'
// so compiler will treat them as external modules.
resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration;
let moduleSpecifier: Node;
@@ -756,9 +786,9 @@ namespace ts {
if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) {
const moduleName = getExternalModuleNameFromDeclaration(host, resolver, parent);
if (moduleName) {
write("\"");
write('"');
write(moduleName);
write("\"");
write('"');
return;
}
}
@@ -854,7 +884,7 @@ namespace ts {
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
return {
diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
errorNode: node.type,
@@ -893,7 +923,7 @@ namespace ts {
}
function isPrivateMethodTypeParameter(node: TypeParameterDeclaration) {
return node.parent.kind === SyntaxKind.MethodDeclaration && (node.parent.flags & NodeFlags.Private);
return node.parent.kind === SyntaxKind.MethodDeclaration && hasModifier(node.parent, ModifierFlags.Private);
}
function emitTypeParameters(typeParameters: TypeParameterDeclaration[]) {
@@ -921,7 +951,7 @@ namespace ts {
}
}
function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getTypeParameterConstraintVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
// Type parameter constraints are named by user so we should always be able to name it
let diagnosticMessage: DiagnosticMessage;
switch (node.parent.kind) {
@@ -943,7 +973,7 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.parent.flags & NodeFlags.Static) {
if (hasModifier(node.parent, ModifierFlags.Static)) {
diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
}
else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
@@ -990,8 +1020,12 @@ namespace ts {
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
write("null");
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
resolver.writeBaseConstructorTypeOfClass(<ClassLikeDeclaration>enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
}
function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getHeritageClauseVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
// Heritage clause is written by user so it can always be named
if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
@@ -1018,7 +1052,7 @@ namespace ts {
function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) {
if (constructorDeclaration) {
forEach(constructorDeclaration.parameters, param => {
if (param.flags & NodeFlags.AccessibilityModifier) {
if (hasModifier(param, ModifierFlags.AccessibilityModifier)) {
emitPropertyDeclaration(param);
}
});
@@ -1027,7 +1061,7 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (node.flags & NodeFlags.Abstract) {
if (hasModifier(node, ModifierFlags.Abstract)) {
write("abstract ");
}
@@ -1077,7 +1111,7 @@ namespace ts {
}
emitJsDocComments(node);
emitClassMemberDeclarationFlags(node.flags);
emitClassMemberDeclarationFlags(getModifierFlags(node));
emitVariableDeclaration(<VariableDeclaration>node);
write(";");
writeLine();
@@ -1102,16 +1136,16 @@ namespace ts {
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!(node.flags & NodeFlags.Private)) {
else if (!hasModifier(node, ModifierFlags.Private)) {
writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError);
}
}
}
function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult) {
function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (node.kind === SyntaxKind.VariableDeclaration) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
@@ -1119,31 +1153,31 @@ namespace ts {
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (node.flags & NodeFlags.Static) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
if (hasModifier(node, ModifierFlags.Static)) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
}
else if (node.parent.kind === SyntaxKind.ClassDeclaration) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
}
else {
// Interfaces cannot have types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
}
}
}
function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult);
function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
errorNode: node,
@@ -1167,8 +1201,8 @@ namespace ts {
}
function emitBindingElement(bindingElement: BindingElement) {
function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult);
function getBindingElementTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
errorNode: bindingElement,
@@ -1230,9 +1264,9 @@ namespace ts {
if (node === accessors.firstAccessor) {
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : NodeFlags.Readonly));
emitClassMemberDeclarationFlags(getModifierFlags(node) | (accessors.setAccessor ? 0 : ModifierFlags.Readonly));
writeTextOfNode(currentText, node.name);
if (!(node.flags & NodeFlags.Private)) {
if (!hasModifier(node, ModifierFlags.Private)) {
accessorWithTypeAnnotation = node;
let type = getTypeAnnotationFromAccessor(node);
if (!type) {
@@ -1259,17 +1293,17 @@ namespace ts {
}
}
function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) {
// Setters have to have type named and cannot infer it so, the type should always be named
if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
if (hasModifier(accessorWithTypeAnnotation.parent, 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;
}
else {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1;
}
@@ -1281,16 +1315,16 @@ namespace ts {
};
}
else {
if (accessorWithTypeAnnotation.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
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;
}
else {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0;
@@ -1316,8 +1350,8 @@ namespace ts {
if (node.kind === SyntaxKind.FunctionDeclaration) {
emitModuleElementDeclarationFlags(node);
}
else if (node.kind === SyntaxKind.MethodDeclaration) {
emitClassMemberDeclarationFlags(node.flags);
else if (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.Constructor) {
emitClassMemberDeclarationFlags(getModifierFlags(node));
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
write("function ");
@@ -1347,7 +1381,7 @@ namespace ts {
if (node.kind === SyntaxKind.IndexSignature) {
// Index signature can have readonly modifier
emitClassMemberDeclarationFlags(node.flags);
emitClassMemberDeclarationFlags(getModifierFlags(node));
write("[");
}
else {
@@ -1378,7 +1412,7 @@ namespace ts {
emitType(node.type);
}
}
else if (node.kind !== SyntaxKind.Constructor && !(node.flags & NodeFlags.Private)) {
else if (node.kind !== SyntaxKind.Constructor && !hasModifier(node, ModifierFlags.Private)) {
writeReturnTypeAtSignature(node, getReturnTypeVisibilityError);
}
@@ -1389,57 +1423,57 @@ namespace ts {
writeLine();
}
function getReturnTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
switch (node.kind) {
case SyntaxKind.ConstructSignature:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
case SyntaxKind.CallSignature:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
case SyntaxKind.IndexSignature:
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
break;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
if (hasModifier(node, ModifierFlags.Static)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
}
else if (node.parent.kind === SyntaxKind.ClassDeclaration) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
}
else {
// Interfaces cannot have return types that cannot be named
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
}
break;
case SyntaxKind.FunctionDeclaration:
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
@@ -1481,12 +1515,12 @@ namespace ts {
node.parent.parent.kind === SyntaxKind.TypeLiteral) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!(node.parent.flags & NodeFlags.Private)) {
else if (!hasModifier(node.parent, ModifierFlags.Private)) {
writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError);
}
function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult);
function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
return diagnosticMessage !== undefined ? {
diagnosticMessage,
errorNode: node,
@@ -1494,53 +1528,53 @@ namespace ts {
} : undefined;
}
function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult: SymbolAccessiblityResult): DiagnosticMessage {
function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult): DiagnosticMessage {
switch (node.parent.kind) {
case SyntaxKind.Constructor:
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
case SyntaxKind.ConstructSignature:
// Interfaces cannot have parameter types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
case SyntaxKind.CallSignature:
// Interfaces cannot have parameter types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.parent.flags & NodeFlags.Static) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
if (hasModifier(node.parent, ModifierFlags.Static)) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
}
else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
}
else {
// Interfaces cannot have parameter types that cannot be named
return symbolAccesibilityResult.errorModuleName ?
return symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
}
case SyntaxKind.FunctionDeclaration:
return symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
@@ -1682,7 +1716,7 @@ namespace ts {
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ false);
referencePathsOutput += "/// <reference path=\"" + declFileName + "\" />" + newLine;
referencesOutput += `/// <reference path="${declFileName}" />${newLine}`;
}
return addedBundledEmitReference;
@@ -1704,7 +1738,7 @@ namespace ts {
const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
const declarationOutput = emitDeclarationResult.referencePathsOutput
const declarationOutput = emitDeclarationResult.referencesOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM);
}
+232 -56
View File
@@ -1,4 +1,4 @@
{
{
"Unterminated string literal.": {
"category": "Error",
"code": 1002
@@ -447,7 +447,7 @@
"category": "Error",
"code": 1147
},
"Cannot compile modules unless the '--module' flag is provided. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"category": "Error",
"code": 1148
},
@@ -687,7 +687,7 @@
"category": "Error",
"code": 1218
},
"Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": {
"Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.": {
"category": "Error",
"code": 1219
},
@@ -723,6 +723,10 @@
"category": "Error",
"code": 1227
},
"A type predicate is only allowed in return type position for functions and methods.": {
"category": "Error",
"code": 1228
},
"A type predicate cannot reference a rest parameter.": {
"category": "Error",
"code": 1229
@@ -775,7 +779,7 @@
"category": "Error",
"code": 1241
},
"'abstract' modifier can only appear on a class or method declaration.": {
"'abstract' modifier can only appear on a class, method, or property declaration.": {
"category": "Error",
"code": 1242
},
@@ -807,6 +811,18 @@
"category": "Error",
"code": 1249
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'.": {
"category": "Error",
"code": 1250
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode.": {
"category": "Error",
"code": 1251
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode.": {
"category": "Error",
"code": 1252
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
@@ -827,6 +843,18 @@
"category": "Error",
"code": 1313
},
"Global module exports may only appear in module files.": {
"category": "Error",
"code": 1314
},
"Global module exports may only appear in declaration files.": {
"category": "Error",
"code": 1315
},
"Global module exports may only appear at top level.": {
"category": "Error",
"code": 1316
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -1031,7 +1059,7 @@
"category": "Error",
"code": 2351
},
"Neither type '{0}' nor type '{1}' is assignable to the other.": {
"Type '{0}' cannot be converted to type '{1}'.": {
"category": "Error",
"code": 2352
},
@@ -1087,6 +1115,10 @@
"category": "Error",
"code": 2365
},
"Function lacks ending return statement and return type does not include 'undefined'.": {
"category": "Error",
"code": 2366
},
"Type parameter name cannot be '{0}'": {
"category": "Error",
"code": 2368
@@ -1147,7 +1179,7 @@
"category": "Error",
"code": 2382
},
"Overload signatures must all be exported or not exported.": {
"Overload signatures must all be exported or non-exported.": {
"category": "Error",
"code": 2383
},
@@ -1307,7 +1339,7 @@
"category": "Error",
"code": 2427
},
"All declarations of an interface must have identical type parameters.": {
"All declarations of '{0}' must have identical type parameters.": {
"category": "Error",
"code": 2428
},
@@ -1407,6 +1439,10 @@
"category": "Error",
"code": 2453
},
"Variable '{0}' is used before being assigned.": {
"category": "Error",
"code": 2454
},
"Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'.": {
"category": "Error",
"code": 2455
@@ -1631,7 +1667,7 @@
"category": "Error",
"code": 2511
},
"Overload signatures must all be abstract or not abstract.": {
"Overload signatures must all be abstract or non-abstract.": {
"category": "Error",
"code": 2512
},
@@ -1699,6 +1735,14 @@
"category": "Error",
"code": 2529
},
"Property '{0}' is incompatible with index signature.": {
"category": "Error",
"code": 2530
},
"Object is possibly 'null' or 'undefined'.": {
"category": "Error",
"code": 2531
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -1775,7 +1819,7 @@
"category": "Error",
"code": 2660
},
"Cannot re-export name that is not defined in the module.": {
"Cannot export '{0}'. Only local declarations can be exported from a module.": {
"category": "Error",
"code": 2661
},
@@ -1819,6 +1863,62 @@
"category": "Error",
"code": 2671
},
"Cannot assign a '{0}' constructor type to a '{1}' constructor type.": {
"category": "Error",
"code": 2672
},
"Constructor of class '{0}' is private and only accessible within the class declaration.": {
"category": "Error",
"code": 2673
},
"Constructor of class '{0}' is protected and only accessible within the class declaration.": {
"category": "Error",
"code": 2674
},
"Cannot extend a class '{0}'. Class constructor is marked as private.": {
"category": "Error",
"code": 2675
},
"Accessors must both be abstract or non-abstract.": {
"category": "Error",
"code": 2676
},
"A type predicate's type must be assignable to its parameter's type.": {
"category": "Error",
"code": 2677
},
"Type '{0}' is not comparable to type '{1}'.": {
"category": "Error",
"code": 2678
},
"A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'.": {
"category": "Error",
"code": 2679
},
"A 'this' parameter must be the first parameter.": {
"category": "Error",
"code": 2680
},
"A constructor cannot have a 'this' parameter.": {
"category": "Error",
"code": 2681
},
"A setter cannot have a 'this' parameter.": {
"category": "Error",
"code": 2682
},
"'this' implicitly has type 'any' because it does not have a type annotation.": {
"category": "Error",
"code": 2683
},
"The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'.": {
"category": "Error",
"code": 2684
},
"The 'this' types of each signature are incompatible.": {
"category": "Error",
"code": 2685
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2099,6 +2199,11 @@
"category": "Error",
"code": 4082
},
"Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict.": {
"category": "Message",
"code": 4090
},
"The current host does not support the '{0}' option.": {
"category": "Error",
"code": 5001
@@ -2187,6 +2292,14 @@
"category": "Error",
"code": 5062
},
"Substututions for pattern '{0}' should be an array.": {
"category": "Error",
"code": 5063
},
"Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'.": {
"category": "Error",
"code": 5064
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@@ -2195,11 +2308,11 @@
"category": "Message",
"code": 6002
},
"Specifies the location where debugger should locate map files instead of generated locations.": {
"Specify the location where debugger should locate map files instead of generated locations.": {
"category": "Message",
"code": 6003
},
"Specifies the location where debugger should locate TypeScript files instead of source locations.": {
"Specify the location where debugger should locate TypeScript files instead of source locations.": {
"category": "Message",
"code": 6004
},
@@ -2231,10 +2344,10 @@
"category": "Message",
"code": 6011
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": {
"category": "Message",
"code": 6015
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": {
"category": "Message",
"code": 6015
},
"Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'": {
"category": "Message",
"code": 6016
@@ -2319,14 +2432,10 @@
"category": "Error",
"code": 6045
},
"Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'.": {
"Argument for '{0}' option must be: {1}": {
"category": "Error",
"code": 6046
},
"Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.": {
"category": "Error",
"code": 6047
},
"Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'.": {
"category": "Error",
"code": 6048
@@ -2363,7 +2472,7 @@
"category": "Message",
"code": 6056
},
"Specifies the root directory of input files. Use to control the output directory structure with --outDir.": {
"Specify the root directory of input files. Use to control the output directory structure with --outDir.": {
"category": "Message",
"code": 6058
},
@@ -2371,7 +2480,7 @@
"category": "Error",
"code": 6059
},
"Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"category": "Message",
"code": 6060
},
@@ -2379,14 +2488,6 @@
"category": "Message",
"code": 6061
},
"Argument for '--newLine' option must be 'CRLF' or 'LF'.": {
"category": "Error",
"code": 6062
},
"Argument for '--moduleResolution' option must be 'node' or 'classic'.": {
"category": "Error",
"code": 6063
},
"Option '{0}' can only be specified in 'tsconfig.json' file.": {
"category": "Error",
"code": 6064
@@ -2403,7 +2504,7 @@
"category": "Message",
"code": 6068
},
"Specifies module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"category": "Message",
"code": 6069
},
@@ -2443,14 +2544,14 @@
"category": "Message",
"code": 6078
},
"Specify library files to be included in the compilation: ": {
"category": "Message",
"code": 6079
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
},
"Argument for '--jsx' must be 'preserve' or 'react'.": {
"category": "Message",
"code": 6081
},
"Only 'amd' and 'system' modules are supported alongside --{0}.": {
"category": "Error",
"code": 6082
@@ -2459,11 +2560,11 @@
"category": "Message",
"code": 6083
},
"Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit": {
"Specify the object invoked for createElement and __spread when targeting 'react' JSX emit": {
"category": "Message",
"code": 6084
},
"Enable tracing of the module resolution process.": {
"Enable tracing of the name resolution process.": {
"category": "Message",
"code": 6085
},
@@ -2511,7 +2612,7 @@
"category": "Message",
"code": 6096
},
"File '{0}' exist - use it as a module resolution result.": {
"File '{0}' exist - use it as a name resolution result.": {
"category": "Message",
"code": 6097
},
@@ -2523,11 +2624,11 @@
"category": "Message",
"code": 6099
},
"'package.json' does not have 'typings' field.": {
"'package.json' does not have 'types' field.": {
"category": "Message",
"code": 6100
},
"'package.json' has 'typings' field '{0}' that references '{1}'.": {
"'package.json' has '{0}' field '{1}' that references '{2}'.": {
"category": "Message",
"code": 6101
},
@@ -2543,7 +2644,7 @@
"category": "Message",
"code": 6104
},
"Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'.": {
"Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.": {
"category": "Message",
"code": 6105
},
@@ -2571,6 +2672,78 @@
"category": "Message",
"code": 6111
},
"Do not emit 'use strict' directives in module output.": {
"category": "Message",
"code": 6112
},
"Enable strict null checks.": {
"category": "Message",
"code": 6113
},
"Unknown option 'excludes'. Did you mean 'exclude'?": {
"category": "Error",
"code": 6114
},
"Raise error on 'this' expressions with an implied 'any' type.": {
"category": "Message",
"code": 6115
},
"======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========": {
"category": "Message",
"code": 6116
},
"Resolving using primary search paths...": {
"category": "Message",
"code": 6117
},
"Resolving from node_modules folder...": {
"category": "Message",
"code": 6118
},
"======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========": {
"category": "Message",
"code": 6119
},
"======== Type reference directive '{0}' was not resolved. ========": {
"category": "Message",
"code": 6120
},
"Resolving with primary search path '{0}'": {
"category": "Message",
"code": 6121
},
"Root directory cannot be determined, skipping primary search paths.": {
"category": "Message",
"code": 6122
},
"======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========": {
"category": "Message",
"code": 6123
},
"Type declaration files to be included in compilation.": {
"category": "Message",
"code": 6124
},
"Looking up in 'node_modules' folder, initial location '{0}'": {
"category": "Message",
"code": 6125
},
"Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder.": {
"category": "Message",
"code": 6126
},
"======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========": {
"category": "Message",
"code": 6127
},
"======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========": {
"category": "Message",
"code": 6128
},
"Use the legacy emitter instead of the transforming emitter.": {
"category": "Message",
"code": 6129
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2659,6 +2832,10 @@
"category": "Error",
"code": 7030
},
"Binding element '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7031
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@@ -2723,11 +2900,6 @@
"category": "Error",
"code": 8016
},
"'decorators' can only be used in a .ts file.": {
"category": "Error",
"code": 8017
},
"Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": {
"category": "Error",
"code": 9002
@@ -2757,23 +2929,27 @@
"code": 17004
},
"A constructor cannot contain a 'super' call when its class extends 'null'": {
"category": "Error",
"code": 17005
"category": "Error",
"code": 17005
},
"An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": {
"category": "Error",
"code": 17006
"category": "Error",
"code": 17006
},
"A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": {
"category": "Error",
"code": 17007
"category": "Error",
"code": 17007
},
"JSX element '{0}' has no corresponding closing tag.": {
"category": "Error",
"code": 17008
"category": "Error",
"code": 17008
},
"'super' must be called before accessing 'this' in the constructor of a derived class.": {
"category": "Error",
"code": 17009
"category": "Error",
"code": 17009
},
"Unknown typing option '{0}'.": {
"category": "Error",
"code": 17010
}
}
+365 -161
View File
File diff suppressed because it is too large Load Diff
+566 -290
View File
File diff suppressed because it is too large Load Diff
+198 -155
View File
@@ -178,6 +178,8 @@ namespace ts {
case SyntaxKind.AsExpression:
return visitNode(cbNode, (<AsExpression>node).expression) ||
visitNode(cbNode, (<AsExpression>node).type);
case SyntaxKind.NonNullExpression:
return visitNode(cbNode, (<NonNullExpression>node).expression);
case SyntaxKind.ConditionalExpression:
return visitNode(cbNode, (<ConditionalExpression>node).condition) ||
visitNode(cbNode, (<ConditionalExpression>node).questionToken) ||
@@ -302,6 +304,9 @@ namespace ts {
case SyntaxKind.ImportClause:
return visitNode(cbNode, (<ImportClause>node).name) ||
visitNode(cbNode, (<ImportClause>node).namedBindings);
case SyntaxKind.GlobalModuleExportDeclaration:
return visitNode(cbNode, (<GlobalModuleExportDeclaration>node).name);
case SyntaxKind.NamespaceImport:
return visitNode(cbNode, (<NamespaceImport>node).name);
case SyntaxKind.NamedImports:
@@ -397,17 +402,23 @@ namespace ts {
return visitNode(cbNode, (<JSDocTypeTag>node).typeExpression);
case SyntaxKind.JSDocTemplateTag:
return visitNodes(cbNodes, (<JSDocTemplateTag>node).typeParameters);
case SyntaxKind.PartiallyEmittedExpression:
return visitNode(cbNode, (<PartiallyEmittedExpression>node).expression);
}
}
export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false): SourceFile {
export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false, scriptKind?: ScriptKind): SourceFile {
const start = new Date().getTime();
const result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
const result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
parseTime += new Date().getTime() - start;
return result;
}
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
// Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
// indicates what changed between the 'text' that this SourceFile has and the 'newText'.
// The SourceFile will be created with the compiler attempting to reuse as many nodes from
@@ -534,23 +545,24 @@ namespace ts {
// attached to the EOF token.
let parseErrorBeforeNextFinishedNode = false;
export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean): SourceFile {
const isJavaScriptFile = hasJavaScriptFileExtension(fileName) || _sourceText.lastIndexOf("// @language=javascript", 0) === 0;
initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor);
export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile {
scriptKind = ensureScriptKind(fileName, scriptKind);
const result = parseSourceFileWorker(fileName, languageVersion, setParentNodes);
initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind);
const result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
return result;
}
function getLanguageVariant(fileName: string) {
function getLanguageVariant(scriptKind: ScriptKind) {
// .tsx and .jsx files are treated as jsx language variant.
return fileExtensionIs(fileName, ".tsx") || fileExtensionIs(fileName, ".jsx") || fileExtensionIs(fileName, ".js") ? LanguageVariant.JSX : LanguageVariant.Standard;
return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS ? LanguageVariant.JSX : LanguageVariant.Standard;
}
function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, isJavaScriptFile: boolean, _syntaxCursor: IncrementalParser.SyntaxCursor) {
function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, scriptKind: ScriptKind) {
NodeConstructor = objectAllocator.getNodeConstructor();
SourceFileConstructor = objectAllocator.getSourceFileConstructor();
@@ -563,14 +575,14 @@ namespace ts {
identifierCount = 0;
nodeCount = 0;
contextFlags = isJavaScriptFile ? NodeFlags.JavaScriptFile : NodeFlags.None;
contextFlags = scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX ? NodeFlags.JavaScriptFile : NodeFlags.None;
parseErrorBeforeNextFinishedNode = false;
// Initialize and prime the scanner before parsing the source elements.
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
scanner.setLanguageVariant(getLanguageVariant(fileName));
scanner.setLanguageVariant(getLanguageVariant(scriptKind));
}
function clearState() {
@@ -578,7 +590,7 @@ namespace ts {
scanner.setText("");
scanner.setOnError(undefined);
// Clear any data. We don't want to accidently hold onto it for too long.
// Clear any data. We don't want to accidentally hold onto it for too long.
parseDiagnostics = undefined;
sourceFile = undefined;
identifiers = undefined;
@@ -586,8 +598,8 @@ namespace ts {
sourceText = undefined;
}
function parseSourceFileWorker(fileName: string, languageVersion: ScriptTarget, setParentNodes: boolean): SourceFile {
sourceFile = createSourceFile(fileName, languageVersion);
function parseSourceFileWorker(fileName: string, languageVersion: ScriptTarget, setParentNodes: boolean, scriptKind: ScriptKind): SourceFile {
sourceFile = createSourceFile(fileName, languageVersion, scriptKind);
sourceFile.flags = contextFlags;
// Prime the scanner.
@@ -654,7 +666,7 @@ namespace ts {
}
}
function createSourceFile(fileName: string, languageVersion: ScriptTarget): SourceFile {
function createSourceFile(fileName: string, languageVersion: ScriptTarget, scriptKind: ScriptKind): 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 = <SourceFile>new SourceFileConstructor(SyntaxKind.SourceFile, /*pos*/ 0, /* end */ sourceText.length);
@@ -664,8 +676,9 @@ namespace ts {
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = normalizePath(fileName);
sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName);
sourceFile.languageVariant = getLanguageVariant(scriptKind);
sourceFile.isDeclarationFile = fileExtensionIs(sourceFile.fileName, ".d.ts");
sourceFile.scriptKind = scriptKind;
return sourceFile;
}
@@ -997,19 +1010,6 @@ namespace ts {
}
array.pos = pos;
array.end = pos;
array.arrayKind = ArrayKind.NodeArray;
return array;
}
function createModifiersArray(elements?: Modifier[], pos?: number): ModifiersArray {
const array = <ModifiersArray>(elements || []);
if (!(pos >= 0)) {
pos = getNodePos();
}
array.pos = pos;
array.end = pos;
array.arrayKind = ArrayKind.ModifiersArray;
array.flags = 0;
return array;
}
@@ -1143,7 +1143,7 @@ namespace ts {
if (token === SyntaxKind.DefaultKeyword) {
return lookAhead(nextTokenIsClassOrFunction);
}
return token !== SyntaxKind.AsteriskToken && token !== SyntaxKind.OpenBraceToken && canFollowModifier();
return token !== SyntaxKind.AsteriskToken && token !== SyntaxKind.AsKeyword && token !== SyntaxKind.OpenBraceToken && canFollowModifier();
}
if (token === SyntaxKind.DefaultKeyword) {
return nextTokenIsClassOrFunction();
@@ -1465,8 +1465,8 @@ namespace ts {
// We can only reuse a node if it was parsed under the same strict mode that we're
// currently in. i.e. if we originally parsed a node in non-strict mode, but then
// the user added 'using strict' at the top of the file, then we can't use that node
// again as the presense of strict mode may cause us to parse the tokens in the file
// differetly.
// again as the presence of strict mode may cause us to parse the tokens in the file
// differently.
//
// Note: we *can* reuse tokens when the strict mode changes. That's because tokens
// are unaffected by strict mode. It's just the parser will decide what to do with it
@@ -1479,7 +1479,7 @@ namespace ts {
}
// Ok, we have a node that looks like it could be reused. Now verify that it is valid
// in the currest list parsing context that we're currently at.
// in the current list parsing context that we're currently at.
if (!canReuseNode(node, parsingContext)) {
return undefined;
}
@@ -1742,7 +1742,7 @@ namespace ts {
};
// Parses a comma-delimited list of elements
function parseDelimitedList<T extends Node>(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimeter?: boolean): NodeArray<T> {
function parseDelimitedList<T extends Node>(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray<T> {
const saveParsingContext = parsingContext;
parsingContext |= 1 << kind;
const result = createNodeArray<T>();
@@ -1770,7 +1770,7 @@ namespace ts {
// parse errors. For example, this can happen when people do things like use
// a semicolon to delimit object literal members. Note: we'll have already
// reported an error when we called parseExpected above.
if (considerSemicolonAsDelimeter && token === SyntaxKind.SemicolonToken && !scanner.hasPrecedingLineBreak()) {
if (considerSemicolonAsDelimiter && token === SyntaxKind.SemicolonToken && !scanner.hasPrecedingLineBreak()) {
nextToken();
}
continue;
@@ -1954,7 +1954,7 @@ namespace ts {
return finishNode(node);
}
function parseTypePredicate(lhs: Identifier | ThisTypeNode): TypePredicateNode {
function parseThisTypePredicate(lhs: ThisTypeNode): TypePredicateNode {
nextToken();
const node = createNode(SyntaxKind.TypePredicate, lhs.pos) as TypePredicateNode;
node.parameterName = lhs;
@@ -2016,27 +2016,24 @@ namespace ts {
}
function isStartOfParameter(): boolean {
return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken;
}
function setModifiers(node: Node, modifiers: ModifiersArray) {
if (modifiers) {
node.flags |= modifiers.flags;
node.modifiers = modifiers;
}
return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken || token === SyntaxKind.ThisKeyword;
}
function parseParameter(): ParameterDeclaration {
const node = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
if (token === SyntaxKind.ThisKeyword) {
node.name = createIdentifier(/*isIdentifier*/true, undefined);
node.type = parseParameterType();
return finishNode(node);
}
node.decorators = parseDecorators();
setModifiers(node, parseModifiers());
node.modifiers = parseModifiers();
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
node.name = parseIdentifierOrPattern();
if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifierKind(token)) {
// in cases like
// 'use strict'
@@ -2074,11 +2071,11 @@ namespace ts {
}
function fillSignature(
returnToken: SyntaxKind,
yieldContext: boolean,
awaitContext: boolean,
requireCompleteParameterList: boolean,
signature: SignatureDeclaration): void {
returnToken: SyntaxKind,
yieldContext: boolean,
awaitContext: boolean,
requireCompleteParameterList: boolean,
signature: SignatureDeclaration): void {
const returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken;
signature.typeParameters = parseTypeParameters();
@@ -2218,27 +2215,27 @@ namespace ts {
return token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBracketToken;
}
function parseIndexSignatureDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): IndexSignatureDeclaration {
function parseIndexSignatureDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): IndexSignatureDeclaration {
const node = <IndexSignatureDeclaration>createNode(SyntaxKind.IndexSignature, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);
node.type = parseTypeAnnotation();
parseTypeMemberSemicolon();
return finishNode(node);
}
function parsePropertyOrMethodSignature(fullStart: number, modifiers: ModifiersArray): PropertySignature | MethodSignature {
function parsePropertyOrMethodSignature(fullStart: number, modifiers: NodeArray<Modifier>): PropertySignature | MethodSignature {
const name = parsePropertyName();
const questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) {
const method = <MethodSignature>createNode(SyntaxKind.MethodSignature, fullStart);
setModifiers(method, modifiers);
method.modifiers = modifiers;
method.name = name;
method.questionToken = questionToken;
// Method signatues don't exist in expression contexts. So they have neither
// Method signatures don't exist in expression contexts. So they have neither
// [Yield] nor [Await]
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method);
parseTypeMemberSemicolon();
@@ -2246,7 +2243,7 @@ namespace ts {
}
else {
const property = <PropertySignature>createNode(SyntaxKind.PropertySignature, fullStart);
setModifiers(property, modifiers);
property.modifiers = modifiers;
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
@@ -2369,17 +2366,19 @@ namespace ts {
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
// If these are followed by a dot, then parse these out as a dotted type reference instead.
const node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReference();
case SyntaxKind.StringLiteral:
return parseStringLiteralTypeNode();
case SyntaxKind.VoidKeyword:
case SyntaxKind.NullKeyword:
return parseTokenNode<TypeNode>();
case SyntaxKind.ThisKeyword: {
const thisKeyword = parseThisTypeNode();
if (token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) {
return parseTypePredicate(thisKeyword);
return parseThisTypePredicate(thisKeyword);
}
else {
return thisKeyword;
@@ -2406,6 +2405,8 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.OpenBraceToken:
@@ -2474,7 +2475,7 @@ namespace ts {
// Skip modifiers
parseModifiers();
}
if (isIdentifier()) {
if (isIdentifier() || token === SyntaxKind.ThisKeyword) {
nextToken();
return true;
}
@@ -2735,7 +2736,7 @@ namespace ts {
function isYieldExpression(): boolean {
if (token === SyntaxKind.YieldKeyword) {
// If we have a 'yield' keyword, and htis is a context where yield expressions are
// If we have a 'yield' keyword, and this is a context where yield expressions are
// allowed, then definitely parse out a yield expression.
if (inYieldContext()) {
return true;
@@ -2754,7 +2755,7 @@ namespace ts {
//
// for now we just check if the next token is an identifier. More heuristics
// can be added here later as necessary. We just need to make sure that we
// don't accidently consume something legal.
// don't accidentally consume something legal.
return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine);
}
@@ -2783,7 +2784,7 @@ namespace ts {
}
else {
// if the next token is not on the same line as yield. or we don't have an '*' or
// the start of an expressin, then this is just a simple "yield" expression.
// the start of an expression, then this is just a simple "yield" expression.
return finishNode(node);
}
}
@@ -2826,7 +2827,7 @@ namespace ts {
return undefined;
}
const isAsync = !!(arrowFunction.flags & NodeFlags.Async);
const isAsync = !!(getModifierFlags(arrowFunction) & ModifierFlags.Async);
// If we have an arrow, then try to parse the body. Even if not, try to parse if we
// have an opening brace, just in case we're in an error state.
@@ -2971,8 +2972,8 @@ namespace ts {
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction {
const node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction);
setModifiers(node, parseModifiersForArrowFunction());
const isAsync = !!(node.flags & NodeFlags.Async);
node.modifiers = parseModifiersForArrowFunction();
const isAsync = !!(getModifierFlags(node) & ModifierFlags.Async);
// Arrow functions are never generators.
//
@@ -3075,7 +3076,7 @@ namespace ts {
// Check the precedence to see if we should "take" this operator
// - For left associative operator (all operator but **), consume the operator,
// recursively call the function below, and parse binaryExpression as a rightOperand
// of the caller if the new precendence of the operator is greater then or equal to the current precendence.
// of the caller if the new precedence of the operator is greater then or equal to the current precedence.
// For example:
// a - b - c;
// ^token; leftOperand = b. Return b to the caller as a rightOperand
@@ -3084,8 +3085,8 @@ namespace ts {
// a - b * c;
// ^token; leftOperand = b. Return b * c to the caller as a rightOperand
// - For right associative operator (**), consume the operator, recursively call the function
// and parse binaryExpression as a rightOperand of the caller if the new precendence of
// the operator is strictly grater than the current precendence
// and parse binaryExpression as a rightOperand of the caller if the new precedence of
// the operator is strictly grater than the current precedence
// For example:
// a ** b ** c;
// ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
@@ -3326,7 +3327,7 @@ namespace ts {
*/
function isIncrementExpression(): boolean {
// This function is called inside parseUnaryExpression to decide
// whether to call parseSimpleUnaryExpression or call parseIncrmentExpression directly
// whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly
switch (token) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
@@ -3729,6 +3730,14 @@ namespace ts {
continue;
}
if (token === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
nextToken();
const nonNullExpression = <NonNullExpression>createNode(SyntaxKind.NonNullExpression, expression.pos);
nonNullExpression.expression = expression;
expression = finishNode(nonNullExpression);
continue;
}
// when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
if (!inDecoratorContext() && parseOptional(SyntaxKind.OpenBracketToken)) {
const indexedAccess = <ElementAccessExpression>createNode(SyntaxKind.ElementAccessExpression, expression.pos);
@@ -3813,7 +3822,7 @@ namespace ts {
return undefined;
}
// If we have a '<', then only parse this as a arugment list if the type arguments
// If we have a '<', then only parse this as a argument list if the type arguments
// are complete and we have an open paren. if we don't, rewind and return nothing.
return typeArguments && canFollowTypeArgumentsInExpression()
? typeArguments
@@ -3942,9 +3951,9 @@ namespace ts {
return finishNode(node);
}
function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): AccessorDeclaration {
function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): AccessorDeclaration {
if (parseContextualModifier(SyntaxKind.GetKeyword)) {
return parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, decorators, modifiers);
return addJSDocComment(parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, decorators, modifiers));
}
else if (parseContextualModifier(SyntaxKind.SetKeyword)) {
return parseAccessorDeclaration(SyntaxKind.SetAccessor, fullStart, decorators, modifiers);
@@ -3990,7 +3999,7 @@ namespace ts {
shorthandDeclaration.equalsToken = equalsToken;
shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
}
return finishNode(shorthandDeclaration);
return addJSDocComment(finishNode(shorthandDeclaration));
}
else {
const propertyAssignment = <PropertyAssignment>createNode(SyntaxKind.PropertyAssignment, fullStart);
@@ -3999,7 +4008,7 @@ namespace ts {
propertyAssignment.questionToken = questionToken;
parseExpected(SyntaxKind.ColonToken);
propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
return finishNode(propertyAssignment);
return addJSDocComment(finishNode(propertyAssignment));
}
}
@@ -4010,7 +4019,7 @@ namespace ts {
node.multiLine = true;
}
node.properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true);
node.properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
parseExpected(SyntaxKind.CloseBraceToken);
return finishNode(node);
}
@@ -4027,12 +4036,12 @@ namespace ts {
}
const node = <FunctionExpression>createNode(SyntaxKind.FunctionExpression);
setModifiers(node, parseModifiers());
node.modifiers = parseModifiers();
parseExpected(SyntaxKind.FunctionKeyword);
node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
const isGenerator = !!node.asteriskToken;
const isAsync = !!(node.flags & NodeFlags.Async);
const isAsync = !!(getModifierFlags(node) & ModifierFlags.Async);
node.name =
isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
isGenerator ? doInYieldContext(parseOptionalIdentifier) :
@@ -4412,7 +4421,8 @@ namespace ts {
continue;
case SyntaxKind.GlobalKeyword:
return nextToken() === SyntaxKind.OpenBraceToken;
nextToken();
return token === SyntaxKind.OpenBraceToken || token === SyntaxKind.Identifier || token === SyntaxKind.ExportKeyword;
case SyntaxKind.ImportKeyword:
nextToken();
@@ -4421,7 +4431,8 @@ namespace ts {
case SyntaxKind.ExportKeyword:
nextToken();
if (token === SyntaxKind.EqualsToken || token === SyntaxKind.AsteriskToken ||
token === SyntaxKind.OpenBraceToken || token === SyntaxKind.DefaultKeyword) {
token === SyntaxKind.OpenBraceToken || token === SyntaxKind.DefaultKeyword ||
token === SyntaxKind.AsKeyword) {
return true;
}
continue;
@@ -4605,9 +4616,15 @@ namespace ts {
return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers);
case SyntaxKind.ExportKeyword:
nextToken();
return token === SyntaxKind.DefaultKeyword || token === SyntaxKind.EqualsToken ?
parseExportAssignment(fullStart, decorators, modifiers) :
parseExportDeclaration(fullStart, decorators, modifiers);
switch (token) {
case SyntaxKind.DefaultKeyword:
case SyntaxKind.EqualsToken:
return parseExportAssignment(fullStart, decorators, modifiers);
case SyntaxKind.AsKeyword:
return parseGlobalModuleExportDeclaration(fullStart, decorators, modifiers);
default:
return parseExportDeclaration(fullStart, decorators, modifiers);
}
default:
if (decorators || modifiers) {
// We reached this point because we encountered decorators and/or modifiers and assumed a declaration
@@ -4615,7 +4632,7 @@ namespace ts {
const node = <Statement>createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
node.pos = fullStart;
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
return finishNode(node);
}
}
@@ -4750,57 +4767,57 @@ namespace ts {
return nextTokenIsIdentifier() && nextToken() === SyntaxKind.CloseParenToken;
}
function parseVariableStatement(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): VariableStatement {
function parseVariableStatement(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): VariableStatement {
const node = <VariableStatement>createNode(SyntaxKind.VariableStatement, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
parseSemicolon();
return addJSDocComment(finishNode(node));
}
function parseFunctionDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): FunctionDeclaration {
function parseFunctionDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): FunctionDeclaration {
const node = <FunctionDeclaration>createNode(SyntaxKind.FunctionDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.FunctionKeyword);
node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier();
node.name = hasModifier(node, ModifierFlags.Default) ? parseOptionalIdentifier() : parseIdentifier();
const isGenerator = !!node.asteriskToken;
const isAsync = !!(node.flags & NodeFlags.Async);
const isAsync = hasModifier(node, ModifierFlags.Async);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, Diagnostics.or_expected);
return addJSDocComment(finishNode(node));
}
function parseConstructorDeclaration(pos: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ConstructorDeclaration {
function parseConstructorDeclaration(pos: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ConstructorDeclaration {
const node = <ConstructorDeclaration>createNode(SyntaxKind.Constructor, pos);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.ConstructorKeyword);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, Diagnostics.or_expected);
return addJSDocComment(finishNode(node));
}
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
const method = <MethodDeclaration>createNode(SyntaxKind.MethodDeclaration, fullStart);
method.decorators = decorators;
setModifiers(method, modifiers);
method.modifiers = modifiers;
method.asteriskToken = asteriskToken;
method.name = name;
method.questionToken = questionToken;
const isGenerator = !!asteriskToken;
const isAsync = !!(method.flags & NodeFlags.Async);
const isAsync = hasModifier(method, ModifierFlags.Async);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method);
method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage);
return addJSDocComment(finishNode(method));
}
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, name: PropertyName, questionToken: Node): ClassElement {
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, name: PropertyName, questionToken: Node): ClassElement {
const property = <PropertyDeclaration>createNode(SyntaxKind.PropertyDeclaration, fullStart);
property.decorators = decorators;
setModifiers(property, modifiers);
property.modifiers = modifiers;
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
@@ -4810,11 +4827,11 @@ namespace ts {
// off. The grammar would look something like this:
//
// MemberVariableDeclaration[Yield]:
// AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initialiser_opt[In];
// AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield];
// AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In];
// AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield];
//
// The checker may still error in the static case to explicitly disallow the yield expression.
property.initializer = modifiers && modifiers.flags & NodeFlags.Static
property.initializer = hasModifier(property, ModifierFlags.Static)
? allowInAnd(parseNonParameterInitializer)
: doOutsideOfContext(NodeFlags.YieldContext | NodeFlags.DisallowInContext, parseNonParameterInitializer);
@@ -4822,7 +4839,7 @@ namespace ts {
return finishNode(property);
}
function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ClassElement {
function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ClassElement {
const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
const name = parsePropertyName();
@@ -4841,10 +4858,10 @@ namespace ts {
return parseInitializer(/*inParameter*/ false);
}
function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): AccessorDeclaration {
function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): AccessorDeclaration {
const node = <AccessorDeclaration>createNode(kind, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.name = parsePropertyName();
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false);
@@ -4963,9 +4980,8 @@ namespace ts {
*
* In such situations, 'permitInvalidConstAsModifier' should be set to true.
*/
function parseModifiers(permitInvalidConstAsModifier?: boolean): ModifiersArray {
let flags = 0;
let modifiers: ModifiersArray;
function parseModifiers(permitInvalidConstAsModifier?: boolean): NodeArray<Modifier> {
let modifiers: NodeArray<Modifier>;
while (true) {
const modifierStart = scanner.getStartPos();
const modifierKind = token;
@@ -4983,31 +4999,28 @@ namespace ts {
}
}
flags |= modifierToFlag(modifierKind);
const modifier = finishNode(createNode(modifierKind, modifierStart));
if (!modifiers) {
modifiers = createModifiersArray([modifier], modifierStart);
modifiers = createNodeArray<Modifier>([modifier], modifierStart);
}
else {
modifiers.push(modifier);
}
}
if (modifiers) {
modifiers.flags = flags;
modifiers.end = scanner.getStartPos();
}
return modifiers;
}
function parseModifiersForArrowFunction(): ModifiersArray {
let modifiers: ModifiersArray;
function parseModifiersForArrowFunction(): NodeArray<Modifier> {
let modifiers: NodeArray<Modifier>;
if (token === SyntaxKind.AsyncKeyword) {
const modifierStart = scanner.getStartPos();
const modifierKind = token;
nextToken();
const modifier = finishNode(createNode(modifierKind, modifierStart));
modifiers = createModifiersArray([modifier], modifierStart);
modifiers.flags = modifierToFlag(modifierKind);
modifiers = createNodeArray<Modifier>([modifier], modifierStart);
modifiers.end = scanner.getStartPos();
}
@@ -5067,14 +5080,14 @@ namespace ts {
SyntaxKind.ClassExpression);
}
function parseClassDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ClassDeclaration {
function parseClassDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ClassDeclaration {
return <ClassDeclaration>parseClassDeclarationOrExpression(fullStart, decorators, modifiers, SyntaxKind.ClassDeclaration);
}
function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration {
function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, kind: SyntaxKind): ClassLikeDeclaration {
const node = <ClassLikeDeclaration>createNode(kind, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.ClassKeyword);
node.name = parseNameOfClassDeclarationOrExpression();
node.typeParameters = parseTypeParameters();
@@ -5149,10 +5162,10 @@ namespace ts {
return parseList(ParsingContext.ClassMembers, parseClassElement);
}
function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): InterfaceDeclaration {
function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): InterfaceDeclaration {
const node = <InterfaceDeclaration>createNode(SyntaxKind.InterfaceDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.InterfaceKeyword);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
@@ -5161,10 +5174,10 @@ namespace ts {
return finishNode(node);
}
function parseTypeAliasDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): TypeAliasDeclaration {
function parseTypeAliasDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): TypeAliasDeclaration {
const node = <TypeAliasDeclaration>createNode(SyntaxKind.TypeAliasDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.TypeKeyword);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
@@ -5185,10 +5198,10 @@ namespace ts {
return finishNode(node);
}
function parseEnumDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): EnumDeclaration {
function parseEnumDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): EnumDeclaration {
const node = <EnumDeclaration>createNode(SyntaxKind.EnumDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.EnumKeyword);
node.name = parseIdentifier();
if (parseExpected(SyntaxKind.OpenBraceToken)) {
@@ -5213,25 +5226,25 @@ namespace ts {
return finishNode(node);
}
function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, flags: NodeFlags): ModuleDeclaration {
function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, flags: NodeFlags): ModuleDeclaration {
const node = <ModuleDeclaration>createNode(SyntaxKind.ModuleDeclaration, fullStart);
// If we are parsing a dotted namespace name, we want to
// propagate the 'Namespace' flag across the names if set.
const namespaceFlag = flags & NodeFlags.Namespace;
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.flags |= flags;
node.name = parseIdentifier();
node.body = parseOptional(SyntaxKind.DotToken)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.Export | namespaceFlag)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag)
: parseModuleBlock();
return finishNode(node);
}
function parseAmbientExternalModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ModuleDeclaration {
function parseAmbientExternalModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ModuleDeclaration {
const node = <ModuleDeclaration>createNode(SyntaxKind.ModuleDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
if (token === SyntaxKind.GlobalKeyword) {
// parse 'global' as name of global scope augmentation
node.name = parseIdentifier();
@@ -5244,8 +5257,8 @@ namespace ts {
return finishNode(node);
}
function parseModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ModuleDeclaration {
let flags = modifiers ? modifiers.flags : 0;
function parseModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ModuleDeclaration {
let flags: NodeFlags = 0;
if (token === SyntaxKind.GlobalKeyword) {
// global augmentation
return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers);
@@ -5275,7 +5288,21 @@ namespace ts {
return nextToken() === SyntaxKind.SlashToken;
}
function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ImportEqualsDeclaration | ImportDeclaration {
function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): GlobalModuleExportDeclaration {
const exportDeclaration = <GlobalModuleExportDeclaration>createNode(SyntaxKind.GlobalModuleExportDeclaration, fullStart);
exportDeclaration.decorators = decorators;
exportDeclaration.modifiers = modifiers;
parseExpected(SyntaxKind.AsKeyword);
parseExpected(SyntaxKind.NamespaceKeyword);
exportDeclaration.name = parseIdentifier();
parseExpected(SyntaxKind.SemicolonToken);
return finishNode(exportDeclaration);
}
function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ImportEqualsDeclaration | ImportDeclaration {
parseExpected(SyntaxKind.ImportKeyword);
const afterImportPos = scanner.getStartPos();
@@ -5288,7 +5315,7 @@ namespace ts {
// import x = M.x;
const importEqualsDeclaration = <ImportEqualsDeclaration>createNode(SyntaxKind.ImportEqualsDeclaration, fullStart);
importEqualsDeclaration.decorators = decorators;
setModifiers(importEqualsDeclaration, modifiers);
importEqualsDeclaration.modifiers = modifiers;
importEqualsDeclaration.name = identifier;
parseExpected(SyntaxKind.EqualsToken);
importEqualsDeclaration.moduleReference = parseModuleReference();
@@ -5300,7 +5327,7 @@ namespace ts {
// Import statement
const importDeclaration = <ImportDeclaration>createNode(SyntaxKind.ImportDeclaration, fullStart);
importDeclaration.decorators = decorators;
setModifiers(importDeclaration, modifiers);
importDeclaration.modifiers = modifiers;
// ImportDeclaration:
// import ImportClause from ModuleSpecifier ;
@@ -5411,7 +5438,7 @@ namespace ts {
// ImportSpecifier:
// BindingIdentifier
// IdentifierName as BindingIdentifier
// ExportSpecififer:
// ExportSpecifier:
// IdentifierName
// IdentifierName as IdentifierName
let checkIdentifierIsKeyword = isKeyword(token) && !isIdentifier();
@@ -5436,10 +5463,10 @@ namespace ts {
return finishNode(node);
}
function parseExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ExportDeclaration {
function parseExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ExportDeclaration {
const node = <ExportDeclaration>createNode(SyntaxKind.ExportDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
if (parseOptional(SyntaxKind.AsteriskToken)) {
parseExpected(SyntaxKind.FromKeyword);
node.moduleSpecifier = parseModuleSpecifier();
@@ -5459,10 +5486,10 @@ namespace ts {
return finishNode(node);
}
function parseExportAssignment(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ExportAssignment {
function parseExportAssignment(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ExportAssignment {
const node = <ExportAssignment>createNode(SyntaxKind.ExportAssignment, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
if (parseOptional(SyntaxKind.EqualsToken)) {
node.isExportEquals = true;
}
@@ -5477,6 +5504,7 @@ namespace ts {
function processReferenceComments(sourceFile: SourceFile): void {
const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText);
const referencedFiles: FileReference[] = [];
const typeReferenceDirectives: FileReference[] = [];
const amdDependencies: { path: string; name: string }[] = [];
let amdModuleName: string;
@@ -5503,7 +5531,12 @@ namespace ts {
sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
const diagnosticMessage = referencePathMatchResult.diagnosticMessage;
if (fileReference) {
referencedFiles.push(fileReference);
if (referencePathMatchResult.isTypeReferenceDirective) {
typeReferenceDirectives.push(fileReference);
}
else {
referencedFiles.push(fileReference);
}
}
if (diagnosticMessage) {
parseDiagnostics.push(createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
@@ -5535,13 +5568,14 @@ namespace ts {
}
sourceFile.referencedFiles = referencedFiles;
sourceFile.typeReferenceDirectives = typeReferenceDirectives;
sourceFile.amdDependencies = amdDependencies;
sourceFile.moduleName = amdModuleName;
}
function setExternalModuleIndicator(sourceFile: SourceFile) {
sourceFile.externalModuleIndicator = forEach(sourceFile.statements, node =>
node.flags & NodeFlags.Export
hasModifier(node, ModifierFlags.Export)
|| node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference
|| node.kind === SyntaxKind.ImportDeclaration
|| node.kind === SyntaxKind.ExportAssignment
@@ -5606,7 +5640,7 @@ namespace ts {
}
export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number) {
initializeState("file.js", content, ScriptTarget.Latest, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined);
initializeState("file.js", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS);
scanner.setText(content, start, length);
token = scanner.scan();
const jsDocTypeExpression = parseJSDocTypeExpression();
@@ -5760,6 +5794,9 @@ namespace ts {
function parseJSDocParameter(): ParameterDeclaration {
const parameter = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
parameter.type = parseJSDocType();
if (parseOptional(SyntaxKind.EqualsToken)) {
parameter.questionToken = createNode(SyntaxKind.EqualsToken);
}
return finishNode(parameter);
}
@@ -5767,16 +5804,22 @@ namespace ts {
const result = <JSDocTypeReference>createNode(SyntaxKind.JSDocTypeReference);
result.name = parseSimplePropertyName();
while (parseOptional(SyntaxKind.DotToken)) {
if (token === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
break;
}
else {
result.name = parseQualifiedName(result.name);
if (token === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
}
else {
while (parseOptional(SyntaxKind.DotToken)) {
if (token === SyntaxKind.LessThanToken) {
result.typeArguments = parseTypeArguments();
break;
}
else {
result.name = parseQualifiedName(result.name);
}
}
}
return finishNode(result);
}
@@ -5914,7 +5957,7 @@ namespace ts {
}
export function parseIsolatedJSDocComment(content: string, start: number, length: number) {
initializeState("file.js", content, ScriptTarget.Latest, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined);
initializeState("file.js", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS);
sourceFile = <SourceFile>{ languageVariant: LanguageVariant.Standard, text: content };
const jsDocComment = parseJSDocCommentWorker(start, length);
const diagnostics = parseDiagnostics;
@@ -6239,11 +6282,11 @@ namespace ts {
if (sourceFile.statements.length === 0) {
// If we don't have any statements in the current source file, then there's no real
// way to incrementally parse. So just do a full parse instead.
return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true);
return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
}
// Make sure we're not trying to incrementally update a source file more than once. Once
// we do an update the original source file is considered unusbale from that point onwards.
// we do an update the original source file is considered unusable from that point onwards.
//
// This is because we do incremental parsing in-place. i.e. we take nodes from the old
// tree and give them new positions and parents. From that point on, trusting the old
@@ -6303,7 +6346,7 @@ namespace ts {
// inconsistent tree. Setting the parents on the new tree should be very fast. We
// will immediately bail out of walking any subtrees when we can see that their parents
// are already correct.
const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true);
const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
return result;
}
@@ -6374,7 +6417,7 @@ namespace ts {
// We have an element that intersects the change range in some way. It may have its
// start, or its end (or both) in the changed range. We want to adjust any part
// that intersects such that the final tree is in a consistent state. i.e. all
// chlidren have spans within the span of their parent, and all siblings are ordered
// children have spans within the span of their parent, and all siblings are ordered
// properly.
// We may need to update both the 'pos' and the 'end' of the element.
@@ -6396,7 +6439,7 @@ namespace ts {
// -------------------ZZZ-----------------
//
// In this case, any element that started in the 'X' range will keep its position.
// However any element htat started after that will have their pos adjusted to be
// However any element that started after that will have their pos adjusted to be
// at the end of the new range. i.e. any node that started in the 'Y' range will
// be adjusted to have their start at the end of the 'Z' range.
//
@@ -6421,7 +6464,7 @@ namespace ts {
// -------------------ZZZ-----------------
//
// In this case, any element that ended in the 'X' range will keep its position.
// However any element htat ended after that will have their pos adjusted to be
// However any element that ended after that will have their pos adjusted to be
// at the end of the new range. i.e. any node that ended in the 'Y' range will
// be adjusted to have their end at the end of the 'Z' range.
if (element.end >= changeRangeOldEnd) {
@@ -6751,7 +6794,7 @@ namespace ts {
// Position was within this node. Keep searching deeper to find the node.
forEachChild(node, visitNode, visitArray);
// don't procede any futher in the search.
// don't proceed any further in the search.
return true;
}
+531 -271
View File
File diff suppressed because it is too large Load Diff
+617 -231
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -114,6 +114,7 @@ namespace ts {
"try": SyntaxKind.TryKeyword,
"type": SyntaxKind.TypeKeyword,
"typeof": SyntaxKind.TypeOfKeyword,
"undefined": SyntaxKind.UndefinedKeyword,
"var": SyntaxKind.VarKeyword,
"void": SyntaxKind.VoidKeyword,
"while": SyntaxKind.WhileKeyword,
@@ -509,7 +510,7 @@ namespace ts {
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
// a <<<<<<< or >>>>>>> marker then it is also followed by a space.
const mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text: string, pos: number) {
@@ -549,7 +550,7 @@ namespace ts {
}
else {
Debug.assert(ch === CharacterCodes.equals);
// Consume everything from the start of the mid-conlict marker to the start of the next
// Consume everything from the start of the mid-conflict marker to the start of the next
// end-conflict marker.
while (pos < len) {
const ch = text.charCodeAt(pos);
+399 -47
View File
@@ -3,22 +3,197 @@
/* @internal */
namespace ts {
export interface SourceMapWriter {
getSourceMapData(): SourceMapData;
setSourceFile(sourceFile: SourceFile): void;
emitPos(pos: number): void;
emitStart(range: TextRange): void;
emitEnd(range: TextRange): void;
/*@deprecated*/ emitEnd(range: TextRange, stopOverridingSpan: boolean): void;
/*@deprecated*/ changeEmitSourcePos(): void;
getText(): string;
getSourceMappingURL(): string;
/**
* Initialize the SourceMapWriter for a new output file.
*
* @param filePath The path to the generated output file.
* @param sourceMapFilePath The path to the output source map file.
* @param sourceFiles The input source files for the program.
* @param isBundledEmit A value indicating whether the generated output file is a bundle.
*/
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void;
/**
* Reset the SourceMapWriter to an empty state.
*/
reset(): void;
enable(): void;
disable(): void;
/**
* Gets test data for source maps.
*/
getSourceMapData(): SourceMapData;
/**
* Set the current source file.
*
* @param sourceFile The source file.
*/
setSourceFile(sourceFile: SourceFile): void;
/**
* Emits a mapping.
*
* If the position is synthetic (undefined or a negative value), no mapping will be
* created.
*
* @param pos The position.
*/
emitPos(pos: number): void;
/**
* Emits a mapping for the start of a range.
*
* If the range's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.
*/
emitStart(range: TextRange): void;
/**
* Emits a mapping for the start of a range.
*
* If the node's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the start position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void;
/**
* Emits a mapping for the end of a range.
*
* If the range's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
*/
emitEnd(range: TextRange): void;
/**
* Emits a mapping for the end of a range.
*
* If the node's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the end position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void;
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @returns The start position of the token, following any trivia.
*/
emitTokenStart(token: SyntaxKind, tokenStartPos: number): number;
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the start position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The start position of the token, following any trivia.
*/
emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @returns The end position of the token.
*/
emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number;
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the end position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The end position of the token.
*/
emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
/*@deprecated*/ changeEmitSourcePos(): void;
/*@deprecated*/ stopOverridingSpan(): void;
/**
* Gets the text for the source map.
*/
getText(): string;
/**
* Gets the SourceMappingURL for the source map.
*/
getSourceMappingURL(): string;
}
let nullSourceMapWriter: SourceMapWriter;
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
nullSourceMapWriter = {
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void { },
reset(): void { },
getSourceMapData(): SourceMapData { return undefined; },
setSourceFile(sourceFile: SourceFile): void { },
emitPos(pos: number): void { },
emitStart(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void { },
emitEnd(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void { },
emitTokenStart(token: SyntaxKind, pos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind, pos: number) => TextRange): number { return -1; },
emitTokenEnd(token: SyntaxKind, end: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind, pos: number) => TextRange): number { return -1; },
changeEmitSourcePos(): void { },
stopOverridingSpan(): void { },
getText(): string { return undefined; },
getSourceMappingURL(): string { return undefined; }
};
}
return nullSourceMapWriter;
}
// Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans
const defaultLastEncodedSourceMapSpan: SourceMapSpan = {
emittedLine: 1,
@@ -28,30 +203,10 @@ namespace ts {
sourceIndex: 0
};
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
nullSourceMapWriter = {
getSourceMapData(): SourceMapData { return undefined; },
setSourceFile(sourceFile: SourceFile): void { },
emitStart(range: TextRange): void { },
emitEnd(range: TextRange, stopOverridingSpan?: boolean): void { },
emitPos(pos: number): void { },
changeEmitSourcePos(): void { },
getText(): string { return undefined; },
getSourceMappingURL(): string { return undefined; },
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void { },
reset(): void { },
enable(): void { },
disable(): void { }
};
}
return nullSourceMapWriter;
}
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
const compilerOptions = host.getCompilerOptions();
let currentSourceFile: SourceFile;
let currentSourceText: string;
let sourceMapDir: string; // The directory in which sourcemap will be
let stopOverridingSpan = false;
let modifyLastSourcePos = false;
@@ -75,26 +230,36 @@ namespace ts {
let disableDepth: number;
return {
initialize,
reset,
getSourceMapData: () => sourceMapData,
setSourceFile,
emitPos,
emitStart,
emitEnd,
emitTokenStart,
emitTokenEnd,
changeEmitSourcePos,
stopOverridingSpan: () => stopOverridingSpan = true,
getText,
getSourceMappingURL,
initialize,
reset,
enable,
disable,
};
/**
* Initialize the SourceMapWriter for a new output file.
*
* @param filePath The path to the generated output file.
* @param sourceMapFilePath The path to the output source map file.
* @param sourceFiles The input source files for the program.
* @param isBundledEmit A value indicating whether the generated output file is a bundle.
*/
function initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
if (sourceMapData) {
reset();
}
currentSourceFile = undefined;
currentSourceText = undefined;
disableDepth = 0;
// Current source map file and its index in the sources list
@@ -154,6 +319,9 @@ namespace ts {
}
}
/**
* Reset the SourceMapWriter to an empty state.
*/
function reset() {
currentSourceFile = undefined;
sourceMapDir = undefined;
@@ -267,6 +435,14 @@ namespace ts {
sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);
}
/**
* Emits a mapping.
*
* If the position is synthetic (undefined or a negative value), no mapping will be
* created.
*
* @param pos The position.
*/
function emitPos(pos: number) {
if (positionIsSynthesized(pos) || disableDepth > 0) {
return;
@@ -313,35 +489,205 @@ namespace ts {
updateLastEncodedAndRecordedSpans();
}
function getStartPos(range: TextRange) {
function getStartPosPastDecorators(range: TextRange) {
const rangeHasDecorators = !!(range as Node).decorators;
return range.pos !== -1 ? skipTrivia(currentSourceFile.text, rangeHasDecorators ? (range as Node).decorators.end : range.pos) : -1;
return skipTrivia(currentSourceText, rangeHasDecorators ? (range as Node).decorators.end : range.pos);
}
function emitStart(range: TextRange) {
emitPos(getStartPos(range));
function getStartPos(range: TextRange) {
return skipTrivia(currentSourceText, range.pos);
}
if (range.disableSourceMap) {
disable();
/**
* Emits a mapping for the start of a range.
*
* If the range's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.0
*/
function emitStart(range: TextRange): void;
/**
* Emits a mapping for the start of a range.
*
* If the node's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the start position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
function emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallback: (node: Node) => TextRange): void;
function emitStart(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange) {
if (contextNode) {
if (!ignoreNodeCallback(contextNode)) {
range = getTextRangeCallback(contextNode) || range;
emitPos(getStartPosPastDecorators(range));
}
if (ignoreChildrenCallback(contextNode)) {
disable();
}
}
else {
emitPos(getStartPosPastDecorators(range));
}
}
function emitEnd(range: TextRange, stopOverridingEnd?: boolean) {
if (range.disableSourceMap) {
enable();
/**
* Emits a mapping for the end of a range.
*
* If the range's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
*/
function emitEnd(range: TextRange): void;
/**
* Emits a mapping for the end of a range.
*
* If the node's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the end position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
function emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallback: (node: Node) => TextRange): void;
function emitEnd(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange) {
if (contextNode) {
if (ignoreChildrenCallback(contextNode)) {
enable();
}
if (!ignoreNodeCallback(contextNode)) {
range = getTextRangeCallback(contextNode) || range;
emitPos(range.end);
}
}
else {
emitPos(range.end);
}
emitPos(range.end);
stopOverridingSpan = stopOverridingEnd;
stopOverridingSpan = false;
}
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @returns The start position of the token, following any trivia.
*/
function emitTokenStart(token: SyntaxKind, tokenStartPos: number): number;
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the start position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The start position of the token, following any trivia.
*/
function emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
function emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
if (contextNode) {
if (ignoreTokenCallback(contextNode, token)) {
return skipTrivia(currentSourceText, tokenStartPos);
}
const range = getTokenTextRangeCallback(contextNode, token);
if (range) {
tokenStartPos = range.pos;
}
}
tokenStartPos = skipTrivia(currentSourceText, tokenStartPos);
emitPos(tokenStartPos);
return tokenStartPos;
}
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @returns The end position of the token.
*/
function emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number;
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the end position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The end position of the token.
*/
function emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
function emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
if (contextNode) {
if (ignoreTokenCallback(contextNode, token)) {
return tokenEndPos;
}
const range = getTokenTextRangeCallback(contextNode, token);
if (range) {
tokenEndPos = range.end;
}
}
emitPos(tokenEndPos);
return tokenEndPos;
}
// @deprecated
function changeEmitSourcePos() {
Debug.assert(!modifyLastSourcePos);
modifyLastSourcePos = true;
}
/**
* Set the current source file.
*
* @param sourceFile The source file.
*/
function setSourceFile(sourceFile: SourceFile) {
currentSourceFile = sourceFile;
currentSourceText = sourceFile.text;
// Add the file to tsFilePaths
// If sourceroot option: Use the relative path corresponding to the common directory path
@@ -368,6 +714,9 @@ namespace ts {
}
}
/**
* Gets the text for the source map.
*/
function getText() {
encodeLastRecordedSourceMapSpan();
@@ -382,6 +731,9 @@ namespace ts {
});
}
/**
* Gets the SourceMappingURL for the source map.
*/
function getSourceMappingURL() {
if (compilerOptions.inlineSourceMap) {
// Encode the sourceMap into the sourceMap url
+114 -63
View File
@@ -1,18 +1,17 @@
/// <reference path="core.ts"/>
namespace ts {
export type FileWatcherCallback = (path: string, removed?: boolean) => void;
export type DirectoryWatcherCallback = (path: string) => void;
export type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
export type DirectoryWatcherCallback = (directoryName: string) => void;
export interface System {
args: string[];
newLine: string;
useCaseSensitiveFileNames: boolean;
/*@internal*/ developmentMode?: boolean;
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@@ -21,13 +20,16 @@ namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
/*@internal*/ getEnvironmentVariable(name: string): string;
/*@internal*/ tryEnableSourceMapsForHost?(): void;
}
interface WatchedFile {
filePath: Path;
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
@@ -37,7 +39,7 @@ namespace ts {
}
export interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
@@ -74,6 +76,7 @@ namespace ts {
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
getEnvironmentVariable?(name: string): string;
};
export var sys: System = (function () {
@@ -213,6 +216,9 @@ namespace ts {
getCurrentDirectory() {
return new ActiveXObject("WScript.Shell").CurrentDirectory;
},
getEnvironmentVariable(name: string) {
return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings(`%${name}%`);
},
readDirectory,
exit(exitCode?: number): void {
try {
@@ -228,6 +234,7 @@ namespace ts {
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
const _crypto = require("crypto");
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
@@ -246,13 +253,13 @@ namespace ts {
return;
}
_fs.stat(watchedFile.filePath, (err: any, stats: any) => {
_fs.stat(watchedFile.fileName, (err: any, stats: any) => {
if (err) {
watchedFile.callback(watchedFile.filePath);
watchedFile.callback(watchedFile.fileName);
}
else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
watchedFile.mtime = getModifiedTime(watchedFile.filePath);
watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0);
watchedFile.mtime = getModifiedTime(watchedFile.fileName);
watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);
}
});
}
@@ -280,11 +287,11 @@ namespace ts {
}, interval);
}
function addFile(filePath: Path, callback: FileWatcherCallback): WatchedFile {
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
const file: WatchedFile = {
filePath,
fileName,
callback,
mtime: getModifiedTime(filePath)
mtime: getModifiedTime(fileName)
};
watchedFiles.push(file);
@@ -308,26 +315,26 @@ namespace ts {
}
function createWatchedFileSet() {
const dirWatchers = createFileMap<DirectoryWatcher>();
const dirWatchers: Map<DirectoryWatcher> = {};
// One file can have multiple watchers
const fileWatcherCallbacks = createFileMap<FileWatcherCallback[]>();
const fileWatcherCallbacks: Map<FileWatcherCallback[]> = {};
return { addFile, removeFile };
function reduceDirWatcherRefCountForFile(filePath: Path) {
const dirPath = getDirectoryPath(filePath);
if (dirWatchers.contains(dirPath)) {
const watcher = dirWatchers.get(dirPath);
function reduceDirWatcherRefCountForFile(fileName: string) {
const dirName = getDirectoryPath(fileName);
if (hasProperty(dirWatchers, dirName)) {
const watcher = dirWatchers[dirName];
watcher.referenceCount -= 1;
if (watcher.referenceCount <= 0) {
watcher.close();
dirWatchers.remove(dirPath);
delete dirWatchers[dirName];
}
}
}
function addDirWatcher(dirPath: Path): void {
if (dirWatchers.contains(dirPath)) {
const watcher = dirWatchers.get(dirPath);
function addDirWatcher(dirPath: string): void {
if (hasProperty(dirWatchers, dirPath)) {
const watcher = dirWatchers[dirPath];
watcher.referenceCount += 1;
return;
}
@@ -338,51 +345,52 @@ namespace ts {
(eventName: string, relativeFileName: string) => fileEventHandler(eventName, relativeFileName, dirPath)
);
watcher.referenceCount = 1;
dirWatchers.set(dirPath, watcher);
dirWatchers[dirPath] = watcher;
return;
}
function addFileWatcherCallback(filePath: Path, callback: FileWatcherCallback): void {
if (fileWatcherCallbacks.contains(filePath)) {
fileWatcherCallbacks.get(filePath).push(callback);
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
if (hasProperty(fileWatcherCallbacks, filePath)) {
fileWatcherCallbacks[filePath].push(callback);
}
else {
fileWatcherCallbacks.set(filePath, [callback]);
fileWatcherCallbacks[filePath] = [callback];
}
}
function addFile(filePath: Path, callback: FileWatcherCallback): WatchedFile {
addFileWatcherCallback(filePath, callback);
addDirWatcher(getDirectoryPath(filePath));
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
addFileWatcherCallback(fileName, callback);
addDirWatcher(getDirectoryPath(fileName));
return { filePath, callback };
return { fileName, callback };
}
function removeFile(watchedFile: WatchedFile) {
removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback);
reduceDirWatcherRefCountForFile(watchedFile.filePath);
removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback);
reduceDirWatcherRefCountForFile(watchedFile.fileName);
}
function removeFileWatcherCallback(filePath: Path, callback: FileWatcherCallback) {
if (fileWatcherCallbacks.contains(filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath));
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
if (hasProperty(fileWatcherCallbacks, filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks[filePath]);
if (newCallbacks.length === 0) {
fileWatcherCallbacks.remove(filePath);
delete fileWatcherCallbacks[filePath];
}
else {
fileWatcherCallbacks.set(filePath, newCallbacks);
fileWatcherCallbacks[filePath] = newCallbacks;
}
}
}
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: Path) {
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: string) {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
const filePath = typeof relativeFileName !== "string"
const fileName = typeof relativeFileName !== "string"
? undefined
: toPath(relativeFileName, baseDirPath, createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
if (eventName === "change" && fileWatcherCallbacks.contains(filePath)) {
for (const fileCallback of fileWatcherCallbacks.get(filePath)) {
fileCallback(filePath);
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
// Some applications save a working file via rename operations
if ((eventName === "change" || eventName === "rename") && hasProperty(fileWatcherCallbacks, fileName)) {
for (const fileCallback of fileWatcherCallbacks[fileName]) {
fileCallback(fileName);
}
}
}
@@ -413,7 +421,7 @@ namespace ts {
const useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
function readFile(fileName: string, encoding?: string): string {
if (!_fs.existsSync(fileName)) {
if (!fileExists(fileName)) {
return undefined;
}
const buffer = _fs.readFileSync(fileName);
@@ -464,6 +472,32 @@ namespace ts {
return useCaseSensitiveFileNames ? path : path.toLowerCase();
}
const enum FileSystemEntryKind {
File,
Directory
}
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {
try {
const stat = _fs.statSync(path);
switch (entryKind) {
case FileSystemEntryKind.File: return stat.isFile();
case FileSystemEntryKind.Directory: return stat.isDirectory();
}
}
catch (e) {
return false;
}
}
function fileExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.File);
}
function directoryExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.Directory);
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
@@ -473,6 +507,11 @@ namespace ts {
const files = _fs.readdirSync(path || ".").sort();
const directories: string[] = [];
for (const current of files) {
// This is necessary because on some file system node fails to exclude
// "." and "..". See https://github.com/nodejs/node/issues/4002
if (current === "." || current === "..") {
continue;
}
const name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
const stat = _fs.statSync(name);
@@ -496,24 +535,23 @@ namespace ts {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
developmentMode: /^development$/i.test(String(process.env.NODE_ENV)),
write(s: string): void {
process.stdout.write(s);
},
readFile,
writeFile,
watchFile: (filePath, callback) => {
// Node 4.0 stablized the `fs.watch` function on Windows which avoids polling
watchFile: (fileName, callback) => {
// Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling
// and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
const watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet;
const watchedFile = watchSet.addFile(filePath, callback);
const watchedFile = watchSet.addFile(fileName, callback);
return {
close: () => watchSet.removeFile(watchedFile)
};
},
watchDirectory: (path, callback, recursive) => {
watchDirectory: (directoryName, callback, recursive) => {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
@@ -525,7 +563,7 @@ namespace ts {
}
return _fs.watch(
path,
directoryName,
options,
(eventName: string, relativeFileName: string) => {
// In watchDirectory we only care about adding and removing files (when event name is
@@ -533,7 +571,7 @@ namespace ts {
// event name is "change")
if (eventName === "rename") {
// When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? relativeFileName : normalizePath(combinePaths(path, relativeFileName)));
callback(!relativeFileName ? relativeFileName : normalizePath(combinePaths(directoryName, relativeFileName)));
};
}
);
@@ -541,12 +579,8 @@ namespace ts {
resolvePath: function (path: string): string {
return _path.resolve(path);
},
fileExists(path: string): boolean {
return _fs.existsSync(path);
},
directoryExists(path: string) {
return _fs.existsSync(path) && _fs.statSync(path).isDirectory();
},
fileExists,
directoryExists,
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
@@ -558,7 +592,23 @@ namespace ts {
getCurrentDirectory() {
return process.cwd();
},
getEnvironmentVariable(name: string) {
return process.env[name] || "";
},
readDirectory,
getModifiedTime(path) {
try {
return _fs.statSync(path).mtime;
}
catch (e) {
return undefined;
}
},
createHash(data) {
const hash = _crypto.createHash("md5");
hash.update(data);
return hash.digest("hex");
},
getMemoryUsage() {
if (global.gc) {
global.gc();
@@ -604,12 +654,16 @@ namespace ts {
createDirectory: ChakraHost.createDirectory,
getExecutingFilePath: () => ChakraHost.executingFile,
getCurrentDirectory: () => ChakraHost.currentDirectory,
getEnvironmentVariable: ChakraHost.getEnvironmentVariable || ((name: string) => ""),
readDirectory: ChakraHost.readDirectory,
exit: ChakraHost.quit,
};
}
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
@@ -617,9 +671,6 @@ namespace ts {
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
else if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else {
return undefined; // Unsupported host
}
+188 -16
View File
@@ -20,7 +20,7 @@ namespace ts {
};
const enum SyntaxKindFeatureFlags {
ExpressionSubstitution = 1 << 0,
Substitution = 1 << 0,
EmitNotifications = 1 << 1,
}
@@ -56,7 +56,7 @@ namespace ts {
* @param transforms An array of Transformers.
*/
export function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]) {
const nodeEmitFlags: NodeEmitFlags[] = [];
const nodeEmitOptions: NodeEmitOptions[] = [];
const lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = [];
const lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = [];
const enabledSyntaxKindFeatures = new Array<SyntaxKindFeatureFlags>(SyntaxKind.Count);
@@ -64,25 +64,32 @@ namespace ts {
let hoistedVariableDeclarations: VariableDeclaration[];
let hoistedFunctionDeclarations: FunctionDeclaration[];
let currentSourceFile: SourceFile;
let lexicalEnvironmentDisabled: boolean;
// The transformation context is provided to each transformer as part of transformer
// initialization.
const context: TransformationContext = {
getCompilerOptions: () => host.getCompilerOptions(),
getEmitResolver: () => resolver,
getEmitHost: () => host,
getNodeEmitFlags,
setNodeEmitFlags,
getSourceMapRange,
setSourceMapRange,
getTokenSourceMapRange,
setTokenSourceMapRange,
getCommentRange,
setCommentRange,
hoistVariableDeclaration,
hoistFunctionDeclaration,
startLexicalEnvironment,
endLexicalEnvironment,
identifierSubstitution: node => node,
expressionSubstitution: node => node,
enableExpressionSubstitution,
isExpressionSubstitutionEnabled,
onEmitNode: (node, emit) => emit(node),
onSubstituteNode,
enableSubstitution,
isSubstitutionEnabled,
onEmitNode,
enableEmitNotification,
isEmitNotificationEnabled,
isEmitNotificationEnabled
};
// Chain together and initialize each transformer.
@@ -105,31 +112,94 @@ namespace ts {
return transformation(sourceFile);
}
function enableExpressionSubstitution(kind: SyntaxKind) {
enabledSyntaxKindFeatures[kind] |= SyntaxKindFeatureFlags.ExpressionSubstitution;
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
function enableSubstitution(kind: SyntaxKind) {
enabledSyntaxKindFeatures[kind] |= SyntaxKindFeatureFlags.Substitution;
}
function isExpressionSubstitutionEnabled(node: Node) {
return (enabledSyntaxKindFeatures[node.kind] & SyntaxKindFeatureFlags.ExpressionSubstitution) !== 0;
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
function isSubstitutionEnabled(node: Node) {
return (enabledSyntaxKindFeatures[node.kind] & SyntaxKindFeatureFlags.Substitution) !== 0;
}
/**
* Default hook for node substitutions.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is to be used in an expression
* position.
*/
function onSubstituteNode(node: Node, isExpression: boolean) {
return node;
}
/**
* Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
*/
function enableEmitNotification(kind: SyntaxKind) {
enabledSyntaxKindFeatures[kind] |= SyntaxKindFeatureFlags.EmitNotifications;
}
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
function isEmitNotificationEnabled(node: Node) {
return (enabledSyntaxKindFeatures[node.kind] & SyntaxKindFeatureFlags.EmitNotifications) !== 0
|| (getNodeEmitFlags(node) & NodeEmitFlags.AdviseOnEmitNode) !== 0;
}
/**
* Default hook for node emit.
*
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(node: Node, emit: (node: Node) => void) {
// Ensure that lexical environment modifications are disabled during the print phase.
if (!lexicalEnvironmentDisabled) {
const savedLexicalEnvironmentDisabled = lexicalEnvironmentDisabled;
lexicalEnvironmentDisabled = true;
emit(node);
lexicalEnvironmentDisabled = savedLexicalEnvironmentDisabled;
return;
}
emit(node);
}
function getEmitOptions(node: Node, create?: boolean) {
let options = isSourceTreeNode(node)
? nodeEmitOptions[getNodeId(node)]
: node.emitOptions;
if (!options && create) {
options = { };
if (isSourceTreeNode(node)) {
nodeEmitOptions[getNodeId(node)] = options;
}
else {
node.emitOptions = options;
}
}
return options;
}
/**
* Gets flags that control emit behavior of a node.
*/
function getNodeEmitFlags(node: Node) {
while (node) {
const nodeId = getNodeId(node);
if (nodeEmitFlags[nodeId] !== undefined) {
return nodeEmitFlags[nodeId];
const options = getEmitOptions(node, /*create*/ false);
if (options && options.flags !== undefined) {
if (options.flags & NodeEmitFlags.Merge) {
options.flags = (options.flags | getNodeEmitFlags(node.original)) & ~NodeEmitFlags.Merge;
}
return options.flags;
}
node = node.original;
@@ -142,7 +212,103 @@ namespace ts {
* Sets flags that control emit behavior of a node.
*/
function setNodeEmitFlags<T extends Node>(node: T, flags: NodeEmitFlags) {
nodeEmitFlags[getNodeId(node)] = flags;
const options = getEmitOptions(node, /*create*/ true);
if (flags & NodeEmitFlags.Merge) {
flags = options.flags | (flags & ~NodeEmitFlags.Merge);
}
options.flags = flags;
return node;
}
/**
* Gets a custom text range to use when emitting source maps.
*/
function getSourceMapRange(node: Node) {
let current = node;
while (current) {
const options = getEmitOptions(current);
if (options && options.sourceMapRange !== undefined) {
return options.sourceMapRange;
}
current = current.original;
}
return node;
}
/**
* Sets a custom text range to use when emitting source maps.
*/
function setSourceMapRange<T extends Node>(node: T, range: TextRange) {
getEmitOptions(node, /*create*/ true).sourceMapRange = range;
return node;
}
function getTokenSourceMapRanges(node: Node) {
let current = node;
while (current) {
const options = getEmitOptions(current);
if (options && options.tokenSourceMapRange) {
return options.tokenSourceMapRange;
}
current = current.original;
}
return undefined;
}
/**
* Gets the TextRange to use for source maps for a token of a node.
*/
function getTokenSourceMapRange(node: Node, token: SyntaxKind) {
const ranges = getTokenSourceMapRanges(node);
if (ranges) {
return ranges[token];
}
return undefined;
}
/**
* Sets the TextRange to use for source maps for a token of a node.
*/
function setTokenSourceMapRange<T extends Node>(node: T, token: SyntaxKind, range: TextRange) {
const options = getEmitOptions(node, /*create*/ true);
if (!options.tokenSourceMapRange) {
const existingRanges = getTokenSourceMapRanges(node);
const ranges = existingRanges ? clone(existingRanges) : { };
options.tokenSourceMapRange = ranges;
}
options.tokenSourceMapRange[token] = range;
return node;
}
/**
* Gets a custom text range to use when emitting comments.
*/
function getCommentRange(node: Node) {
let current = node;
while (current) {
const options = getEmitOptions(current, /*create*/ false);
if (options && options.commentRange !== undefined) {
return options.commentRange;
}
current = current.original;
}
return node;
}
/**
* Sets a custom text range to use when emitting comments.
*/
function setCommentRange<T extends Node>(node: T, range: TextRange) {
getEmitOptions(node, /*create*/ true).commentRange = range;
return node;
}
@@ -150,6 +316,7 @@ namespace ts {
* Records a hoisted variable declaration for the provided name within a lexical environment.
*/
function hoistVariableDeclaration(name: Identifier): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
const decl = createVariableDeclaration(name);
if (!hoistedVariableDeclarations) {
hoistedVariableDeclarations = [decl];
@@ -163,6 +330,7 @@ namespace ts {
* Records a hoisted function declaration within a lexical environment.
*/
function hoistFunctionDeclaration(func: FunctionDeclaration): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
if (!hoistedFunctionDeclarations) {
hoistedFunctionDeclarations = [func];
}
@@ -176,6 +344,8 @@ namespace ts {
* are pushed onto a stack, and the related storage variables are reset.
*/
function startLexicalEnvironment(): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase.");
// Save the current lexical environment. Rather than resizing the array we adjust the
// stack size variable. This allows us to reuse existing array slots we've
// already allocated between transformations to avoid allocation and GC overhead during
@@ -192,6 +362,8 @@ namespace ts {
* any hoisted declarations added in this environment are returned.
*/
function endLexicalEnvironment(): Statement[] {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase.");
let statements: Statement[];
if (hoistedVariableDeclarations || hoistedFunctionDeclarations) {
if (hoistedFunctionDeclarations) {
+74 -52
View File
@@ -13,13 +13,20 @@ namespace ts {
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenDestructuringAssignment(
context: TransformationContext,
node: BinaryExpression,
needsValue: boolean,
recordTempVariable: (node: Identifier) => void,
visitor?: (node: Node) => Node) {
visitor?: (node: Node) => VisitResult<Node>): Expression {
if (isEmptyObjectLiteralOrArrayLiteral(node.left)) {
return node.right;
const right = node.right;
if (isDestructuringAssignment(right)) {
return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor);
}
else {
return node.right;
}
}
let location: TextRange = node;
@@ -32,7 +39,7 @@ namespace ts {
//
// The source map location for the assignment should point to the entire binary
// expression.
value = ensureIdentifier(node.right, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor);
}
else if (nodeIsSynthesized(node)) {
// Generally, the source map location for a destructuring assignment is the root
@@ -41,10 +48,10 @@ namespace ts {
// However, if the root expression is synthesized (as in the case
// of the initializer when transforming a ForOfStatement), then the source map
// location should point to the right-hand value of the expression.
location = node.right;
location = value;
}
flattenDestructuring(node, value, location, emitAssignment, emitTempVariableAssignment, visitor);
flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor);
if (needsValue) {
expressions.push(value);
@@ -56,17 +63,17 @@ namespace ts {
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
const expression = createAssignment(name, value, location);
if (isSimpleExpression(value)) {
expression.disableSourceMap = true;
}
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(expression, NodeEmitFlags.NoNestedSourceMaps);
aggregateTransformFlags(expression);
expressions.push(expression);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable();
recordTempVariable(name);
const name = createTempVariable(recordTempVariable);
emitAssignment(name, value, location);
return name;
}
@@ -79,25 +86,30 @@ namespace ts {
* @param value The rhs value for the binding pattern.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenParameterDestructuring(node: ParameterDeclaration, value: Expression, visitor?: (node: Node) => Node) {
export function flattenParameterDestructuring(
context: TransformationContext,
node: ParameterDeclaration,
value: Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const declarations: VariableDeclaration[] = [];
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
return declarations;
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
const declaration = createVariableDeclaration(name, value, location);
if (isSimpleExpression(value)) {
declaration.disableSourceMap = true;
}
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(declaration, NodeEmitFlags.NoNestedSourceMaps);
aggregateTransformFlags(declaration);
declarations.push(declaration);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable();
const name = createTempVariable(/*recordTempVariable*/ undefined);
emitAssignment(name, value, location);
return name;
}
@@ -110,30 +122,31 @@ namespace ts {
* @param value An optional rhs value for the binding pattern.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenVariableDestructuring(node: VariableDeclaration, value?: Expression, visitor?: (node: Node) => Node) {
export function flattenVariableDestructuring(
context: TransformationContext,
node: VariableDeclaration,
value?: Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const declarations: VariableDeclaration[] = [];
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
return declarations;
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
const declaration = createVariableDeclaration(name, value, location);
if (declarations.length === 0) {
declaration.pos = -1;
}
if (isSimpleExpression(value)) {
declaration.disableSourceMap = true;
}
declaration.original = original;
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(declaration, NodeEmitFlags.NoNestedSourceMaps);
declarations.push(declaration);
aggregateTransformFlags(declaration);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable();
const name = createTempVariable(/*recordTempVariable*/ undefined);
emitAssignment(name, value, location, /*original*/ undefined);
return name;
}
@@ -148,14 +161,15 @@ namespace ts {
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenVariableDestructuringToExpression(
context: TransformationContext,
node: VariableDeclaration,
recordTempVariable: (name: Identifier) => void,
nameSubstitution?: (name: Identifier) => Expression,
visitor?: (node: Node) => Node) {
visitor?: (node: Node) => VisitResult<Node>) {
const pendingAssignments: Expression[] = [];
flattenDestructuring(node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment);
flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor);
const expression = inlineExpressions(pendingAssignments);
aggregateTransformFlags(expression);
@@ -167,31 +181,32 @@ namespace ts {
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable();
recordTempVariable(name);
const name = createTempVariable(recordTempVariable);
emitPendingAssignment(name, value, location, /*original*/ undefined);
return name;
}
function emitPendingAssignment(name: Expression, value: Expression, location: TextRange, original: Node) {
const expression = createAssignment(name, value, location);
if (isSimpleExpression(value)) {
expression.disableSourceMap = true;
}
expression.original = original;
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(expression, NodeEmitFlags.NoNestedSourceMaps);
pendingAssignments.push(expression);
return expression;
}
}
function flattenDestructuring(
context: TransformationContext,
root: BindingElement | BinaryExpression,
value: Expression,
location: TextRange,
emitAssignment: (name: Identifier, value: Expression, location: TextRange, original: Node) => void,
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
visitor?: (node: Node) => Node) {
visitor?: (node: Node) => VisitResult<Node>) {
if (value && visitor) {
value = visitNode(value, visitor, isExpression);
}
@@ -236,7 +251,7 @@ namespace ts {
emitArrayLiteralAssignment(<ArrayLiteralExpression>target, value, location);
}
else {
const name = cloneNode(<Identifier>target, /*location*/ target, /*flags*/ undefined, /*parent*/ undefined, /*original*/ target);
const name = getSynthesizedClone(<Identifier>target, { sourceMapRange: target, commentRange: target });
emitAssignment(name, value, location, /*original*/ undefined);
}
}
@@ -326,8 +341,7 @@ namespace ts {
}
}
else {
const clonedName = cloneNode(name, /*location*/ undefined, /*flags*/ undefined, /*parent*/ undefined, /*original*/ name);
emitAssignment(clonedName, value, target, target);
emitAssignment(name, value, target, target);
}
}
@@ -354,19 +368,20 @@ namespace ts {
ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)
);
}
else if (isIdentifier(propertyName)) {
return createPropertyAccess(
expression,
propertyName.text
);
else if (isLiteralExpression(propertyName)) {
const clone = getSynthesizedClone(propertyName);
clone.text = unescapeIdentifier(clone.text);
return createElementAccess(expression, clone);
}
else {
// We create a synthetic copy of the identifier in order to avoid the rewriting that might
// otherwise occur when the identifier is emitted.
return createElementAccess(
expression,
cloneNode(propertyName)
);
if (isGeneratedIdentifier(propertyName)) {
const clone = getSynthesizedClone(propertyName);
clone.text = unescapeIdentifier(clone.text);
return createPropertyAccess(expression, clone);
}
else {
return createPropertyAccess(expression, createIdentifier(unescapeIdentifier(propertyName.text)));
}
}
}
}
@@ -381,17 +396,24 @@ namespace ts {
* false if it is necessary to always emit an identifier.
* @param location The location to use for source maps and comments.
* @param emitTempVariableAssignment A callback used to emit a temporary variable.
* @param visitor An optional callback used to visit the value.
*/
function ensureIdentifier(
value: Expression,
reuseIdentifierExpressions: boolean,
location: TextRange,
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier) {
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
visitor?: (node: Node) => VisitResult<Node>) {
if (isIdentifier(value) && reuseIdentifierExpressions) {
return value;
}
else {
if (visitor) {
value = visitNode(value, visitor, isExpression);
}
return emitTempVariableAssignment(value, location);
}
}
}
}
File diff suppressed because it is too large Load Diff
+11 -11
View File
@@ -12,7 +12,7 @@ namespace ts {
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): Node {
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES7) {
return visitorWorker(node);
}
@@ -24,13 +24,15 @@ namespace ts {
}
}
function visitorWorker(node: Node) {
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
}
Debug.fail(`Unexpected node kind: ${formatSyntaxKind(node.kind)}.`);
default:
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
function visitBinaryExpression(node: BinaryExpression): Expression {
@@ -42,11 +44,9 @@ namespace ts {
let value: Expression;
if (isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
const expressionTemp = createTempVariable();
hoistVariableDeclaration(expressionTemp);
const expressionTemp = createTempVariable(hoistVariableDeclaration);
const argumentExpressionTemp = createTempVariable();
hoistVariableDeclaration(argumentExpressionTemp);
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
target = createElementAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
@@ -62,8 +62,7 @@ namespace ts {
}
else if (isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
const expressionTemp = createTempVariable();
hoistVariableDeclaration(expressionTemp);
const expressionTemp = createTempVariable(hoistVariableDeclaration);
target = createPropertyAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
@@ -90,7 +89,8 @@ namespace ts {
return createMathPow(left, right, /*location*/ node);
}
else {
Debug.fail(`Unexpected operator kind: ${formatSyntaxKind(node.operatorToken.kind)}.`);
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
}
+52 -24
View File
@@ -18,7 +18,7 @@ namespace ts {
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): Node {
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.Jsx) {
return visitorWorker(node);
}
@@ -30,16 +30,21 @@ namespace ts {
}
}
function visitorWorker(node: Node): Node {
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.JsxElement:
return visitJsxElement(<JsxElement>node);
return visitJsxElement(<JsxElement>node, /*isChild*/ false);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node);
}
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ false);
Debug.fail(`Unexpected node kind: ${formatSyntaxKind(node.kind)}.`);
case SyntaxKind.JsxExpression:
return visitJsxExpression(<JsxExpression>node);
default:
Debug.failBadSyntaxKind(node);
return undefined;
}
}
function transformJsxChildToExpression(node: JsxChild): Expression {
@@ -51,24 +56,26 @@ namespace ts {
return visitJsxExpression(<JsxExpression>node);
case SyntaxKind.JsxElement:
return visitJsxElement(<JsxElement>node);
return visitJsxElement(<JsxElement>node, /*isChild*/ true);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node);
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ true);
default:
Debug.failBadSyntaxKind(node);
return undefined;
}
Debug.fail(`Unexpected node kind: ${formatSyntaxKind(node.kind)}.`);
}
function visitJsxElement(node: JsxElement) {
return visitJsxOpeningLikeElement(node.openingElement, node.children);
function visitJsxElement(node: JsxElement, isChild: boolean) {
return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
}
function visitJsxSelfClosingElement(node: JsxSelfClosingElement) {
return visitJsxOpeningLikeElement(node, /*children*/ undefined);
function visitJsxSelfClosingElement(node: JsxSelfClosingElement, isChild: boolean) {
return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
}
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: JsxChild[]) {
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: JsxChild[], isChild: boolean, location: TextRange) {
const tagName = getTagName(node);
let objectProperties: Expression;
const attrs = node.attributes;
@@ -93,17 +100,25 @@ namespace ts {
}
// Either emit one big object literal (no spread attribs), or
// a call to React.__spread
// a call to the __assign helper.
objectProperties = singleOrUndefined(segments)
|| createJsxSpread(compilerOptions.reactNamespace, segments);
|| createAssignHelper(segments);
}
return createJsxCreateElement(
const element = createReactCreateElement(
compilerOptions.reactNamespace,
tagName,
objectProperties,
filter(map(children, transformJsxChildToExpression), isDefined)
filter(map(children, transformJsxChildToExpression), isDefined),
node,
location
);
if (isChild) {
startOnNewLine(element);
}
return element;
}
function transformJsxSpreadAttributeToExpression(node: JsxSpreadAttribute) {
@@ -112,12 +127,25 @@ namespace ts {
function transformJsxAttributeToObjectLiteralElement(node: JsxAttribute) {
const name = getAttributeName(node);
const expression = node.initializer
? visitNode(node.initializer, visitor, isExpression)
: createLiteral(true);
const expression = transformJsxAttributeInitializer(node.initializer);
return createPropertyAssignment(name, expression);
}
function transformJsxAttributeInitializer(node: StringLiteral | JsxExpression) {
if (node === undefined) {
return createLiteral(true);
}
else if (node.kind === SyntaxKind.StringLiteral) {
return node;
}
else if (node.kind === SyntaxKind.JsxExpression) {
return visitJsxExpression(<JsxExpression>node);
}
else {
Debug.failBadSyntaxKind(node);
}
}
function visitJsxText(node: JsxText) {
const text = getTextOfNode(node, /*includeTrivia*/ true);
let parts: Expression[];
@@ -214,10 +242,10 @@ namespace ts {
function getAttributeName(node: JsxAttribute): StringLiteral | Identifier {
const name = node.name;
if (/^[A-Za-z_]\w*$/.test(name.text)) {
return createLiteral(name.text);
return name;
}
else {
return name;
return createLiteral(name.text);
}
}
+119
View File
@@ -4,10 +4,129 @@
/*@internal*/
namespace ts {
export function transformES6Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
let currentSourceFile: SourceFile;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
return visitEachChild(node, visitor, context);
}
return node;
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportClause:
return visitImportClause(<ImportClause>node);
case SyntaxKind.NamedImports:
case SyntaxKind.NamespaceImport:
return visitNamedBindings(<NamedImportBindings>node);
case SyntaxKind.ImportSpecifier:
return visitImportSpecifier(<ImportSpecifier>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.NamedExports:
return visitNamedExports(<NamedExports>node);
case SyntaxKind.ExportSpecifier:
return visitExportSpecifier(<ExportSpecifier>node);
}
return node;
}
function visitExportAssignment(node: ExportAssignment): ExportAssignment {
if (node.isExportEquals) {
return undefined; // do not emit export equals for ES6
}
const original = getOriginalNode(node);
return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node: undefined;
}
function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration {
if (!node.exportClause) {
return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
return undefined;
}
const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true);
if (node.exportClause === newExportClause) {
return node;
}
return newExportClause
? createExportDeclaration(newExportClause, node.moduleSpecifier)
: undefined;
}
function visitNamedExports(node: NamedExports): NamedExports {
const newExports = visitNodes(node.elements, visitor, isExportSpecifier);
if (node.elements === newExports) {
return node;
}
return newExports.length ? createNamedExports(newExports) : undefined;
}
function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier {
return resolver.isValueAliasDeclaration(node) ? node : undefined;
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration {
return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
function visitImportDeclaration(node: ImportDeclaration) {
if (node.importClause) {
const newImportClause = visitNode(node.importClause, visitor, isImportClause);
if (!newImportClause.name && !newImportClause.namedBindings) {
return undefined;
}
else if (newImportClause !== node.importClause) {
return createImportDeclaration(newImportClause, node.moduleSpecifier);
}
}
return node;
}
function visitImportClause(node: ImportClause): ImportClause {
let newDefaultImport = node.name;
if (!resolver.isReferencedAliasDeclaration(node)) {
newDefaultImport = undefined;
}
const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true);
return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings
? createImportClause(newDefaultImport, newNamedBindings)
: node;
}
function visitNamedBindings(node: NamedImportBindings): VisitResult<NamedImportBindings> {
if (node.kind === SyntaxKind.NamespaceImport) {
return resolver.isReferencedAliasDeclaration(node) ? node: undefined;
}
else {
const newNamedImportElements = visitNodes((<NamedImports>node).elements, visitor, isImportSpecifier);
if (!newNamedImportElements || newNamedImportElements.length == 0) {
return undefined;
}
if (newNamedImportElements === (<NamedImports>node).elements) {
return node;
}
return createNamedImports(newNamedImportElements);
}
}
function visitImportSpecifier(node: ImportSpecifier) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
}
}
File diff suppressed because it is too large Load Diff
+256 -159
View File
@@ -5,51 +5,68 @@
namespace ts {
export function transformSystemModule(context: TransformationContext) {
interface DependencyGroup {
name: Identifier;
name: StringLiteral;
externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
}
const {
getNodeEmitFlags,
setNodeEmitFlags,
getCommentRange,
setCommentRange,
getSourceMapRange,
setSourceMapRange,
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
hoistFunctionDeclaration,
setNodeEmitFlags
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const host = context.getEmitHost();
const languageVersion = getEmitScriptTarget(compilerOptions);
const previousExpressionSubstitution = context.expressionSubstitution;
context.enableExpressionSubstitution(SyntaxKind.Identifier);
context.enableExpressionSubstitution(SyntaxKind.BinaryExpression);
context.enableExpressionSubstitution(SyntaxKind.PostfixUnaryExpression);
context.expressionSubstitution = substituteExpression;
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(SyntaxKind.Identifier);
context.enableSubstitution(SyntaxKind.BinaryExpression);
context.enableSubstitution(SyntaxKind.PrefixUnaryExpression);
context.enableSubstitution(SyntaxKind.PostfixUnaryExpression);
context.enableEmitNotification(SyntaxKind.SourceFile);
const exportFunctionForFileMap: Identifier[] = [];
let currentSourceFile: SourceFile;
let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
let exportSpecifiers: Map<ExportSpecifier[]>;
let exportEquals: ExportAssignment;
let hasExportStars: boolean;
let hasExportStarsToExportValues: boolean;
let exportFunctionForFile: Identifier;
let contextObjectForFile: Identifier;
let exportedLocalNames: Identifier[];
let exportedFunctionDeclarations: ExpressionStatement[];
let enclosingBlockScopedContainer: Node;
let currentParent: Node;
let currentNode: Node;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
currentNode = node;
// Perform the transformation.
const updated = transformSystemModuleWorker(node);
aggregateTransformFlags(updated);
currentSourceFile = undefined;
externalImports = undefined;
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStars = false;
hasExportStarsToExportValues = false;
exportFunctionForFile = undefined;
contextObjectForFile = undefined;
exportedLocalNames = undefined;
@@ -76,66 +93,50 @@ namespace ts {
Debug.assert(!exportFunctionForFile);
// Collect information about the external module and dependency groups.
({ externalImports, exportSpecifiers, exportEquals, hasExportStars } = collectExternalModuleInfo(node, resolver));
({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver));
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
exportFunctionForFile = createUniqueName("exports");
contextObjectForFile = createUniqueName("context");
exportFunctionForFileMap[getNodeId(node)] = exportFunctionForFile;
const dependencyGroups = collectDependencyGroups(externalImports);
const statements: Statement[] = [];
// Add any prologue directives.
const statementOffset = copyPrologueDirectives(node.statements, statements);
// Add the body of the module.
addSystemModuleBody(statements, node, dependencyGroups);
// var __moduleName = context_1 && context_1.id;
addNode(statements,
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
"__moduleName",
createLogicalAnd(
contextObjectForFile,
createPropertyAccess(contextObjectForFile, "id")
)
)
])
const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions);
const dependencies = createArrayLiteral(map(dependencyGroups, getNameOfDependencyGroup));
const body = createFunctionExpression(
/*asteriskToken*/ undefined,
/*name*/ undefined,
[
createParameter(exportFunctionForFile),
createParameter(contextObjectForFile)
],
setNodeEmitFlags(
createBlock(statements, /*location*/ undefined, /*multiLine*/ true),
NodeEmitFlags.EmitEmitHelpers
)
);
// Add the body of the module.
addSystemModuleBody(statements, node, dependencyGroups, statementOffset);
// Write the call to `System.register`
// Clear the emit-helpers flag for later passes since we'll have already used it in the module body
// So the helper will be emit at the correct position instead of at the top of the source-file
return updateSourceFile(node, [
createStatement(
createCall(
createPropertyAccess(createIdentifier("System"), "register"),
[
node.moduleName ? createLiteral(node.moduleName) : undefined,
createArrayLiteral(map(dependencyGroups, getNameOfDependencyGroup)),
createFunctionExpression(
/*asteriskToken*/ undefined,
/*name*/ undefined,
[
createParameter(exportFunctionForFile),
createParameter(contextObjectForFile)
],
setNodeEmitFlags(
setMultiLine(
createBlock(statements),
/*multiLine*/ true
),
NodeEmitFlags.EmitEmitHelpers
)
)
]
moduleName
? [moduleName, dependencies, body]
: [dependencies, body]
)
)
]);
], /*nodeEmitFlags*/ ~NodeEmitFlags.EmitEmitHelpers & getNodeEmitFlags(node));
}
/**
@@ -145,7 +146,7 @@ namespace ts {
* @param node The source file for the module.
* @param statementOffset The offset at which to begin visiting the statements of the SourceFile.
*/
function addSystemModuleBody(statements: Statement[], node: SourceFile, dependencyGroups: DependencyGroup[], statementOffset: number) {
function addSystemModuleBody(statements: Statement[], node: SourceFile, dependencyGroups: DependencyGroup[]) {
// Shape of the body in system modules:
//
// function (exports) {
@@ -193,6 +194,25 @@ namespace ts {
// only in the outer module body and not in the inner one.
startLexicalEnvironment();
// Add any prologue directives.
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict);
// var __moduleName = context_1 && context_1.id;
addNode(statements,
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
"__moduleName",
createLogicalAnd(
contextObjectForFile,
createPropertyAccess(contextObjectForFile, "id")
)
)
])
)
);
// Visit the statements of the source file, emitting any transformations into
// the `executeStatements` array. We do this *before* we fill the `setters` array
// as we both emit transformations as well as aggregate some data used when creating
@@ -222,11 +242,13 @@ namespace ts {
),
createPropertyAssignment("execute",
createFunctionExpression(
/*asteriskToken*/ node,
/*asteriskToken*/ undefined,
/*name*/ undefined,
[],
createBlock(
executeStatements
executeStatements,
/*location*/ undefined,
/*multiLine*/ true
)
)
)
@@ -238,6 +260,9 @@ namespace ts {
}
function addExportStarIfNeeded(statements: Statement[]) {
if (!hasExportStarsToExportValues) {
return;
}
// when resolving exports local exported entries/indirect exported entries in the module
// should always win over entries with similar names that were added via star exports
// to support this we store names of local/indirect exported entries in a set.
@@ -303,7 +328,7 @@ namespace ts {
createVariableDeclarationList([
createVariableDeclaration(
exportedNamesStorageRef,
createObjectLiteral(exportedNames)
createObjectLiteral(exportedNames, /*location*/ undefined, /*multiline*/ true)
)
])
)
@@ -320,10 +345,11 @@ namespace ts {
const setters: Expression[] = [];
for (const group of dependencyGroups) {
// derive a unique name for parameter from the first named entry in the group
const parameterName = createUniqueName(forEach(group.externalImports, getLocalNameTextForExternalImport) || "");
const localName = forEach(group.externalImports, i => getLocalNameForExternalImport(i, currentSourceFile));
const parameterName = localName ? getGeneratedNameForNode(localName) : createUniqueName("");
const statements: Statement[] = [];
for (const entry of group.externalImports) {
const importVariableName = getLocalNameForExternalImport(entry);
const importVariableName = getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
case SyntaxKind.ImportDeclaration:
if (!(<ImportDeclaration>entry).importClause) {
@@ -371,7 +397,7 @@ namespace ts {
createStatement(
createCall(
exportFunctionForFile,
[createObjectLiteral(properties)]
[createObjectLiteral(properties, /*location*/ undefined, /*multiline*/ true)]
)
)
);
@@ -400,15 +426,15 @@ namespace ts {
/*asteriskToken*/ undefined,
/*name*/ undefined,
[createParameter(parameterName)],
createBlock(statements)
createBlock(statements, /*location*/ undefined, /*multiLine*/ true)
)
);
}
return createArrayLiteral(setters);
return createArrayLiteral(setters, /*location*/ undefined, /*multiLine*/ true);
}
function visitSourceElement(node: Node): Node {
function visitSourceElement(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
@@ -427,7 +453,29 @@ namespace ts {
}
}
function visitNestedNode(node: Node): Node {
function visitNestedNode(node: Node): VisitResult<Node> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
const savedCurrentParent = currentParent;
const savedCurrentNode = currentNode;
const currentGrandparent = currentParent;
currentParent = currentNode;
currentNode = node;
if (currentParent && isBlockScope(currentParent, currentGrandparent)) {
enclosingBlockScopedContainer = currentParent;
}
const result = visitNestedNodeWorker(node);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
currentParent = savedCurrentParent;
currentNode = savedCurrentNode;
return result;
}
function visitNestedNodeWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
@@ -480,6 +528,9 @@ namespace ts {
case SyntaxKind.Block:
return visitBlock(<Block>node);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(<ExpressionStatement>node);
default:
return node;
}
@@ -487,7 +538,7 @@ namespace ts {
function visitImportDeclaration(node: ImportDeclaration): Node {
if (node.importClause && contains(externalImports, node)) {
hoistVariableDeclaration(getLocalNameForExternalImport(node));
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
}
return undefined;
@@ -495,18 +546,18 @@ namespace ts {
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): Node {
if (contains(externalImports, node)) {
hoistVariableDeclaration(getLocalNameForExternalImport(node));
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
}
// NOTE(rbuckton): Do we support export import = require('') in System?
return undefined;
}
function visitExportDeclaration(node: ExportDeclaration): OneOrMany<Statement> {
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
if (!node.moduleSpecifier) {
const statements: Statement[] = [];
addNodes(statements, map(node.exportClause.elements, visitExportSpecifier));
return createNodeArrayNode(statements);
return statements;
}
return undefined;
@@ -525,11 +576,13 @@ namespace ts {
}
function visitExportAssignment(node: ExportAssignment): Statement {
if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) {
return createExportStatement(
createLiteral("default"),
node.expression
);
if (!node.isExportEquals) {
if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) {
return createExportStatement(
createLiteral("default"),
node.expression
);
}
}
return undefined;
@@ -541,15 +594,22 @@ namespace ts {
*
* @param node The variable statement to visit.
*/
function visitVariableStatement(node: VariableStatement): OneOrMany<Statement> {
const isExported = (node.flags & NodeFlags.Export) !== 0;
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
const shouldHoist =
((getCombinedNodeFlags(getOriginalNode(node.declarationList)) & NodeFlags.BlockScoped) == 0) ||
enclosingBlockScopedContainer.kind === SyntaxKind.SourceFile;
if (!shouldHoist) {
return node;
}
const isExported = hasModifier(node, ModifierFlags.Export);
const expressions: Expression[] = [];
for (const variable of node.declarationList.declarations) {
addNode(expressions, transformVariable(variable, isExported));
addNode(expressions, <Expression>transformVariable(variable, isExported));
}
if (expressions.length) {
return createStatement(inlineExpressions(expressions));
return createStatement(inlineExpressions(expressions), node);
}
return undefined;
@@ -561,7 +621,7 @@ namespace ts {
* @param node The VariableDeclaration to transform.
* @param isExported A value used to indicate whether the containing statement was exported.
*/
function transformVariable(node: VariableDeclaration, isExported: boolean): Expression {
function transformVariable(node: VariableDeclaration, isExported: boolean): VariableDeclaration | Expression {
// Hoist any bound names within the declaration.
hoistBindingElement(node, isExported);
@@ -577,7 +637,7 @@ namespace ts {
}
else {
// If the variable has a BindingPattern, flatten the variable into multiple assignment expressions.
return flattenVariableDestructuringToExpression(node, hoistVariableDeclaration);
return flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration);
}
}
@@ -587,10 +647,10 @@ namespace ts {
* @param node The function declaration to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): Node {
if (node.flags & NodeFlags.Export) {
if (hasModifier(node, ModifierFlags.Export)) {
// If the function is exported, ensure it has a name and rewrite the function without any export flags.
const name = node.name || getGeneratedNameForNode(node);
node = createFunctionDeclaration(
const newNode = createFunctionDeclaration(
/*modifiers*/ undefined,
node.asteriskToken,
name,
@@ -601,9 +661,12 @@ namespace ts {
// Record a declaration export in the outer module body function.
recordExportedFunctionDeclaration(node);
if ((node.flags & NodeFlags.Default) === 0) {
if (!hasModifier(node, ModifierFlags.Default)) {
recordExportName(name);
}
setOriginalNode(newNode, node);
node = newNode;
}
// Hoist the function declaration to the outer module body function.
@@ -611,12 +674,30 @@ namespace ts {
return undefined;
}
function visitExpressionStatement(node: ExpressionStatement): VisitResult<Statement> {
const originalNode = getOriginalNode(node);
if ((originalNode.kind === SyntaxKind.ModuleDeclaration || originalNode.kind === SyntaxKind.EnumDeclaration) && hasModifier(originalNode, ModifierFlags.Export)) {
const name = getDeclarationName(<ModuleDeclaration | EnumDeclaration>originalNode);
// We only need to hoistVariableDeclaration for EnumDeclaration
// as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement
// which then call transformsVariable for each declaration in declarationList
if (originalNode.kind === SyntaxKind.EnumDeclaration) {
hoistVariableDeclaration(name);
}
return [
node,
createExportStatement(name, name)
];
}
return node;
}
/**
* Visits a ClassDeclaration, hoisting its name to the outer module body function.
*
* @param node The class declaration to visit.
*/
function visitClassDeclaration(node: ClassDeclaration): OneOrMany<Statement> {
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
// Hoist the name of the class declaration to the outer module body function.
const name = getDeclarationName(node);
hoistVariableDeclaration(name);
@@ -640,15 +721,19 @@ namespace ts {
);
// If the class was exported, write a declaration export to the inner module body function.
if (node.flags & NodeFlags.Export) {
if ((node.flags & NodeFlags.Default) === 0) {
if (hasModifier(node, ModifierFlags.Export)) {
if (!hasModifier(node, ModifierFlags.Default)) {
recordExportName(name);
}
addNode(statements, createDeclarationExport(node));
}
return createNodeArrayNode(statements);
return statements;
}
function shouldHoistLoopInitializer(node: VariableDeclarationList | Expression) {
return isVariableDeclarationList(node) && (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0;
}
/**
@@ -658,10 +743,10 @@ namespace ts {
*/
function visitForStatement(node: ForStatement): ForStatement {
const initializer = node.initializer;
if (isVariableDeclarationList(initializer)) {
if (shouldHoistLoopInitializer(initializer)) {
const expressions: Expression[] = [];
for (const variable of initializer.declarations) {
addNode(expressions, transformVariable(variable, /*isExported*/ false));
for (const variable of (<VariableDeclarationList>initializer).declarations) {
addNode(expressions, <Expression>transformVariable(variable, /*isExported*/ false));
};
return createFor(
@@ -691,7 +776,7 @@ namespace ts {
const name = firstDeclaration.name;
return isIdentifier(name)
? name
: flattenVariableDestructuringToExpression(firstDeclaration, hoistVariableDeclaration);
: flattenVariableDestructuringToExpression(context, firstDeclaration, hoistVariableDeclaration);
}
/**
@@ -701,9 +786,9 @@ namespace ts {
*/
function visitForInStatement(node: ForInStatement): ForInStatement {
const initializer = node.initializer;
if (isVariableDeclarationList(initializer)) {
if (shouldHoistLoopInitializer(initializer)) {
const updated = getMutableClone(node);
updated.initializer = transformForBinding(initializer);
updated.initializer = transformForBinding(<VariableDeclarationList>initializer);
updated.statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock);
return updated;
}
@@ -719,9 +804,9 @@ namespace ts {
*/
function visitForOfStatement(node: ForOfStatement): ForOfStatement {
const initializer = node.initializer;
if (isVariableDeclarationList(initializer)) {
if (shouldHoistLoopInitializer(initializer)) {
const updated = getMutableClone(node);
updated.initializer = transformForBinding(initializer);
updated.initializer = transformForBinding(<VariableDeclarationList>initializer);
updated.statement = visitNode(node.statement, visitNestedNode, isStatement, /*optional*/ false, liftToBlock);
return updated;
}
@@ -881,20 +966,47 @@ namespace ts {
// Substitutions
//
function onEmitNode(node: Node, emit: (node: Node) => void): void {
if (node.kind === SyntaxKind.SourceFile) {
exportFunctionForFile = exportFunctionForFileMap[getNodeId(node)];
previousOnEmitNode(node, emit);
exportFunctionForFile = undefined;
}
else {
previousOnEmitNode(node, emit);
}
}
/**
* Hooks node substitutions.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is to be used in an expression
* position.
*/
function onSubstituteNode(node: Node, isExpression: boolean) {
node = previousOnSubstituteNode(node, isExpression);
if (isExpression) {
return substituteExpression(<Expression>node);
}
return node;
}
/**
* Substitute the expression, if necessary.
*
* @param node The node to substitute.
*/
function substituteExpression(node: Expression): Expression {
node = previousExpressionSubstitution(node);
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
case SyntaxKind.BinaryExpression:
return substituteBinaryExpression(<BinaryExpression>node);
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return substitutePostfixUnaryExpression(<PostfixUnaryExpression>node);
return substituteUnaryExpression(<PrefixUnaryExpression | PostfixUnaryExpression>node);
}
return node;
}
@@ -905,7 +1017,10 @@ namespace ts {
function substituteExpressionIdentifier(node: Identifier): Expression {
const importDeclaration = resolver.getReferencedImportDeclaration(node);
if (importDeclaration) {
return createImportBinding(importDeclaration);
const importBinding = createImportBinding(importDeclaration);
if (importBinding) {
return importBinding;
}
}
return node;
@@ -1026,67 +1141,41 @@ namespace ts {
}
function substituteDestructuring(node: BinaryExpression) {
return flattenDestructuringAssignment(node, /*needsValue*/ true, hoistVariableDeclaration);
return flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration);
}
function substitutePostfixUnaryExpression(node: PostfixUnaryExpression): Expression {
function substituteUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression): Expression {
const operand = node.operand;
if (isIdentifier(operand)) {
const exportDeclaration = resolver.getReferencedExportContainer(operand);
if (exportDeclaration) {
const exportCall = createExportExpression(
operand,
createPrefix(node.operator, operand, node)
);
const operator = node.operator;
const substitute =
isIdentifier(operand) &&
(
node.kind === SyntaxKind.PostfixUnaryExpression ||
(node.kind === SyntaxKind.PrefixUnaryExpression && (operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken))
);
return node.operator === SyntaxKind.PlusPlusToken
? createSubtract(exportCall, createLiteral(1))
: createAdd(exportCall, createLiteral(1));
if (substitute) {
const exportDeclaration = resolver.getReferencedExportContainer(<Identifier>operand);
if (exportDeclaration) {
const expr = createPrefix(node.operator, operand, node);
setNodeEmitFlags(expr, NodeEmitFlags.NoSubstitution);
const call = createExportExpression(<Identifier>operand, expr);
if (node.kind === SyntaxKind.PrefixUnaryExpression) {
return call;
}
else {
// export function returns the value that was passes as the second argument
// however for postfix unary expressions result value should be the value before modification.
// emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)'
return operator === SyntaxKind.PlusPlusToken
? createSubtract(call, createLiteral(1))
: createAdd(call, createLiteral(1));
}
}
}
return node;
}
function getExternalModuleNameLiteral(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration) {
const moduleName = getExternalModuleName(importNode);
if (moduleName.kind === SyntaxKind.StringLiteral) {
return tryRenameExternalModule(<StringLiteral>moduleName)
|| getSynthesizedClone(<StringLiteral>moduleName);
}
return undefined;
}
/**
* Some bundlers (SystemJS builder) sometimes want to rename dependencies.
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName: LiteralExpression) {
if (currentSourceFile.renamedDependencies && hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
return createLiteral(currentSourceFile.renamedDependencies[moduleName.text]);
}
return undefined;
}
function getLocalNameTextForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string {
const name = getLocalNameForExternalImport(node);
return name ? name.text : undefined;
}
function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): Identifier {
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
return createIdentifier(getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name));
}
if (node.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node).importClause) {
return getGeneratedNameForNode(node);
}
if (node.kind === SyntaxKind.ExportDeclaration && (<ExportDeclaration>node).moduleSpecifier) {
return getGeneratedNameForNode(node);
}
}
/**
* Gets a name to use for a DeclarationStatement.
* @param node The declaration statement.
@@ -1130,14 +1219,17 @@ namespace ts {
]),
m,
createBlock([
createIf(
condition,
createStatement(
createAssignment(
createElementAccess(exports, n),
createElementAccess(m, n)
setNodeEmitFlags(
createIf(
condition,
createStatement(
createAssignment(
createElementAccess(exports, n),
createElementAccess(m, n)
)
)
)
),
NodeEmitFlags.SingleLine
)
])
),
@@ -1147,7 +1239,9 @@ namespace ts {
[exports]
)
)
])
],
/*location*/ undefined,
/*multiline*/ true)
)
);
@@ -1179,7 +1273,7 @@ namespace ts {
*/
function createDeclarationExport(node: DeclarationStatement) {
const declarationName = getDeclarationName(node);
const exportName = node.flags & NodeFlags.Default ? createLiteral("default") : declarationName;
const exportName = hasModifier(node, ModifierFlags.Default) ? createLiteral("default") : declarationName;
return createExportStatement(exportName, declarationName);
}
@@ -1189,12 +1283,14 @@ namespace ts {
if (isImportClause(importDeclaration)) {
importAlias = getGeneratedNameForNode(importDeclaration.parent);
name = createIdentifier("default");
name.originalKeywordKind = SyntaxKind.DefaultKeyword;
}
else if (isImportSpecifier(importDeclaration)) {
importAlias = getGeneratedNameForNode(importDeclaration.parent.parent.parent);
name = importDeclaration.propertyName || importDeclaration.name;
}
else {
return undefined;
}
if (name.originalKeywordKind && languageVersion === ScriptTarget.ES3) {
return createElementAccess(importAlias, createLiteral(name.text));
@@ -1209,7 +1305,7 @@ namespace ts {
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; i++) {
const externalImport = externalImports[i];
const externalModuleName = getExternalModuleNameLiteral(externalImport);
const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
const text = externalModuleName.text;
if (hasProperty(groupIndices, text)) {
// deduplicate/group entries in dependency list by the dependency name
@@ -1249,7 +1345,7 @@ namespace ts {
exportedFunctionDeclarations.push(createDeclarationExport(node));
}
function hoistBindingElement(node: VariableDeclaration | BindingElement, isExported: boolean) {
function hoistBindingElement(node: VariableDeclaration | BindingElement, isExported: boolean): void {
const name = node.name;
if (isIdentifier(name)) {
hoistVariableDeclaration(getSynthesizedClone(name));
@@ -1270,9 +1366,10 @@ namespace ts {
hoistBindingElement(node, /*isExported*/ false);
}
function updateSourceFile(node: SourceFile, statements: Statement[]) {
const updated = cloneNode(node, node, node.flags, /*parent*/ undefined, node);
function updateSourceFile(node: SourceFile, statements: Statement[], nodeEmitFlags: NodeEmitFlags) {
const updated = getMutableClone(node);
updated.statements = createNodeArray(statements, node.statements);
setNodeEmitFlags(updated, nodeEmitFlags);
return updated;
}
}
File diff suppressed because it is too large Load Diff
+74 -36
View File
@@ -14,6 +14,20 @@ namespace ts {
}
}
function reportEmittedFiles(files: string[], host: CompilerHost): void {
if (!files || files.length == 0) {
return;
}
const currentDir = sys.getCurrentDirectory();
for (const file of files) {
const filepath = getNormalizedAbsolutePath(file, currentDir);
sys.write(`TSFILE: ${filepath}${sys.newLine}`);
}
}
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
@@ -108,14 +122,13 @@ namespace ts {
sys.write(output);
}
const redForegroundEscapeSequence = "\u001b[91m";
const yellowForegroundEscapeSequence = "\u001b[93m";
const blueForegroundEscapeSequence = "\u001b[93m";
const gutterStyleSequence = "\u001b[100;30m";
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const elipsis = "...";
const ellipsis = "...";
const categoryFormatMap: Map<string> = {
[DiagnosticCategory.Warning]: yellowForegroundEscapeSequence,
[DiagnosticCategory.Error]: redForegroundEscapeSequence,
@@ -139,7 +152,7 @@ namespace ts {
const hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
let gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(elipsis.length, gutterWidth);
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
output += sys.newLine;
@@ -147,7 +160,7 @@ namespace ts {
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
output += formatAndReset(padLeft(elipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine;
output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine;
i = lastLine - 1;
}
@@ -327,21 +340,19 @@ namespace ts {
return sys.exit(ExitStatus.Success);
}
// Firefox has Object.prototype.watch
if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) {
if (isWatchSet(commandLine.options)) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (configFileName) {
const configFilePath = toPath(configFileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
configFileWatcher = sys.watchFile(configFilePath, configFileChanged);
configFileWatcher = sys.watchFile(configFileName, configFileChanged);
}
if (sys.watchDirectory && configFileName) {
const directory = ts.getDirectoryPath(configFileName);
directoryWatcher = sys.watchDirectory(
// When the configFileName is just "tsconfig.json", the watched directory should be
// the current direcotry; if there is a given "project" parameter, then the configFileName
// the current directory; if there is a given "project" parameter, then the configFileName
// is an absolute file name.
directory == "" ? "." : directory,
watchedDirectoryChanged, /*recursive*/ true);
@@ -376,12 +387,16 @@ namespace ts {
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options);
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options, configFileName);
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
if (isWatchSet(configParseResult.options) && !sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
return configParseResult;
}
@@ -415,7 +430,7 @@ namespace ts {
const compileResult = compile(rootFileNames, compilerOptions, compilerHost);
if (!compilerOptions.watch) {
if (!isWatchSet(compilerOptions)) {
return sys.exit(compileResult.exitStatus);
}
@@ -441,10 +456,9 @@ namespace ts {
}
// Use default host function
const sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
if (sourceFile && compilerOptions.watch) {
if (sourceFile && isWatchSet(compilerOptions) && sys.watchFile) {
// Attach a file watcher
const filePath = toPath(sourceFile.fileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
sourceFile.fileWatcher = sys.watchFile(filePath, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
}
return sourceFile;
}
@@ -486,7 +500,7 @@ namespace ts {
}
function watchedDirectoryChanged(fileName: string) {
if (fileName && !ts.isSupportedSourceFileName(fileName, commandLine.options)) {
if (fileName && !ts.isSupportedSourceFileName(fileName, compilerOptions)) {
return;
}
@@ -590,30 +604,23 @@ namespace ts {
}
}
reportDiagnostics(diagnostics, compilerHost);
// If the user doesn't want us to emit, then we're done at this point.
if (compilerOptions.noEmit) {
return diagnostics.length
? ExitStatus.DiagnosticsPresent_OutputsSkipped
: ExitStatus.Success;
}
// Otherwise, emit and report any errors we ran into.
const emitOutput = program.emit();
reportDiagnostics(emitOutput.diagnostics, compilerHost);
diagnostics = diagnostics.concat(emitOutput.diagnostics);
// If the emitter didn't emit anything, then pass that value along.
if (emitOutput.emitSkipped) {
reportDiagnostics(sortAndDeduplicateDiagnostics(diagnostics), compilerHost);
reportEmittedFiles(emitOutput.emittedFiles, compilerHost);
if (emitOutput.emitSkipped && diagnostics.length > 0) {
// If the emitter didn't emit anything, then pass that value along.
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
// The emitter emitted something, inform the caller if that happened in the presence
// of diagnostics or not.
if (diagnostics.length > 0 || emitOutput.diagnostics.length > 0) {
else if (diagnostics.length > 0) {
// The emitter emitted something, inform the caller if that happened in the presence
// of diagnostics or not.
return ExitStatus.DiagnosticsPresent_OutputsGenerated;
}
return ExitStatus.Success;
}
}
@@ -656,6 +663,8 @@ namespace ts {
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap: Map<string[]> = {}; // 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];
@@ -676,7 +685,22 @@ namespace ts {
usageText += getParamType(option);
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(option.description));
let description: string;
if (option.name === "lib") {
description = getDiagnosticText(option.description);
const options: string[] = [];
const element = (<CommandLineOptionOfListType>option).element;
forEachKey(<Map<number | string>>element.type, key => {
options.push(`'${key}'`);
});
optionsDescriptionMap[description] = options;
}
else {
description = getDiagnosticText(option.description);
}
descriptionColumn.push(description);
// Set the new margin for the description column if necessary.
marginLength = Math.max(usageText.length, marginLength);
@@ -692,7 +716,16 @@ namespace ts {
for (let i = 0; i < usageColumn.length; i++) {
const usage = usageColumn[i];
const description = descriptionColumn[i];
const kindsList = optionsDescriptionMap[description];
output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine;
if (kindsList) {
output += makePadding(marginLength + 4);
for (const kind of kindsList) {
output += kind + " ";
}
output += sys.newLine;
}
}
sys.write(output);
@@ -719,14 +752,19 @@ namespace ts {
else {
const compilerOptions = extend(options, defaultInitCompilerOptions);
const configurations: any = {
compilerOptions: serializeCompilerOptions(compilerOptions),
exclude: ["node_modules"]
compilerOptions: serializeCompilerOptions(compilerOptions)
};
if (fileNames && fileNames.length) {
// only set the files property if we have at least one file
configurations.files = fileNames;
}
else {
configurations.exclude = ["node_modules"];
if (compilerOptions.outDir) {
configurations.exclude.push(compilerOptions.outDir);
}
}
sys.writeFile(file, JSON.stringify(configurations, undefined, 4));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* compilerHost */ undefined);
@@ -777,7 +815,7 @@ namespace ts {
}
}
if (ts.sys.developmentMode && ts.sys.tryEnableSourceMapsForHost) {
if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) {
ts.sys.tryEnableSourceMapsForHost();
}
+1 -2
View File
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
@@ -8,9 +7,9 @@
"sourceMap": true
},
"files": [
"types.ts",
"core.ts",
"sys.ts",
"types.ts",
"diagnosticInformationMap.generated.ts",
"scanner.ts",
"parser.ts",
+322 -117
View File
@@ -1,3 +1,4 @@
namespace ts {
export interface Map<T> {
[index: string]: T;
@@ -20,7 +21,6 @@ namespace ts {
export interface TextRange {
pos: number;
end: number;
/* @internal */ disableSourceMap?: boolean; // Whether a synthesized text range disables source maps for its contents (used by transforms).
}
// token > SyntaxKind.Identifer => token is a keyword
@@ -171,6 +171,7 @@ namespace ts {
StringKeyword,
SymbolKeyword,
TypeKeyword,
UndefinedKeyword,
FromKeyword,
GlobalKeyword,
OfKeyword, // LastKeyword and LastToken
@@ -240,6 +241,7 @@ namespace ts {
OmittedExpression,
ExpressionWithTypeArguments,
AsExpression,
NonNullExpression,
// Misc
TemplateSpan,
@@ -274,6 +276,7 @@ namespace ts {
ModuleDeclaration,
ModuleBlock,
CaseBlock,
GlobalModuleExportDeclaration,
ImportEqualsDeclaration,
ImportDeclaration,
ImportClause,
@@ -342,7 +345,11 @@ namespace ts {
// Synthesized list
SyntaxList,
NodeArrayNode,
// Transformation nodes
NotEmittedStatement,
PartiallyEmittedExpression,
// Enum value count
Count,
// Markers
@@ -373,18 +380,9 @@ namespace ts {
export const enum NodeFlags {
None = 0,
Export = 1 << 0, // Declarations
Ambient = 1 << 1, // Declarations
Public = 1 << 2, // Property/Method
Private = 1 << 3, // Property/Method
Protected = 1 << 4, // Property/Method
Static = 1 << 5, // Property/Method
Readonly = 1 << 6, // Property/Method
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
Let = 1 << 10, // Variable declaration
Const = 1 << 11, // Variable declaration
Let = 1 << 0, // Variable declaration
Const = 1 << 1, // Variable declaration
NestedNamespace = 1 << 2, // Namespace declaration
Namespace = 1 << 12, // Namespace declaration
ExportContext = 1 << 13, // Export context (initialized by binding)
ContainsThis = 1 << 14, // Interface contains references to "this"
@@ -403,36 +401,50 @@ namespace ts {
JavaScriptFile = 1 << 27, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 28, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 29, // If we've computed data from children and cached it in this node
HasJsxSpreadAttribute = 1 << 30,
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async,
AccessibilityModifier = Public | Private | Protected,
BlockScoped = Let | Const,
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions,
// Parsing context flags
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext,
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile,
// Exclude these flags when parsing a Type
TypeExcludesFlags = YieldContext | AwaitContext,
}
export const enum ModifierFlags {
None = 0,
Export = 1 << 0, // Declarations
Ambient = 1 << 1, // Declarations
Public = 1 << 2, // Property/Method
Private = 1 << 3, // Property/Method
Protected = 1 << 4, // Property/Method
Static = 1 << 5, // Property/Method
Readonly = 1 << 6, // Property/Method
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
Const = 1 << 11, // Variable declaration
HasComputedFlags = 1 << 31, // Modifier flags have been computed
AccessibilityModifier = Public | Private | Protected,
NonPublicAccessibilityModifier = Private | Protected,
}
export const enum JsxFlags {
None = 0,
/** An element from a named property of the JSX.IntrinsicElements interface */
IntrinsicNamedElement = 1 << 0,
/** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 1 << 1,
/** An element backed by a class, class-like, or function value */
ValueElement = 1 << 2,
/** Element resolution failed */
UnknownElement = 1 << 4,
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement,
}
/* @internal */
export const enum RelationComparisonResult {
Succeeded = 1, // Should be truthy
@@ -443,10 +455,11 @@ namespace ts {
export interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
/* @internal */ modifierFlagsCache?: ModifierFlags;
/* @internal */ transformFlags?: TransformFlags;
/* @internal */ excludeTransformFlags?: TransformFlags;
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
modifiers?: ModifiersArray; // Array of modifiers
modifiers?: NodeArray<Modifier>; // Array of modifiers
/* @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.
@@ -456,35 +469,13 @@ namespace ts {
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
/* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
}
export const enum ArrayKind {
NodeArray = 1,
ModifiersArray = 2,
/* @internal */ emitOptions?: NodeEmitOptions; // Options used to control node emit (used by transforms, should never be set directly on a source tree node)
}
export interface NodeArray<T extends Node> extends Array<T>, TextRange {
arrayKind: ArrayKind;
hasTrailingComma?: boolean;
}
/**
* A NodeArrayNode is a transient node used during transformations to indicate that more than
* one node will substitute a single node in the source. When the source is a NodeArray (as
* part of a call to `visitNodes`), the nodes of a NodeArrayNode will be spread into the
* result array. When the source is a Node (as part of a call to `visitNode`), the NodeArrayNode
* must be converted into a compatible node via the `lift` callback.
*/
/* @internal */
// @kind(SyntaxKind.NodeArrayNode)
export interface NodeArrayNode<T extends Node> extends Node {
nodes: NodeArray<T>;
}
export interface ModifiersArray extends NodeArray<Modifier> {
flags: number;
}
// @kind(SyntaxKind.AbstractKeyword)
// @kind(SyntaxKind.AsyncKeyword)
// @kind(SyntaxKind.ConstKeyword)
@@ -497,6 +488,7 @@ namespace ts {
// @kind(SyntaxKind.StaticKeyword)
export interface Modifier extends Node { }
/*@internal*/
export const enum GeneratedIdentifierKind {
None, // Not automatically generated.
Auto, // Automatically generated identifier.
@@ -507,9 +499,14 @@ namespace ts {
// @kind(SyntaxKind.Identifier)
export interface Identifier extends PrimaryExpression {
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
}
// Transient identifier node (marked by id === -1)
export interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
// @kind(SyntaxKind.QualifiedName)
@@ -820,6 +817,8 @@ namespace ts {
// @kind(SyntaxKind.StringLiteral)
export interface StringLiteral extends LiteralExpression {
_stringLiteralBrand: any;
/* @internal */
textSourceNode?: Identifier | StringLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
}
// Note: 'brands' in our syntax nodes serve to give us a small amount of nominal typing.
@@ -837,6 +836,14 @@ namespace ts {
// @kind(SyntaxKind.OmittedExpression)
export interface OmittedExpression extends Expression { }
// Represents an expression that is elided as part of a transformation to emit comments on a
// not-emitted node. The 'expression' property of a NotEmittedExpression should be emitted.
// @internal
// @kind(SyntaxKind.NotEmittedExpression)
export interface PartiallyEmittedExpression extends LeftHandSideExpression {
expression: Expression;
}
export interface UnaryExpression extends Expression {
_unaryExpressionBrand: any;
}
@@ -1014,6 +1021,8 @@ namespace ts {
name: Identifier;
}
export type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
// @kind(SyntaxKind.ElementAccessExpression)
export interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
@@ -1058,6 +1067,11 @@ namespace ts {
export type AssertionExpression = TypeAssertion | AsExpression;
// @kind(SyntaxKind.NonNullExpression)
export interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
/// A JSX expression of the form <TagName attrs>...</TagName>
// @kind(SyntaxKind.JsxElement)
export interface JsxElement extends PrimaryExpression {
@@ -1089,7 +1103,7 @@ namespace ts {
export interface JsxAttribute extends Node {
name: Identifier;
/// JSX attribute initializers are optional; <X y /> is sugar for <X y={true} />
initializer?: Expression;
initializer?: StringLiteral | JsxExpression;
}
// @kind(SyntaxKind.JsxSpreadAttribute)
@@ -1118,6 +1132,13 @@ namespace ts {
_statementBrand: any;
}
// Represents a statement that is elided as part of a transformation to emit comments on a
// not-emitted node.
// @internal
// @kind(SyntaxKind.NotEmittedStatement)
export interface NotEmittedStatement extends Statement {
}
// @kind(SyntaxKind.EmptyStatement)
export interface EmptyStatement extends Statement { }
@@ -1260,6 +1281,8 @@ namespace ts {
block: Block;
}
export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
export interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@@ -1382,6 +1405,12 @@ namespace ts {
name: Identifier;
}
// @kind(SyntaxKind.GlobalModuleImport)
export interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
// @kind(SyntaxKind.ExportDeclaration)
export interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
@@ -1571,6 +1600,7 @@ namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
@@ -1589,11 +1619,14 @@ namespace ts {
hasNoDefaultLib: boolean;
languageVersion: ScriptTarget;
/* @internal */ scriptKind: ScriptKind;
// The first node that causes this file to be an external module
/* @internal */ externalModuleIndicator: Node;
// The first node that causes this file to be a CommonJS module
/* @internal */ commonJsModuleIndicator: Node;
// True if the file was a root file in a compilation or a /// reference targets
/* @internal */ wasReferenced?: boolean;
/* @internal */ identifiers: Map<string>;
/* @internal */ nodeCount: number;
@@ -1613,8 +1646,9 @@ namespace ts {
/* @internal */ classifiableNames?: Map<string>;
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
// It is used to resolve module names in the checker.
// Content of this fiels should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<ResolvedModule>;
/* @internal */ resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
}
@@ -1630,7 +1664,7 @@ namespace ts {
}
export interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
export class OperationCanceledException { }
@@ -1691,6 +1725,7 @@ namespace ts {
/* @internal */ getTypeCount(): number;
/* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection;
/* @internal */ getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
// For testing purposes only.
/* @internal */ structureIsReused?: boolean;
}
@@ -1739,7 +1774,9 @@ namespace ts {
export interface EmitResult {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[]; // Array of files the compiler wrote to disk
/* @internal */ sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
}
@@ -1749,6 +1786,7 @@ namespace ts {
getSourceFiles(): SourceFile[];
getSourceFile(fileName: string): SourceFile;
getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
}
export interface TypeChecker {
@@ -1766,6 +1804,7 @@ namespace ts {
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@@ -1807,8 +1846,9 @@ namespace ts {
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@@ -1872,22 +1912,24 @@ namespace ts {
Identifier
}
export interface TypePredicate {
export interface TypePredicateBase {
kind: TypePredicateKind;
type: Type;
}
// @kind (TypePredicateKind.This)
export interface ThisTypePredicate extends TypePredicate {
export interface ThisTypePredicate extends TypePredicateBase {
_thisTypePredicateBrand: any;
}
// @kind (TypePredicateKind.Identifier)
export interface IdentifierTypePredicate extends TypePredicate {
export interface IdentifierTypePredicate extends TypePredicateBase {
parameterName: string;
parameterIndex: number;
}
export type TypePredicate = IdentifierTypePredicate | ThisTypePredicate;
/* @internal */
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
@@ -1900,7 +1942,7 @@ namespace ts {
}
/* @internal */
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
export interface SymbolAccessibilityResult extends SymbolVisibilityResult {
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
@@ -1928,7 +1970,7 @@ namespace ts {
/* @internal */
export interface EmitResolver {
hasGlobalName(name: string): boolean;
getReferencedExportContainer(node: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration;
getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration;
getReferencedImportDeclaration(node: Identifier): Declaration;
getReferencedDeclarationWithCollidingName(node: Identifier): Declaration;
isDeclarationWithCollidingName(node: Declaration): boolean;
@@ -1942,16 +1984,19 @@ namespace ts {
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile;
getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[];
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
}
export const enum SymbolFlags {
@@ -2047,6 +2092,7 @@ namespace ts {
members?: SymbolTable; // Class, interface or literal instance members
exports?: SymbolTable; // Module exports
globalExports?: SymbolTable; // Conditional global UMD exports
/* @internal */ id?: number; // Unique id (used to look up SymbolLinks)
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
/* @internal */ parent?: Symbol; // Parent symbol
@@ -2067,9 +2113,11 @@ namespace ts {
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
isDeclaratonWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // true if module exports some value (not just types)
exportsSomeValue?: boolean; // True if module exports some value (not just types)
firstAssignmentChecked?: boolean; // True if first assignment node has been computed
firstAssignment?: Node; // First assignment node (undefined if no assignments)
}
/* @internal */
@@ -2095,9 +2143,9 @@ namespace ts {
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function
BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement
HasSeenSuperCall = 0x00080000, // Set during the binding when encounter 'super'
DecoratedClassWithSelfReference = 0x00100000, // Decorated class that contains a binding to itself inside of the class body.
SelfReferenceInDecoratedClass = 0x00200000, // Binding to a decorated class inside of the class's body.
DecoratedClassWithSelfReference = 0x00080000, // Decorated class that contains a binding to itself inside of the class body.
SelfReferenceInDecoratedClass = 0x00100000, // Binding to a decorated class inside of the class's body.
NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop
}
/* @internal */
@@ -2112,11 +2160,13 @@ namespace ts {
isVisible?: boolean; // Is this node visible
generatedName?: string; // Generated name for module, enum, or import declaration
generatedNames?: Map<string>; // Generated names table for source file
assignmentChecks?: Map<boolean>; // Cache of assignment checks
assignmentMap?: Map<boolean>; // Cached map of references assigned within this node
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
importOnRightSide?: Symbol; // for import declarations - import that appear on the right side
jsxFlags?: JsxFlags; // flags for knowning what kind of element/attributes we're dealing with
jsxFlags?: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
resolvedJsxType?: Type; // resolved element attributes type of a JSX openinglike element
hasSuperCall?: boolean; // recorded result when we try to find super-call. We only try to find one if this flag is undefined, indicating that we haven't made an attempt.
superCall?: ExpressionStatement; // Cached first super-call found in the constructor. Used in checking whether super is called before this-accessing
}
export const enum TypeFlags {
@@ -2144,7 +2194,7 @@ namespace ts {
/* @internal */
FreshObjectLiteral = 0x00100000, // Fresh object literal type
/* @internal */
ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type
ContainsUndefinedOrNull = 0x00200000, // Type is or contains undefined or null type
/* @internal */
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
/* @internal */
@@ -2152,8 +2202,9 @@ namespace ts {
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
PredicateType = 0x08000000, // Predicate types are also Boolean types, but should not be considered Intrinsics - there's no way to capture this with flags
/* @internal */
Nullable = Undefined | Null,
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
/* @internal */
@@ -2164,7 +2215,7 @@ namespace ts {
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral | PredicateType,
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
/* @internal */
PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
@@ -2185,11 +2236,6 @@ namespace ts {
intrinsicName: string; // Name of intrinsic type
}
// Predicate types (TypeFlags.Predicate)
export interface PredicateType extends Type {
predicate: ThisTypePredicate | IdentifierTypePredicate;
}
// String literal types (TypeFlags.StringLiteral)
export interface StringLiteralType extends Type {
text: string; // Text of string literal
@@ -2220,7 +2266,7 @@ namespace ts {
// Type references (TypeFlags.Reference). When a class or interface has type parameters or
// a "this" type, references to the class or interface are made using type references. The
// typeArguments property specififes the types to substitute for the type parameters of the
// typeArguments property specifies the types to substitute for the type parameters of the
// class or interface and optionally includes an extra element that specifies the type to
// substitute for "this" in the resulting instantiation. When no extra argument is present,
// the type reference itself is substituted for "this". The typeArguments property is undefined
@@ -2306,6 +2352,7 @@ namespace ts {
declaration: SignatureDeclaration; // Originating declaration
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: Symbol[]; // Parameters
thisType?: Type; // type of this-type
/* @internal */
resolvedReturnType: Type; // Resolved return type
/* @internal */
@@ -2324,6 +2371,8 @@ namespace ts {
erasedSignatureCache?: Signature; // Erased version of signature (deferred)
/* @internal */
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
/* @internal */
typePredicate?: TypePredicate;
}
export const enum IndexKind {
@@ -2340,6 +2389,7 @@ namespace ts {
/* @internal */
export interface TypeMapper {
(t: TypeParameter): Type;
mappedTypes?: Type[]; // Types mapped by this mapper
instantiations?: Type[]; // Cache of instantiations created using this type mapper.
context?: InferenceContext; // The inference context this mapper was created from.
// Only inference mappers have this set (in createInferenceMapper).
@@ -2422,10 +2472,13 @@ namespace ts {
export type PathSubstitutions = Map<string[]>;
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
export interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@@ -2435,6 +2488,7 @@ namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@@ -2444,6 +2498,7 @@ namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@@ -2473,18 +2528,47 @@ namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
/* @internal */ stripInternal?: boolean;
/* @internal */ experimentalTransforms?: boolean;
/* @internal */ useLegacyEmitter?: boolean;
// Skip checking lib.d.ts to help speed up tests.
/* @internal */ skipDefaultLibCheck?: boolean;
// Do not perform validation of output file name in transpile scenarios
/* @internal */ suppressOutputPathCheck?: boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
/* @internal */
// When options come from a config file, its path is recorded here
configFilePath?: string;
/* @internal */
// Path used to used to compute primary search locations
typesRoot?: string;
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
export interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
export interface DiscoverTypingsInfo {
fileNames: string[]; // The file names that belong to the same project.
projectRootPath: string; // The path to the project root directory
safeListPath: string; // The path used to retrieve the safe list
packageNameToTypingLocation: Map<string>; // The map of package names to their cached typing locations
typingOptions: TypingOptions; // Used to customize the typing inference process
compilerOptions: CompilerOptions; // Used as a source for typing inference
}
export enum ModuleKind {
@@ -2516,6 +2600,14 @@ namespace ts {
character: number;
}
export const enum ScriptKind {
Unknown = 0,
JS = 1,
JSX = 2,
TS = 3,
TSX = 4
}
export const enum ScriptTarget {
ES3 = 0,
ES5 = 1,
@@ -2537,6 +2629,7 @@ namespace ts {
export interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
@@ -2544,7 +2637,7 @@ namespace ts {
/* @internal */
export interface CommandLineOptionBase {
name: string;
type: "string" | "number" | "boolean" | "object" | Map<number>; // a value of a primitive type, or an object literal mapping named values to actual values
type: "string" | "number" | "boolean" | "object" | "list" | Map<number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
isFilePath?: boolean; // True if option value is a path or fileName
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does
@@ -2560,8 +2653,7 @@ namespace ts {
/* @internal */
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
type: Map<number>; // an object literal mapping named values to actual values
error: DiagnosticMessage; // The error given when the argument does not fit a customized 'type'
type: Map<number | string>; // an object literal mapping named values to actual values
}
/* @internal */
@@ -2570,7 +2662,13 @@ namespace ts {
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption;
export interface CommandLineOptionOfListType extends CommandLineOptionBase {
type: "list";
element: CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType;
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption | CommandLineOptionOfListType;
/* @internal */
export const enum CharacterCodes {
@@ -2734,10 +2832,23 @@ namespace ts {
failedLookupLocations: string[];
}
export interface ResolvedTypeReferenceDirective {
// True if the type declaration file was found in a primary lookup location
primary: boolean;
// The location of the .d.ts file we located, or undefined if resolution failed
resolvedFileName?: string;
}
export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
@@ -2747,15 +2858,23 @@ namespace ts {
/*
* CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
* module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
* will appply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
* will apply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
* If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
* 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getEnvironmentVariable?(name: string): string;
}
/* @internal */
export const enum TransformFlags {
None = 0,
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
TypeScript = 1 << 0,
@@ -2775,12 +2894,16 @@ namespace ts {
ContainsPropertyInitializer = 1 << 11,
ContainsLexicalThis = 1 << 12,
ContainsCapturedLexicalThis = 1 << 13,
ContainsDefaultValueAssignments = 1 << 14,
ContainsParameterPropertyAssignments = 1 << 15,
ContainsSpreadElementExpression = 1 << 16,
ContainsComputedPropertyName = 1 << 17,
ContainsBlockScopedBinding = 1 << 18,
ContainsYield = 1 << 19,
ContainsLexicalThisInComputedPropertyName = 1 << 14,
ContainsDefaultValueAssignments = 1 << 15,
ContainsParameterPropertyAssignments = 1 << 16,
ContainsSpreadElementExpression = 1 << 17,
ContainsComputedPropertyName = 1 << 18,
ContainsBlockScopedBinding = 1 << 19,
ContainsBindingPattern = 1 << 20,
ContainsYield = 1 << 21,
HasComputedFlags = 1 << 31, // Transform flags have been computed.
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
@@ -2792,16 +2915,18 @@ namespace ts {
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
NodeExcludes = TypeScript | Jsx | ES7 | ES6 | DestructuringAssignment,
NodeExcludes = TypeScript | Jsx | ES7 | ES6 | DestructuringAssignment | HasComputedFlags,
ArrowFunctionExcludes = ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield,
FunctionExcludes = ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield,
ConstructorExcludes = ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield,
MethodOrAccessorExcludes = ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield,
ClassExcludes = ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments,
ClassExcludes = ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName,
ModuleExcludes = ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding,
TypeExcludes = ~ContainsTypeScript,
ObjectLiteralExcludes = ContainsDecorators | ContainsComputedPropertyName,
ObjectLiteralExcludes = ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
ArrayLiteralOrCallOrNewExcludes = ContainsSpreadElementExpression,
VariableDeclarationListExcludes = ContainsBindingPattern,
ParameterExcludes = ContainsBindingPattern,
}
/* @internal */
@@ -2812,14 +2937,55 @@ namespace ts {
EmitAdvancedSuperHelper = 1 << 3, // Emit the advanced _super helper for async methods.
UMDDefine = 1 << 4, // This node should be replaced with the UMD define helper.
NoLexicalEnvironment = 1 << 5, // A new LexicalEnvironment should *not* be introduced when emitting this node, this is primarily used when printing a SystemJS module.
SingleLine = 1 << 6, // The contents of this node should be emit on a single line.
AdviseOnEmitNode = 1 << 7, // The node printer should invoke the onBeforeEmitNode and onAfterEmitNode callbacks when printing this node.
IsNotEmittedNode = 1 << 8, // Is a node that is not emitted but whose comments should be preserved if possible.
EmitCommentsOfNotEmittedParent = 1 << 9, // Emits comments of missing parent nodes.
NoSubstitution = 1 << 10, // Disables further substitution of an expression.
SingleLine = 1 << 6, // The contents of this node should be emitted on a single line.
AdviseOnEmitNode = 1 << 7, // The printer should invoke the onEmitNode callback when printing this node.
NoSubstitution = 1 << 8, // Disables further substitution of an expression.
CapturesThis = 1 << 9, // The function captures a lexical `this`
NoLeadingSourceMap = 1 << 10, // Do not emit a leading source map location for this node.
NoTrailingSourceMap = 1 << 11, // Do not emit a trailing source map location for this node.
NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node.
NoNestedSourceMaps = 1 << 12, // Do not emit source map locations for children of this node.
NoTokenLeadingSourceMaps = 1 << 13, // Do not emit leading source map location for token nodes.
NoTokenTrailingSourceMaps = 1 << 14, // Do not emit trailing source map location for token nodes.
NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node.
NoLeadingComments = 1 << 15, // Do not emit leading comments for this node.
NoTrailingComments = 1 << 16, // Do not emit trailing comments for this node.
NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node.
ExportName = 1 << 17, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
LocalName = 1 << 18, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
Indented = 1 << 19, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
Merge = 1 << 20, // When getting emit options, merge with existing emit options.
// SourceMap Specialization.
// TODO(rbuckton): These should be removed once source maps are aligned with the old
// emitter and new baselines are taken. This exists solely to
// align with the old emitter.
SourceMapEmitOpenBraceAsToken = 1 << 21, // Emits the open brace of a block function body as a source mapped token.
SourceMapAdjustRestParameterLoop = 1 << 22, // Emits adjusted source map positions for a ForStatement generated when transforming a rest parameter for ES5/3.
}
/* @internal */
export interface NodeEmitOptions {
/**
* Specifies a custom range to use when emitting source maps.
*/
sourceMapRange?: TextRange;
/**
* Specifies a custom range to use when emitting tokens of a node.
*/
tokenSourceMapRange?: Map<TextRange>;
/**
* Specifies a custom range to use when emitting comments.
*/
commentRange?: TextRange;
/**
* Specifies flags to use to customize emit.
*/
flags?: NodeEmitFlags;
}
/** Additional context provided to `visitEachChild` */
/* @internal */
export interface LexicalEnvironment {
/** Starts a new lexical environment. */
startLexicalEnvironment(): void;
@@ -2832,44 +2998,83 @@ namespace ts {
export interface TransformationContext extends LexicalEnvironment {
getCompilerOptions(): CompilerOptions;
getEmitResolver(): EmitResolver;
getEmitHost(): EmitHost;
/**
* Gets flags used to customize later transformations or emit.
*/
getNodeEmitFlags(node: Node): NodeEmitFlags;
/**
* Sets flags used to customize later transformations or emit.
*/
setNodeEmitFlags<T extends Node>(node: T, flags: NodeEmitFlags): T;
/**
* Gets the TextRange to use for source maps for the node.
*/
getSourceMapRange(node: Node): TextRange;
/**
* Sets the TextRange to use for source maps for the node.
*/
setSourceMapRange<T extends Node>(node: T, range: TextRange): T;
/**
* Gets the TextRange to use for source maps for a token of a node.
*/
getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange;
/**
* Sets the TextRange to use for source maps for a token of a node.
*/
setTokenSourceMapRange<T extends Node>(node: T, token: SyntaxKind, range: TextRange): T;
/**
* Gets the TextRange to use for comments for the node.
*/
getCommentRange(node: Node): TextRange;
/**
* Sets the TextRange to use for comments for the node.
*/
setCommentRange<T extends Node>(node: T, range: TextRange): T;
/**
* Hoists a function declaration to the containing scope.
*/
hoistFunctionDeclaration(node: FunctionDeclaration): void;
/**
* Hoists a variable declaration to the containing scope.
*/
hoistVariableDeclaration(node: Identifier): void;
/**
* Hook used by transformers to substitute non-expression identifiers
* just before theyare emitted by the pretty printer.
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
identifierSubstitution?: (node: Identifier) => Identifier;
enableSubstitution(kind: SyntaxKind): void;
/**
* Enables expression substitutions in the pretty printer for
* the provided SyntaxKind.
* Determines whether expression substitutions are enabled for the provided node.
*/
enableExpressionSubstitution(kind: SyntaxKind): void;
/**
* Determines whether expression substitutions are enabled for the
* provided node.
*/
isExpressionSubstitutionEnabled(node: Node): boolean;
isSubstitutionEnabled(node: Node): boolean;
/**
* Hook used by transformers to substitute expressions just before they
* are emitted by the pretty printer.
*/
expressionSubstitution?: (node: Expression) => Expression;
onSubstituteNode?: (node: Node, isExpression: boolean) => Node;
/**
* Enables before/after emit notifications in the pretty printer for
* the provided SyntaxKind.
* Enables before/after emit notifications in the pretty printer for the provided
* SyntaxKind.
*/
enableEmitNotification(kind: SyntaxKind): void;
/**
* Determines whether before/after emit notifications should be raised
* in the pretty printer when it emits a node.
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
isEmitNotificationEnabled(node: Node): boolean;
@@ -2902,7 +3107,7 @@ namespace ts {
getGlobalDiagnostics(): Diagnostic[];
// If fileName is provided, gets all the diagnostics associated with that file name.
// Otherwise, returns all the diagnostics (global and file associated) in this colletion.
// Otherwise, returns all the diagnostics (global and file associated) in this collection.
getDiagnostics(fileName?: string): Diagnostic[];
// Gets a count of how many times this collection has been modified. This value changes
+547 -145
View File
File diff suppressed because it is too large Load Diff
+215 -197
View File
@@ -3,7 +3,7 @@
/* @internal */
namespace ts {
export type OneOrMany<T extends Node> = T | NodeArrayNode<T>;
export type VisitResult<T extends Node> = T | T[];
/**
* Describes an edge of a Node, used when traversing a syntax tree.
@@ -46,27 +46,27 @@ namespace ts {
const nodeEdgeTraversalMap: Map<NodeTraversalPath> = {
[SyntaxKind.QualifiedName]: [
{ name: "left", test: isEntityName },
{ name: "right", test: isIdentifier },
{ name: "right", test: isIdentifier }
],
[SyntaxKind.ComputedPropertyName]: [
{ name: "expression", test: isExpression },
{ name: "expression", test: isExpression }
],
[SyntaxKind.Parameter]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isBindingName },
{ name: "type", test: isTypeNode, optional: true },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.Decorator]: [
{ name: "expression", test: isLeftHandSideExpression },
{ name: "expression", test: isLeftHandSideExpression }
],
[SyntaxKind.PropertyDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isPropertyName },
{ name: "type", test: isTypeNode, optional: true },
{ name: "initializer", test: isExpression, optional: true },
{ name: "initializer", test: isExpression, optional: true }
],
[SyntaxKind.MethodDeclaration]: [
{ name: "decorators", test: isDecorator },
@@ -75,7 +75,7 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.Constructor]: [
{ name: "decorators", test: isDecorator },
@@ -83,7 +83,7 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.GetAccessor]: [
{ name: "decorators", test: isDecorator },
@@ -92,7 +92,7 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.SetAccessor]: [
{ name: "decorators", test: isDecorator },
@@ -101,53 +101,53 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.ObjectBindingPattern]: [
{ name: "elements", test: isBindingElement },
{ name: "elements", test: isBindingElement }
],
[SyntaxKind.ArrayBindingPattern]: [
{ name: "elements", test: isBindingElement },
{ name: "elements", test: isBindingElement }
],
[SyntaxKind.BindingElement]: [
{ name: "propertyName", test: isPropertyName, optional: true },
{ name: "name", test: isBindingName },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ArrayLiteralExpression]: [
{ name: "elements", test: isExpression, parenthesize: parenthesizeExpressionForList },
{ name: "elements", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ObjectLiteralExpression]: [
{ name: "properties", test: isObjectLiteralElement },
{ name: "properties", test: isObjectLiteralElement }
],
[SyntaxKind.PropertyAccessExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "name", test: isIdentifier },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.ElementAccessExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "argumentExpression", test: isExpression },
{ name: "argumentExpression", test: isExpression }
],
[SyntaxKind.CallExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "typeArguments", test: isTypeNode },
{ name: "arguments", test: isExpression },
{ name: "arguments", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.NewExpression]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForNew },
{ name: "typeArguments", test: isTypeNode },
{ name: "arguments", test: isExpression },
{ name: "arguments", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.TaggedTemplateExpression]: [
{ name: "tag", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "template", test: isTemplate },
{ name: "template", test: isTemplate }
],
[SyntaxKind.TypeAssertionExpression]: [
{ name: "type", test: isTypeNode },
{ name: "expression", test: isUnaryExpression },
{ name: "expression", test: isUnaryExpression }
],
[SyntaxKind.ParenthesizedExpression]: [
{ name: "expression", test: isExpression },
{ name: "expression", test: isExpression }
],
[SyntaxKind.FunctionExpression]: [
{ name: "decorators", test: isDecorator },
@@ -156,7 +156,7 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.ArrowFunction]: [
{ name: "decorators", test: isDecorator },
@@ -164,44 +164,44 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isConciseBody, lift: liftToBlock, parenthesize: parenthesizeConciseBody },
{ name: "body", test: isConciseBody, lift: liftToBlock, parenthesize: parenthesizeConciseBody }
],
[SyntaxKind.DeleteExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand },
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.TypeOfExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand },
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.VoidExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand },
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.AwaitExpression]: [
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand },
{ name: "expression", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.PrefixUnaryExpression]: [
{ name: "operand", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand },
{ name: "operand", test: isUnaryExpression, parenthesize: parenthesizePrefixOperand }
],
[SyntaxKind.PostfixUnaryExpression]: [
{ name: "operand", test: isLeftHandSideExpression, parenthesize: parenthesizePostfixOperand },
{ name: "operand", test: isLeftHandSideExpression, parenthesize: parenthesizePostfixOperand }
],
[SyntaxKind.BinaryExpression]: [
{ name: "left", test: isExpression, parenthesize: (node: Expression, parent: BinaryExpression) => parenthesizeBinaryOperand(getOperator(parent), node, true) },
{ name: "right", test: isExpression, parenthesize: (node: Expression, parent: BinaryExpression) => parenthesizeBinaryOperand(getOperator(parent), node, false) },
{ name: "left", test: isExpression, parenthesize: (node: Expression, parent: BinaryExpression) => parenthesizeBinaryOperand(getOperator(parent), node, true, /*leftOperand*/ undefined) },
{ name: "right", test: isExpression, parenthesize: (node: Expression, parent: BinaryExpression) => parenthesizeBinaryOperand(getOperator(parent), node, false, parent.left) }
],
[SyntaxKind.ConditionalExpression]: [
{ name: "condition", test: isExpression },
{ name: "whenTrue", test: isExpression },
{ name: "whenFalse", test: isExpression },
{ name: "whenFalse", test: isExpression }
],
[SyntaxKind.TemplateExpression]: [
{ name: "head", test: isTemplateLiteralFragment },
{ name: "templateSpans", test: isTemplateSpan },
{ name: "templateSpans", test: isTemplateSpan }
],
[SyntaxKind.YieldExpression]: [
{ name: "expression", test: isExpression, optional: true },
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.SpreadElementExpression]: [
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForList },
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ClassExpression]: [
{ name: "decorators", test: isDecorator },
@@ -209,96 +209,99 @@ namespace ts {
{ name: "name", test: isIdentifier, optional: true },
{ name: "typeParameters", test: isTypeParameter },
{ name: "heritageClauses", test: isHeritageClause },
{ name: "members", test: isClassElement },
{ name: "members", test: isClassElement }
],
[SyntaxKind.ExpressionWithTypeArguments]: [
{ name: "expression", test: isLeftHandSideExpression, parenthesize: parenthesizeForAccess },
{ name: "typeArguments", test: isTypeNode },
{ name: "typeArguments", test: isTypeNode }
],
[SyntaxKind.AsExpression]: [
{ name: "expression", test: isExpression },
{ name: "type", test: isTypeNode },
{ name: "type", test: isTypeNode }
],
[SyntaxKind.NonNullExpression]: [
{ name: "expression", test: isLeftHandSideExpression }
],
[SyntaxKind.TemplateSpan]: [
{ name: "expression", test: isExpression },
{ name: "literal", test: isTemplateLiteralFragment },
{ name: "literal", test: isTemplateLiteralFragment }
],
[SyntaxKind.Block]: [
{ name: "statements", test: isStatement },
{ name: "statements", test: isStatement }
],
[SyntaxKind.VariableStatement]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "declarationList", test: isVariableDeclarationList },
{ name: "declarationList", test: isVariableDeclarationList }
],
[SyntaxKind.ExpressionStatement]: [
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForExpressionStatement },
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForExpressionStatement }
],
[SyntaxKind.IfStatement]: [
{ name: "expression", test: isExpression },
{ name: "thenStatement", test: isStatement, lift: liftToBlock },
{ name: "elseStatement", test: isStatement, lift: liftToBlock, optional: true },
{ name: "elseStatement", test: isStatement, lift: liftToBlock, optional: true }
],
[SyntaxKind.DoStatement]: [
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "expression", test: isExpression },
{ name: "expression", test: isExpression }
],
[SyntaxKind.WhileStatement]: [
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ForStatement]: [
{ name: "initializer", test: isForInitializer, optional: true },
{ name: "condition", test: isExpression, optional: true },
{ name: "incrementor", test: isExpression, optional: true },
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ForInStatement]: [
{ name: "initializer", test: isForInitializer },
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ForOfStatement]: [
{ name: "initializer", test: isForInitializer },
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ContinueStatement]: [
{ name: "label", test: isIdentifier, optional: true },
{ name: "label", test: isIdentifier, optional: true }
],
[SyntaxKind.BreakStatement]: [
{ name: "label", test: isIdentifier, optional: true },
{ name: "label", test: isIdentifier, optional: true }
],
[SyntaxKind.ReturnStatement]: [
{ name: "expression", test: isExpression, optional: true },
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.WithStatement]: [
{ name: "expression", test: isExpression },
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.SwitchStatement]: [
{ name: "expression", test: isExpression },
{ name: "caseBlock", test: isCaseBlock },
{ name: "caseBlock", test: isCaseBlock }
],
[SyntaxKind.LabeledStatement]: [
{ name: "label", test: isIdentifier },
{ name: "statement", test: isStatement, lift: liftToBlock },
{ name: "statement", test: isStatement, lift: liftToBlock }
],
[SyntaxKind.ThrowStatement]: [
{ name: "expression", test: isExpression },
{ name: "expression", test: isExpression }
],
[SyntaxKind.TryStatement]: [
{ name: "tryBlock", test: isBlock },
{ name: "catchClause", test: isCatchClause, optional: true },
{ name: "finallyBlock", test: isBlock, optional: true },
{ name: "finallyBlock", test: isBlock, optional: true }
],
[SyntaxKind.VariableDeclaration]: [
{ name: "name", test: isBindingName },
{ name: "type", test: isTypeNode, optional: true },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.VariableDeclarationList]: [
{ name: "declarations", test: isVariableDeclaration },
{ name: "declarations", test: isVariableDeclaration }
],
[SyntaxKind.FunctionDeclaration]: [
{ name: "decorators", test: isDecorator },
@@ -307,7 +310,7 @@ namespace ts {
{ name: "typeParameters", test: isTypeParameter },
{ name: "parameters", test: isParameter },
{ name: "type", test: isTypeNode, optional: true },
{ name: "body", test: isBlock, optional: true },
{ name: "body", test: isBlock, optional: true }
],
[SyntaxKind.ClassDeclaration]: [
{ name: "decorators", test: isDecorator },
@@ -315,128 +318,132 @@ namespace ts {
{ name: "name", test: isIdentifier, optional: true },
{ name: "typeParameters", test: isTypeParameter },
{ name: "heritageClauses", test: isHeritageClause },
{ name: "members", test: isClassElement },
{ name: "members", test: isClassElement }
],
[SyntaxKind.EnumDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier },
{ name: "members", test: isEnumMember },
{ name: "members", test: isEnumMember }
],
[SyntaxKind.ModuleDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isModuleName },
{ name: "body", test: isModuleBody },
{ name: "body", test: isModuleBody }
],
[SyntaxKind.ModuleBlock]: [
{ name: "statements", test: isStatement },
{ name: "statements", test: isStatement }
],
[SyntaxKind.CaseBlock]: [
{ name: "clauses", test: isCaseOrDefaultClause },
{ name: "clauses", test: isCaseOrDefaultClause }
],
[SyntaxKind.ImportEqualsDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "name", test: isIdentifier },
{ name: "moduleReference", test: isModuleReference },
{ name: "moduleReference", test: isModuleReference }
],
[SyntaxKind.ImportDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "importClause", test: isImportClause, optional: true },
{ name: "moduleSpecifier", test: isExpression },
{ name: "moduleSpecifier", test: isExpression }
],
[SyntaxKind.ImportClause]: [
{ name: "name", test: isIdentifier, optional: true },
{ name: "namedBindings", test: isNamedImportBindings, optional: true },
{ name: "namedBindings", test: isNamedImportBindings, optional: true }
],
[SyntaxKind.NamespaceImport]: [
{ name: "name", test: isIdentifier },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.NamedImports]: [
{ name: "elements", test: isImportSpecifier },
{ name: "elements", test: isImportSpecifier }
],
[SyntaxKind.ImportSpecifier]: [
{ name: "propertyName", test: isIdentifier, optional: true },
{ name: "name", test: isIdentifier },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.ExportAssignment]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "expression", test: isExpression },
{ name: "expression", test: isExpression }
],
[SyntaxKind.ExportDeclaration]: [
{ name: "decorators", test: isDecorator },
{ name: "modifiers", test: isModifier },
{ name: "exportClause", test: isNamedExports, optional: true },
{ name: "moduleSpecifier", test: isExpression, optional: true },
{ name: "moduleSpecifier", test: isExpression, optional: true }
],
[SyntaxKind.NamedExports]: [
{ name: "elements", test: isExportSpecifier },
{ name: "elements", test: isExportSpecifier }
],
[SyntaxKind.ExportSpecifier]: [
{ name: "propertyName", test: isIdentifier, optional: true },
{ name: "name", test: isIdentifier },
{ name: "name", test: isIdentifier }
],
[SyntaxKind.ExternalModuleReference]: [
{ name: "expression", test: isExpression, optional: true },
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.JsxElement]: [
{ name: "openingElement", test: isJsxOpeningElement },
{ name: "children", test: isJsxChild },
{ name: "closingElement", test: isJsxClosingElement },
{ name: "closingElement", test: isJsxClosingElement }
],
[SyntaxKind.JsxSelfClosingElement]: [
{ name: "tagName", test: isEntityName },
{ name: "attributes", test: isJsxAttributeLike },
{ name: "attributes", test: isJsxAttributeLike }
],
[SyntaxKind.JsxOpeningElement]: [
{ name: "tagName", test: isEntityName },
{ name: "attributes", test: isJsxAttributeLike },
{ name: "attributes", test: isJsxAttributeLike }
],
[SyntaxKind.JsxClosingElement]: [
{ name: "tagName", test: isEntityName },
{ name: "tagName", test: isEntityName }
],
[SyntaxKind.JsxAttribute]: [
{ name: "name", test: isIdentifier },
{ name: "initializer", test: isExpression, optional: true },
{ name: "initializer", test: isStringLiteralOrJsxExpression, optional: true }
],
[SyntaxKind.JsxSpreadAttribute]: [
{ name: "expression", test: isExpression },
{ name: "expression", test: isExpression }
],
[SyntaxKind.JsxExpression]: [
{ name: "expression", test: isExpression, optional: true },
{ name: "expression", test: isExpression, optional: true }
],
[SyntaxKind.CaseClause]: [
{ name: "expression", test: isExpression, parenthesize: parenthesizeExpressionForList },
{ name: "statements", test: isStatement },
{ name: "statements", test: isStatement }
],
[SyntaxKind.DefaultClause]: [
{ name: "statements", test: isStatement },
{ name: "statements", test: isStatement }
],
[SyntaxKind.HeritageClause]: [
{ name: "types", test: isExpressionWithTypeArguments },
{ name: "types", test: isExpressionWithTypeArguments }
],
[SyntaxKind.CatchClause]: [
{ name: "variableDeclaration", test: isVariableDeclaration },
{ name: "block", test: isBlock },
{ name: "block", test: isBlock }
],
[SyntaxKind.PropertyAssignment]: [
{ name: "name", test: isPropertyName },
{ name: "initializer", test: isExpression, parenthesize: parenthesizeExpressionForList },
{ name: "initializer", test: isExpression, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.ShorthandPropertyAssignment]: [
{ name: "name", test: isIdentifier },
{ name: "objectAssignmentInitializer", test: isExpression, optional: true },
{ name: "objectAssignmentInitializer", test: isExpression, optional: true }
],
[SyntaxKind.EnumMember]: [
{ name: "name", test: isPropertyName },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList },
{ name: "initializer", test: isExpression, optional: true, parenthesize: parenthesizeExpressionForList }
],
[SyntaxKind.SourceFile]: [
{ name: "statements", test: isStatement },
{ name: "statements", test: isStatement }
],
[SyntaxKind.NotEmittedStatement]: [],
[SyntaxKind.PartiallyEmittedExpression]: [
{ name: "expression", test: isExpression }
]
};
/**
@@ -448,7 +455,7 @@ namespace ts {
* @param f The callback function
* @param initial The initial value to supply to the reduction.
*/
export function reduceEachChild<T>(node: Node, f: (memo: T, node: Node) => T, initial: T) {
export function reduceEachChild<T>(node: Node, f: (memo: T, node: Node) => T, initial: T): T {
if (node === undefined) {
return undefined;
}
@@ -478,7 +485,7 @@ namespace ts {
* @param optional An optional value indicating whether the Node is itself optional.
* @param lift An optional callback to execute to lift a NodeArrayNode into a valid Node.
*/
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => Node, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray<Node>) => T): T {
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray<Node>) => T): T {
return <T>visitNodeWorker(node, visitor, test, optional, lift, /*parenthesize*/ undefined, /*parentNode*/ undefined);
}
@@ -493,32 +500,38 @@ namespace ts {
* @param parenthesize A callback used to parenthesize the node if needed.
* @param parentNode A parentNode for the node.
*/
function visitNodeWorker(node: Node, visitor: (node: Node) => Node, test: (node: Node) => boolean, optional: boolean, lift: (node: NodeArray<Node>) => Node, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): Node {
function visitNodeWorker(node: Node, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional: boolean, lift: (node: Node[]) => Node, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): Node {
if (node === undefined) {
return undefined;
}
let visited = visitor(node);
const visited = visitor(node);
if (visited === node) {
return node;
}
if (visited !== undefined && isNodeArrayNode(visited)) {
visited = (lift || extractSingleNode)((<NodeArrayNode<Node>>visited).nodes);
}
if (parenthesize !== undefined && visited !== undefined) {
visited = parenthesize(visited, parentNode);
}
let visitedNode: Node;
if (visited === undefined) {
Debug.assert(optional, "Node not optional.");
if (!optional) {
Debug.failNotOptional();
}
return undefined;
}
else if (isArray(visited)) {
visitedNode = (lift || extractSingleNode)(visited);
}
else {
visitedNode = visited;
}
Debug.assert(test === undefined || test(visited), "Wrong node type after visit.");
aggregateTransformFlags(visited);
return visited;
if (parenthesize !== undefined) {
visitedNode = parenthesize(visitedNode, parentNode);
}
Debug.assertNode(visitedNode, test);
aggregateTransformFlags(visitedNode);
return visitedNode;
}
/**
@@ -530,7 +543,7 @@ namespace ts {
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
export function visitNodes<T extends Node, TArray extends NodeArray<T>>(nodes: TArray, visitor: (node: Node) => Node, test: (node: Node) => boolean, start?: number, count?: number): TArray {
export function visitNodes<T extends Node, TArray extends NodeArray<T>>(nodes: TArray, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, start?: number, count?: number): TArray {
return <TArray>visitNodesWorker(nodes, visitor, test, /*parenthesize*/ undefined, /*parentNode*/ undefined, start, count);
}
@@ -543,12 +556,12 @@ namespace ts {
* @param start An optional value indicating the starting offset at which to start visiting.
* @param count An optional value indicating the maximum number of nodes to visit.
*/
function visitNodesWorker(nodes: NodeArray<Node>, visitor: (node: Node) => Node, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, start: number, count: number): NodeArray<Node> {
function visitNodesWorker(nodes: NodeArray<Node>, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, start: number, count: number): NodeArray<Node> {
if (nodes === undefined) {
return undefined;
}
let updated: Node[];
let updated: NodeArray<Node>;
// Ensure start and count have valid values
const length = nodes.length;
@@ -560,9 +573,12 @@ namespace ts {
count = length - start;
}
// If we are not visiting all of the original nodes, we must always create a new array.
if (start > 0 || count < length) {
updated = [];
// If we are not visiting all of the original nodes, we must always create a new array.
// Since this is a fragment of a node array, we do not copy over the previous location
// and will only copy over `hasTrailingComma` if we are including the last element.
updated = createNodeArray<Node>([], /*location*/ undefined,
/*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
}
// Visit each original node.
@@ -572,20 +588,14 @@ namespace ts {
if (updated !== undefined || visited === undefined || visited !== node) {
if (updated === undefined) {
// Ensure we have a copy of `nodes`, up to the current index.
updated = nodes.slice(0, i);
updated = createNodeArray(nodes.slice(0, i), /*location*/ nodes, nodes.hasTrailingComma);
}
addNodeWorker(updated, visited, /*addOnNewLine*/ undefined, test, parenthesize, parentNode, /*isVisiting*/ visited !== node);
}
}
if (updated !== undefined) {
return isModifiersArray(nodes)
? createModifiersArray(updated, nodes)
: createNodeArray(updated, nodes, nodes.hasTrailingComma);
}
return nodes;
return updated || nodes;
}
/**
@@ -595,8 +605,8 @@ namespace ts {
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
export function visitEachChild<T extends Node>(node: T, visitor: (node: Node) => Node, context: LexicalEnvironment): T;
export function visitEachChild<T extends Node>(node: T & Map<any>, visitor: (node: Node) => Node, context: LexicalEnvironment): T {
export function visitEachChild<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, context: LexicalEnvironment): T;
export function visitEachChild<T extends Node>(node: T & Map<any>, visitor: (node: Node) => VisitResult<Node>, context: LexicalEnvironment): T {
if (node === undefined) {
return undefined;
}
@@ -611,17 +621,12 @@ namespace ts {
const edgeTraversalPath = nodeEdgeTraversalMap[node.kind];
if (edgeTraversalPath) {
let modifiers: NodeFlags;
for (const edge of edgeTraversalPath) {
const value = <Node | NodeArray<Node>>node[edge.name];
if (value !== undefined) {
let visited: Node | NodeArray<Node>;
if (isArray(value)) {
const visitedArray = visitNodesWorker(value, visitor, edge.test, edge.parenthesize, node, 0, value.length);
if (isModifiersArray(visitedArray)) {
modifiers = visitedArray.flags;
}
visited = visitedArray;
}
else {
@@ -631,12 +636,6 @@ namespace ts {
if (updated !== undefined || visited !== value) {
if (updated === undefined) {
updated = getMutableClone(node);
updated.flags &= ~NodeFlags.Modifier;
}
if (modifiers) {
updated.flags |= modifiers;
modifiers = undefined;
}
if (visited !== value) {
@@ -666,33 +665,13 @@ namespace ts {
return updated;
}
/**
* Flattens an array of nodes that could contain NodeArrayNodes.
*/
export function flattenNodes<T extends Node>(nodes: OneOrMany<T>[]): T[] {
let result: T[];
if (nodes) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (result || node === undefined || isNodeArrayNode(node)) {
if (!result) {
result = <T[]>nodes.slice(0, i);
}
addNode(result, node);
}
}
}
return result || <T[]>nodes;
}
/**
* Appends a node to an array.
*
* @param to The destination array.
* @param from The source Node or NodeArrayNode.
*/
export function addNode<T extends Node>(to: T[], from: OneOrMany<T>, startOnNewLine?: boolean) {
export function addNode<T extends Node>(to: T[], from: VisitResult<T>, startOnNewLine?: boolean): void {
addNodeWorker(to, from, startOnNewLine, /*test*/ undefined, /*parenthesize*/ undefined, /*parentNode*/ undefined, /*isVisiting*/ false);
}
@@ -702,36 +681,36 @@ namespace ts {
* @param to The destination NodeArray.
* @param from The source array of Node or NodeArrayNode.
*/
export function addNodes<T extends Node>(to: T[], from: OneOrMany<T>[], startOnNewLine?: boolean) {
export function addNodes<T extends Node>(to: T[], from: VisitResult<T>[], startOnNewLine?: boolean): void {
addNodesWorker(to, from, startOnNewLine, /*test*/ undefined, /*parenthesize*/ undefined, /*parentNode*/ undefined, /*isVisiting*/ false);
}
function addNodeWorker(to: Node[], from: OneOrMany<Node>, startOnNewLine: boolean, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, isVisiting: boolean) {
function addNodeWorker(to: Node[], from: VisitResult<Node>, startOnNewLine: boolean, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, isVisiting: boolean): void {
if (to && from) {
if (isNodeArrayNode(from)) {
addNodesWorker(to, from.nodes, startOnNewLine, test, parenthesize, parentNode, isVisiting);
return;
if (isArray(from)) {
addNodesWorker(to, from, startOnNewLine, test, parenthesize, parentNode, isVisiting);
}
else {
const node = parenthesize !== undefined
? parenthesize(from, parentNode)
: from;
if (parenthesize !== undefined) {
from = parenthesize(from, parentNode);
Debug.assertNode(node, test);
if (startOnNewLine) {
node.startsOnNewLine = true;
}
if (isVisiting) {
aggregateTransformFlags(node);
}
to.push(node);
}
Debug.assert(test === undefined || test(from), "Wrong node type after visit.");
if (startOnNewLine) {
from.startsOnNewLine = true;
}
if (isVisiting) {
aggregateTransformFlags(from);
}
to.push(from);
}
}
function addNodesWorker(to: Node[], from: OneOrMany<Node>[], startOnNewLine: boolean, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, isVisiting: boolean) {
function addNodesWorker(to: Node[], from: VisitResult<Node>[], startOnNewLine: boolean, test: (node: Node) => boolean, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node, isVisiting: boolean): void {
if (to && from) {
for (const node of from) {
addNodeWorker(to, node, startOnNewLine, test, parenthesize, parentNode, isVisiting);
@@ -772,9 +751,9 @@ namespace ts {
* @param node The SourceFile node.
* @param declarations The generated lexical declarations.
*/
export function mergeSourceFileLexicalEnvironment(node: SourceFile, declarations: Statement[]) {
export function mergeSourceFileLexicalEnvironment(node: SourceFile, declarations: Statement[]): SourceFile {
if (declarations !== undefined && declarations.length) {
const mutableNode = cloneNode(node, /*location*/ node, node.flags, /*parent*/ undefined, /*original*/ node);
const mutableNode = getMutableClone(node);
mutableNode.statements = mergeStatements(mutableNode.statements, declarations);
return mutableNode;
}
@@ -788,10 +767,10 @@ namespace ts {
* @param node The ModuleDeclaration node.
* @param declarations The generated lexical declarations.
*/
export function mergeModuleDeclarationLexicalEnvironment(node: ModuleDeclaration, declarations: Statement[]) {
export function mergeModuleDeclarationLexicalEnvironment(node: ModuleDeclaration, declarations: Statement[]): ModuleDeclaration {
Debug.assert(node.body.kind === SyntaxKind.ModuleBlock);
if (declarations !== undefined && declarations.length) {
const mutableNode = cloneNode(node, /*location*/ node, node.flags, /*parent*/ undefined, /*original*/ node);
const mutableNode = getMutableClone(node);
mutableNode.body = mergeBlockLexicalEnvironment(<ModuleBlock>node.body, declarations);
return mutableNode;
}
@@ -805,10 +784,10 @@ namespace ts {
* @param node The function-like node.
* @param declarations The generated lexical declarations.
*/
function mergeFunctionLikeLexicalEnvironment(node: FunctionLikeDeclaration, declarations: Statement[]) {
function mergeFunctionLikeLexicalEnvironment(node: FunctionLikeDeclaration, declarations: Statement[]): FunctionLikeDeclaration {
Debug.assert(node.body !== undefined);
if (declarations !== undefined && declarations.length) {
const mutableNode = cloneNode(node, /*location*/ node, node.flags, /*parent*/ undefined, /*original*/ node);
const mutableNode = getMutableClone(node);
mutableNode.body = mergeConciseBodyLexicalEnvironment(mutableNode.body, declarations);
return mutableNode;
}
@@ -822,7 +801,7 @@ namespace ts {
* @param node The ConciseBody of an arrow function.
* @param declarations The lexical declarations to merge.
*/
export function mergeFunctionBodyLexicalEnvironment(body: FunctionBody, declarations: Statement[]) {
export function mergeFunctionBodyLexicalEnvironment(body: FunctionBody, declarations: Statement[]): FunctionBody {
if (declarations !== undefined && declarations.length > 0) {
return mergeBlockLexicalEnvironment(body, declarations);
}
@@ -836,7 +815,7 @@ namespace ts {
* @param node The ConciseBody of an arrow function.
* @param declarations The lexical declarations to merge.
*/
export function mergeConciseBodyLexicalEnvironment(body: ConciseBody, declarations: Statement[]) {
export function mergeConciseBodyLexicalEnvironment(body: ConciseBody, declarations: Statement[]): ConciseBody {
if (declarations !== undefined && declarations.length > 0) {
if (isBlock(body)) {
return mergeBlockLexicalEnvironment(body, declarations);
@@ -858,8 +837,8 @@ namespace ts {
* @param node The block into which to merge lexical declarations.
* @param declarations The lexical declarations to merge.
*/
function mergeBlockLexicalEnvironment<T extends Block>(node: T, declarations: Statement[]) {
const mutableNode = cloneNode(node, /*location*/ node, node.flags, /*parent*/ undefined, /*original*/ node);
function mergeBlockLexicalEnvironment<T extends Block>(node: T, declarations: Statement[]): T {
const mutableNode = getMutableClone(node);
mutableNode.statements = mergeStatements(node.statements, declarations);
return mutableNode;
}
@@ -870,7 +849,7 @@ namespace ts {
* @param statements The node array to concatentate with the supplied lexical declarations.
* @param declarations The lexical declarations to merge.
*/
function mergeStatements(statements: NodeArray<Statement>, declarations: Statement[]) {
function mergeStatements(statements: NodeArray<Statement>, declarations: Statement[]): NodeArray<Statement> {
return createNodeArray(concatenate(statements, declarations), /*location*/ statements);
}
@@ -879,9 +858,9 @@ namespace ts {
*
* @param nodes The NodeArray.
*/
export function liftToBlock(nodes: NodeArray<Node>) {
export function liftToBlock(nodes: Node[]): Statement {
Debug.assert(every(nodes, isStatement), "Cannot lift nodes to a Block.");
return createBlock(<NodeArray<Statement>>nodes);
return <Statement>singleOrUndefined(nodes) || createBlock(<NodeArray<Statement>>nodes);
}
/**
@@ -889,9 +868,9 @@ namespace ts {
*
* @param nodes The NodeArray.
*/
function extractSingleNode(nodes: NodeArray<Node>) {
function extractSingleNode(nodes: Node[]): Node {
Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
return nodes.length > 0 ? nodes[0] : undefined;
return singleOrUndefined(nodes);
}
/**
@@ -911,15 +890,15 @@ namespace ts {
*/
function aggregateTransformFlagsForNode(node: Node): TransformFlags {
if (node === undefined) {
return <TransformFlags>0;
return TransformFlags.None;
}
if (node.transformFlags === undefined) {
else if (node.transformFlags & TransformFlags.HasComputedFlags) {
return node.transformFlags & ~node.excludeTransformFlags;
}
else {
const subtreeFlags = aggregateTransformFlagsForSubtree(node);
return computeTransformFlagsForNode(node, subtreeFlags);
}
return node.transformFlags & ~node.excludeTransformFlags;
}
/**
@@ -928,12 +907,12 @@ namespace ts {
function aggregateTransformFlagsForSubtree(node: Node): TransformFlags {
// We do not transform ambient declarations or types, so there is no need to
// recursively aggregate transform flags.
if (node.flags & NodeFlags.Ambient || isTypeNode(node)) {
return <TransformFlags>0;
if (hasModifier(node, ModifierFlags.Ambient) || isTypeNode(node)) {
return TransformFlags.None;
}
// Aggregate the transform flags of each child.
return reduceEachChild<TransformFlags>(node, aggregateTransformFlagsForChildNode, 0);
return reduceEachChild(node, aggregateTransformFlagsForChildNode, TransformFlags.None);
}
/**
@@ -943,4 +922,43 @@ namespace ts {
function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, child: Node): TransformFlags {
return transformFlags | aggregateTransformFlagsForNode(child);
}
export namespace Debug {
export function failNotOptional(message?: string) {
if (shouldAssert(AssertionLevel.Normal)) {
Debug.assert(false, message || "Node not optional.");
}
}
export function failBadSyntaxKind(node: Node, message?: string) {
if (shouldAssert(AssertionLevel.Normal)) {
Debug.assert(false,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was unexpected.`);
}
}
export function assertNode<T extends Node>(node: Node, test: (node: Node) => boolean, message?: string): void {
if (shouldAssert(AssertionLevel.Normal)) {
Debug.assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`);
};
}
function getFunctionName(func: Function) {
if (typeof func !== "function") {
return "";
}
else if (func.hasOwnProperty("name")) {
return (<any>func).name;
}
else {
const text = Function.prototype.toString.call(func);
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
return match ? match[1] : "";
}
}
}
}
+122 -115
View File
@@ -1,7 +1,7 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/// <reference path="typeWriter.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
const enum CompilerTestType {
Conformance,
@@ -88,7 +88,7 @@ class CompilerBaselineRunner extends RunnerBase {
toBeCompiled = [];
otherFiles = [];
if (/require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
if (testCaseContent.settings["noImplicitReferences"] || /require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content });
units.forEach(unit => {
if (unit.name !== lastUnit.name) {
@@ -102,6 +102,10 @@ class CompilerBaselineRunner extends RunnerBase {
});
}
if (tsConfigOptions && tsConfigOptions.configFilePath !== undefined) {
tsConfigOptions.configFilePath = ts.combinePaths(rootDir, tsConfigOptions.configFilePath);
}
const output = Harness.Compiler.compileFiles(
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ undefined);
@@ -140,7 +144,7 @@ class CompilerBaselineRunner extends RunnerBase {
});
it (`Correct module resolution tracing for ${fileName}`, () => {
if (options.traceModuleResolution) {
if (options.traceResolution) {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".trace.json"), () => {
return JSON.stringify(result.traceResults || [], undefined, 4);
});
@@ -252,125 +256,128 @@ class CompilerBaselineRunner extends RunnerBase {
}
// NEWTODO: Type baselines
if (result.errors.length === 0) {
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type outputed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
}
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
}
if (e1 || e2) {
throw e1 || e2;
}
if (result.errors.length !== 0) {
return;
}
function checkBaseLines(isSymbolBaseLine: boolean) {
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type displayed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
}
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
}
if (e1 || e2) {
throw e1 || e2;
}
return;
function checkBaseLines(isSymbolBaseLine: boolean) {
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
const codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
let typeInfo = [formattedLine];
const existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
const currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
const typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push("\r\n");
}
}
}
else {
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join("");
else {
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
const codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
let typeInfo = [formattedLine];
const existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
const currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
const typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push("\r\n");
}
}
}
else {
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join("");
}
});
});
}
+2 -2
View File
@@ -1073,7 +1073,7 @@ declare module "crypto" {
update(data: any): void;
sign(private_key: string, output_format: string): string;
}
export function createVerify(algorith: string): Verify;
export function createVerify(algorithm: string): Verify;
interface Verify {
update(data: any): void;
verify(object: string, signature: string, signature_format?: string): boolean;
@@ -1237,7 +1237,7 @@ declare module "assert" {
export function equal(actual: any, expected: any, message?: string): void;
export function notEqual(actual: any, expected: any, message?: string): void;
export function deepEqual(actual: any, expected: any, message?: string): void;
export function notDeepEqual(acutal: any, expected: any, message?: string): void;
export function notDeepEqual(actual: any, expected: any, message?: string): void;
export function strictEqual(actual: any, expected: any, message?: string): void;
export function notStrictEqual(actual: any, expected: any, message?: string): void;
export var throws: {
+69 -28
View File
@@ -18,7 +18,7 @@
/// <reference path="harnessLanguageService.ts" />
/// <reference path="harness.ts" />
/// <reference path="fourslashRunner.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace FourSlash {
ts.disableIncrementalParsing = false;
@@ -221,8 +221,8 @@ namespace FourSlash {
function tryAdd(path: string) {
const inputFile = inputFiles[path];
if (inputFile && !Harness.isLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile);
if (inputFile && !Harness.isDefaultLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile, /*isRootFile*/ true);
return true;
}
}
@@ -231,13 +231,13 @@ namespace FourSlash {
private getLanguageServiceAdapter(testType: FourSlashTestType, cancellationToken: TestCancellationToken, compilationOptions: ts.CompilerOptions): Harness.LanguageService.LanguageServiceAdapter {
switch (testType) {
case FourSlashTestType.Native:
return new Harness.LanguageService.NativeLanugageServiceAdapter(cancellationToken, compilationOptions);
return new Harness.LanguageService.NativeLanguageServiceAdapter(cancellationToken, compilationOptions);
case FourSlashTestType.Shims:
return new Harness.LanguageService.ShimLanugageServiceAdapter(/*preprocessToResolve*/ false, cancellationToken, compilationOptions);
return new Harness.LanguageService.ShimLanguageServiceAdapter(/*preprocessToResolve*/ false, cancellationToken, compilationOptions);
case FourSlashTestType.ShimsWithPreprocess:
return new Harness.LanguageService.ShimLanugageServiceAdapter(/*preprocessToResolve*/ true, cancellationToken, compilationOptions);
return new Harness.LanguageService.ShimLanguageServiceAdapter(/*preprocessToResolve*/ true, cancellationToken, compilationOptions);
case FourSlashTestType.Server:
return new Harness.LanguageService.ServerLanugageServiceAdapter(cancellationToken, compilationOptions);
return new Harness.LanguageService.ServerLanguageServiceAdapter(cancellationToken, compilationOptions);
default:
throw new Error("Unknown FourSlash test type: ");
}
@@ -247,6 +247,10 @@ namespace FourSlash {
// Create a new Services Adapter
this.cancellationToken = new TestCancellationToken();
const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
if (compilationOptions.typesRoot) {
compilationOptions.typesRoot = ts.getNormalizedAbsolutePath(compilationOptions.typesRoot, this.basePath);
}
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = languageServiceAdapter.getLanguageService();
@@ -268,7 +272,7 @@ namespace FourSlash {
if (startResolveFileRef) {
// Add the entry-point file itself into the languageServiceShimHost
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content);
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content, /*isRootFile*/ true);
const resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content);
const referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles;
@@ -291,17 +295,19 @@ namespace FourSlash {
// Check if no-default-lib flag is false and if so add default library
if (!resolvedResult.isLibFile) {
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
}
else {
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
ts.forEachKey(this.inputFiles, fileName => {
if (!Harness.isLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName]);
if (!Harness.isDefaultLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName], /*isRootFile*/ true);
}
});
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
this.formatCodeOptions = {
@@ -649,7 +655,7 @@ namespace FourSlash {
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
}
else {
this.raiseError(`No completions at position '${ this.currentCaretPosition }' when looking for '${ symbol }'.`);
this.raiseError(`No completions at position '${this.currentCaretPosition}' when looking for '${symbol}'.`);
}
}
@@ -1279,7 +1285,7 @@ namespace FourSlash {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
// this.checkPostEditInletiants();
// this.checkPostEditInvariants();
}
}
}
@@ -1370,7 +1376,7 @@ namespace FourSlash {
const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
// this.checkPostEditInletiants();
// this.checkPostEditInvariants();
}
}
}
@@ -1414,7 +1420,7 @@ namespace FourSlash {
return;
}
const incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName);
const incrementalSourceFile = this.languageService.getNonBoundSourceFile(this.activeFile.fileName);
Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined);
const incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics;
@@ -1752,13 +1758,13 @@ namespace FourSlash {
const actual = (<ts.server.SessionClient>this.languageService).getProjectInfo(
this.activeFile.fileName,
/* needFileNameList */ true
);
);
assert.equal(
expected.join(","),
actual.fileNames.map( file => {
actual.fileNames.map(file => {
return file.replace(this.basePath + "/", "");
}).join(",")
);
}).join(",")
);
}
}
@@ -1844,6 +1850,37 @@ namespace FourSlash {
});
}
public verifyBraceCompletionAtPostion(negative: boolean, openingBrace: string) {
const openBraceMap: ts.Map<ts.CharacterCodes> = {
"(": ts.CharacterCodes.openParen,
"{": ts.CharacterCodes.openBrace,
"[": ts.CharacterCodes.openBracket,
"'": ts.CharacterCodes.singleQuote,
'"': ts.CharacterCodes.doubleQuote,
"`": ts.CharacterCodes.backtick,
"<": ts.CharacterCodes.lessThan
};
const charCode = openBraceMap[openingBrace];
if (!charCode) {
this.raiseError(`Invalid openingBrace '${openingBrace}' specified.`);
}
const position = this.currentCaretPosition;
const validBraceCompletion = this.languageService.isValidBraceCompletionAtPostion(this.activeFile.fileName, position, charCode);
if (!negative && !validBraceCompletion) {
this.raiseError(`${position} is not a valid brace completion position for ${openingBrace}`);
}
if (negative && validBraceCompletion) {
this.raiseError(`${position} is a valid brace completion position for ${openingBrace}`);
}
}
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) {
const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
@@ -2233,7 +2270,7 @@ namespace FourSlash {
};
const host = Harness.Compiler.createCompilerHost(
[ fourslashFile, testFile ],
[fourslashFile, testFile],
(fn, contents) => result = contents,
ts.ScriptTarget.Latest,
Harness.IO.useCaseSensitiveFileNames(),
@@ -2245,8 +2282,8 @@ namespace FourSlash {
const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
if (diagnostics.length > 0) {
throw new Error(`Error compiling ${fileName}: ` +
diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, Harness.IO.newLine())).join("\r\n"));
const diagnosticText = diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, Harness.IO.newLine())).join("\r\n");
throw new Error(`Error compiling ${fileName}: ${diagnosticText}`);
}
program.emit(sourceFile);
@@ -2258,7 +2295,7 @@ namespace FourSlash {
function runCode(code: string, state: TestState): void {
// Compile and execute the test
const wrappedCode =
`(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) {
`(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) {
${code}
})`;
try {
@@ -2372,7 +2409,7 @@ ${code}
}
}
}
// TODO: should be '==='?
// TODO: should be '==='?
}
else if (line == "" || lineLength === 0) {
// Previously blank lines between fourslash content caused it to be considered as 2 files,
@@ -2771,12 +2808,12 @@ namespace FourSlashInterface {
// Verifies the member list contains the specified symbol. The
// member list is brought up if necessary
public memberListContains(symbol: string, text?: string, documenation?: string, kind?: string) {
public memberListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
if (this.negative) {
this.state.verifyMemberListDoesNotContain(symbol);
}
else {
this.state.verifyMemberListContains(symbol, text, documenation, kind);
this.state.verifyMemberListContains(symbol, text, documentation, kind);
}
}
@@ -2864,6 +2901,10 @@ namespace FourSlashInterface {
public verifyDefinitionsName(name: string, containerName: string) {
this.state.verifyDefinitionsName(this.negative, name, containerName);
}
public isValidBraceCompletionAtPostion(openingBrace: string) {
this.state.verifyBraceCompletionAtPostion(this.negative, openingBrace);
}
}
export class Verify extends VerifyNegatable {
@@ -3082,7 +3123,7 @@ namespace FourSlashInterface {
this.state.getSemanticDiagnostics(expected);
}
public ProjectInfo(expected: string []) {
public ProjectInfo(expected: string[]) {
this.state.verifyProjectInfo(expected);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
///<reference path="fourslash.ts" />
///<reference path="harness.ts"/>
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
const enum FourSlashTestType {
Native,
+166 -52
View File
@@ -1,7 +1,7 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -23,7 +23,7 @@
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
@@ -65,6 +65,11 @@ namespace Utils {
return Buffer ? (new Buffer(s)).toString("utf8") : s;
}
export function byteLength(s: string, encoding?: string): number {
// stub implementation if Buffer is not available (in-browser case)
return Buffer ? Buffer.byteLength(s, encoding) : s.length;
}
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
const environment = getExecutionEnvironment();
switch (environment) {
@@ -346,7 +351,7 @@ namespace Utils {
assert.equal(node1.end, node2.end, "node1.end !== node2.end");
assert.equal(node1.kind, node2.kind, "node1.kind !== node2.kind");
// call this on both nodes to ensure all propagated flags have been set (and thus can be
// call this on both nodes to ensure all propagated flags have been set (and thus can be
// compared).
assert.equal(ts.containsParseError(node1), ts.containsParseError(node2));
assert.equal(node1.flags, node2.flags, "node1.flags !== node2.flags");
@@ -391,6 +396,60 @@ namespace Utils {
throw new Error("Could not find child in parent");
}
const maxHarnessFrames = 1;
export function filterStack(error: Error, stackTraceLimit: number = Infinity) {
const stack = <string>(<any>error).stack;
if (stack) {
const lines = stack.split(/\r\n?|\n/g);
const filtered: string[] = [];
let frameCount = 0;
let harnessFrameCount = 0;
for (let line of lines) {
if (isStackFrame(line)) {
if (frameCount >= stackTraceLimit
|| isMocha(line)
|| isNode(line)) {
continue;
}
if (isHarness(line)) {
if (harnessFrameCount >= maxHarnessFrames) {
continue;
}
harnessFrameCount++;
}
line = line.replace(/\bfile:\/\/\/(.*?)(?=(:\d+)*($|\)))/, (_, path) => ts.sys.resolvePath(path));
frameCount++;
}
filtered.push(line);
}
(<any>error).stack = filtered.join(Harness.IO.newLine());
}
return error;
}
function isStackFrame(line: string) {
return /^\s+at\s/.test(line);
}
function isMocha(line: string) {
return /[\\/](node_modules|components)[\\/]mocha(js)?[\\/]|[\\/]mocha\.js/.test(line);
}
function isNode(line: string) {
return /\((timers|events|node|module)\.js:/.test(line);
}
function isHarness(line: string) {
return /[\\/]src[\\/]harness[\\/]|[\\/]run\.js/.test(line);
}
}
namespace Harness.Path {
@@ -426,6 +485,8 @@ namespace Harness {
getExecutingFilePath(): string;
exit(exitCode?: number): void;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
tryEnableSourceMapsForHost?(): void;
getEnvironmentVariable?(name: string): string;
}
export var IO: IO;
@@ -464,6 +525,7 @@ namespace Harness {
export const fileExists: typeof IO.fileExists = fso.FileExists;
export const log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export const readDirectory: typeof IO.readDirectory = (path, extension, exclude) => ts.sys.readDirectory(path, extension, exclude);
export const getEnvironmentVariable: typeof IO.getEnvironmentVariable = name => ts.sys.getEnvironmentVariable(name);
export function createDirectory(path: string) {
if (directoryExists(path)) {
@@ -533,6 +595,13 @@ namespace Harness {
export const log: typeof IO.log = s => console.log(s);
export const readDirectory: typeof IO.readDirectory = (path, extension, exclude) => ts.sys.readDirectory(path, extension, exclude);
export const getEnvironmentVariable: typeof IO.getEnvironmentVariable = name => ts.sys.getEnvironmentVariable(name);
export function tryEnableSourceMapsForHost() {
if (ts.sys.tryEnableSourceMapsForHost) {
ts.sys.tryEnableSourceMapsForHost();
}
}
export function createDirectory(path: string) {
if (!directoryExists(path)) {
@@ -687,7 +756,16 @@ namespace Harness {
return dirPath;
}
export let directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export const resolvePath = (path: string) => directoryName(path);
export function resolvePath(path: string) {
const response = Http.getFileFromServerSync(serverRoot + path + "?resolve=true");
if (response.status === 200) {
return response.responseText;
}
else {
return null;
}
}
export function fileExists(path: string): boolean {
const response = Http.getFileFromServerSync(serverRoot + path);
@@ -746,14 +824,16 @@ namespace Harness {
namespace Harness {
export const libFolder = "built/local/";
const tcServicesFileName = ts.combinePaths(libFolder, "typescriptServices.js");
export const tcServicesFile = IO.readFile(tcServicesFileName);
const tcServicesFileName = ts.combinePaths(libFolder, Utils.getExecutionEnvironment() === Utils.ExecutionEnvironment.Browser ? "typescriptServicesInBrowserTest.js" : "typescriptServices.js");
export const tcServicesFile = IO.readFile(tcServicesFileName) + (Utils.getExecutionEnvironment() !== Utils.ExecutionEnvironment.Browser
? IO.newLine() + `//# sourceURL=${IO.resolvePath(tcServicesFileName)}`
: "");
export interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
}
// Settings
// Settings
export let userSpecifiedRoot = "";
export let lightMode = false;
@@ -792,7 +872,7 @@ namespace Harness {
fileName: string,
sourceText: string,
languageVersion: ts.ScriptTarget) {
// We'll only assert invariants outside of light mode.
// We'll only assert invariants outside of light mode.
const shouldAssertInvariants = !Harness.lightMode;
// Only set the parent nodes if we're asserting invariants. We don't need them otherwise.
@@ -809,15 +889,33 @@ namespace Harness {
const lineFeed = "\n";
export const defaultLibFileName = "lib.d.ts";
export const defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
const libFileNameSourceFileMap: ts.Map<ts.SourceFile> = {
[defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest)
};
export function getDefaultLibrarySourceFile(fileName = defaultLibFileName): ts.SourceFile {
if (!isDefaultLibraryFile(fileName)) {
return undefined;
}
if (!libFileNameSourceFileMap[fileName]) {
libFileNameSourceFileMap[fileName] = createSourceFileAndAssertInvariants(fileName, IO.readFile(libFolder + fileName), ts.ScriptTarget.Latest);
}
return libFileNameSourceFileMap[fileName];
}
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName;
}
// Cache these between executions so we don't have to re-parse them for every test
export const fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return Harness.IO.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
return fileName;
}
export function createCompilerHost(
@@ -842,23 +940,21 @@ namespace Harness {
}
}
function getSourceFile(fn: string, languageVersion: ts.ScriptTarget) {
fn = ts.normalizePath(fn);
const path = ts.toPath(fn, currentDirectory, getCanonicalFileName);
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget) {
fileName = ts.normalizePath(fileName);
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
return fileMap.get(path);
}
else if (fn === fourslashFileName) {
else if (fileName === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
return fourslashSourceFile;
}
else {
if (fn === defaultLibFileName) {
return languageVersion === ts.ScriptTarget.ES6 ? defaultES6LibSourceFile : defaultLibSourceFile;
}
// Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC
return undefined;
// Return if it is other library file, otherwise return undefined
return getDefaultLibrarySourceFile(fileName);
}
}
@@ -867,16 +963,21 @@ namespace Harness {
newLineKind === ts.NewLineKind.LineFeed ? lineFeed :
Harness.IO.newLine();
return {
getCurrentDirectory: () => currentDirectory,
getSourceFile,
getDefaultLibFileName: options => defaultLibFileName,
getDefaultLibFileName,
writeFile,
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => newLine,
fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
readFile: (fileName: string): string => { throw new Error("NotYetImplemented"); }
fileExists: fileName => {
return fileMap.contains(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
},
readFile: (fileName: string): string => {
return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)).getText();
}
};
}
@@ -887,7 +988,7 @@ namespace Harness {
libFiles?: string;
}
// Additional options not already in ts.optionDeclarations
// Additional options not already in ts.optionDeclarations
const harnessOptionDeclarations: ts.CommandLineOption[] = [
{ name: "allowNonTsExtensions", type: "boolean" },
{ name: "useCaseSensitiveFileNames", type: "boolean" },
@@ -895,7 +996,9 @@ namespace Harness {
{ name: "includeBuiltFile", type: "string" },
{ name: "fileName", type: "string" },
{ name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" }
{ name: "noErrorTruncation", type: "boolean" },
{ name: "suppressOutputPathCheck", type: "boolean" },
{ name: "noImplicitReferences", type: "boolean" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
@@ -919,6 +1022,7 @@ namespace Harness {
}
const option = getCommandLineOption(name);
if (option) {
const errors: ts.Diagnostic[] = [];
switch (option.type) {
case "boolean":
options[option.name] = value.toLowerCase() === "true";
@@ -927,15 +1031,16 @@ namespace Harness {
options[option.name] = value;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
case "list":
options[option.name] = ts.parseListTypeOption(<ts.CommandLineOptionOfListType>option, value, errors);
break;
default:
let map = <ts.Map<number>>option.type;
let key = value.toLowerCase();
if (ts.hasProperty(map, key)) {
options[option.name] = map[key];
}
else {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
options[option.name] = ts.parseCustomTypeOption(<ts.CommandLineOptionOfCustomType>option, value, errors);
break;
}
if (errors.length > 0) {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
}
else {
@@ -962,10 +1067,8 @@ namespace Harness {
compilerOptions: ts.CompilerOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory: string): CompilationOutput {
const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.clone(compilerOptions) : { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.module = options.module || ts.ModuleKind.None;
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
options.noErrorTruncation = true;
options.skipDefaultLibCheck = true;
@@ -1015,7 +1118,7 @@ namespace Harness {
options.newLine);
let traceResults: string[];
if (options.traceModuleResolution) {
if (options.traceResolution) {
traceResults = [];
compilerHost.trace = text => traceResults.push(text);
}
@@ -1134,11 +1237,11 @@ namespace Harness {
errLines.forEach(e => outputLines.push(e));
// do not count errors from lib.d.ts here, they are computed separately as numLibraryDiagnostics
// if lib.d.ts is explicitly included in input files and there are some errors in it (i.e. because of duplicate identifiers)
// if lib.d.ts is explicitly included in input files and there are some errors in it (i.e. because of duplicate identifiers)
// then they will be added twice thus triggering 'total errors' assertion with condition
// 'totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length
if (!error.file || !isLibraryFile(error.file.fileName)) {
if (!error.file || !isDefaultLibraryFile(error.file.fileName)) {
totalErrorsReportedInNonLibraryFiles++;
}
}
@@ -1217,7 +1320,7 @@ namespace Harness {
});
const numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
return diagnostic.file && (isLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
return diagnostic.file && (isDefaultLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
});
const numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
@@ -1330,7 +1433,7 @@ namespace Harness {
public getSourceMapRecord() {
if (this.sourceMapData) {
return Harness.SourceMapRecoder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
return Harness.SourceMapRecorder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
}
}
}
@@ -1444,7 +1547,7 @@ namespace Harness {
};
testUnitData.push(newTestFile2);
// unit tests always list files explicitly
// unit tests always list files explicitly
const parseConfigHost: ts.ParseConfigHost = {
readDirectory: (name) => []
};
@@ -1461,6 +1564,7 @@ namespace Harness {
baseDir = ts.getNormalizedAbsolutePath(baseDir, rootDir);
}
tsConfig = ts.parseJsonConfigFileContent(configJson.config, parseConfigHost, baseDir);
tsConfig.options.configFilePath = data.name;
// delete entry from the list
testUnitData.splice(i, 1);
@@ -1589,23 +1693,29 @@ namespace Harness {
let actual = <string>undefined;
const actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
try {
if (runImmediately) {
actual = generateActual(actualFileName, generateContent);
const comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
}
else {
actual = generateActual(actualFileName, generateContent);
if (runImmediately) {
actual = generateActual(actualFileName, generateContent);
const comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
const comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
}
}
else {
actual = generateActual(actualFileName, generateContent);
const comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
catch (e) {
throw Utils.filterStack(e);
}
}
}
export function isLibraryFile(filePath: string): boolean {
return (Path.getFileName(filePath) === "lib.d.ts") || (Path.getFileName(filePath) === "lib.core.d.ts");
export function isDefaultLibraryFile(filePath: string): boolean {
// We need to make sure that the filePath is prefixed with "lib." not just containing "lib." and end with ".d.ts"
const fileName = Path.getFileName(filePath);
return ts.startsWith(fileName, "lib.") && ts.endsWith(fileName, ".d.ts");
}
export function isBuiltFile(filePath: string): boolean {
@@ -1613,12 +1723,16 @@ namespace Harness {
}
export function getDefaultLibraryFile(io: Harness.IO): Harness.Compiler.TestFile {
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + "lib.d.ts";
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + Harness.Compiler.defaultLibFileName;
return { unitName: libFile, content: io.readFile(libFile) };
}
if (Error) (<any>Error).stackTraceLimit = 1;
}
if (Harness.IO.tryEnableSourceMapsForHost && /^development$/i.test(Harness.IO.getEnvironmentVariable("NODE_ENV"))) {
Harness.IO.tryEnableSourceMapsForHost();
}
// TODO: not sure why Utils.evalFile isn't working with this, eventually will concat it like old compiler instead of eval
eval(Harness.tcServicesFile);
+49 -12
View File
@@ -9,7 +9,7 @@ namespace Harness.LanguageService {
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
private lineMap: number[] = undefined;
constructor(public fileName: string, public content: string) {
constructor(public fileName: string, public content: string, public isRootFile: boolean) {
this.setContent(content);
}
@@ -135,7 +135,13 @@ namespace Harness.LanguageService {
public getFilenames(): string[] {
const fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript, (fileName) => { fileNames.push(fileName); });
ts.forEachValue(this.fileNameToScript, (scriptInfo) => {
if (scriptInfo.isRootFile) {
// only include root files here
// usually it means that we won't include lib.d.ts in the list of root files so it won't mess the computation of compilation root dir.
fileNames.push(scriptInfo.fileName);
}
});
return fileNames;
}
@@ -143,8 +149,8 @@ namespace Harness.LanguageService {
return ts.lookUp(this.fileNameToScript, fileName);
}
public addScript(fileName: string, content: string): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content);
public addScript(fileName: string, content: string, isRootFile: boolean): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content, isRootFile);
}
public editScript(fileName: string, start: number, end: number, newText: string) {
@@ -177,12 +183,13 @@ namespace Harness.LanguageService {
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getCurrentDirectory(): string { return ""; }
getDefaultLibFileName(): string { return ""; }
getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; }
getScriptFileNames(): string[] { return this.getFilenames(); }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
const script = this.getScriptInfo(fileName);
return script ? new ScriptSnapshot(script) : undefined;
}
getScriptKind(fileName: string): ts.ScriptKind { return ts.ScriptKind.Unknown; }
getScriptVersion(fileName: string): string {
const script = this.getScriptInfo(fileName);
return script ? script.version.toString() : undefined;
@@ -193,7 +200,7 @@ namespace Harness.LanguageService {
error(s: string): void { }
}
export class NativeLanugageServiceAdapter implements LanguageServiceAdapter {
export class NativeLanguageServiceAdapter implements LanguageServiceAdapter {
private host: NativeLanguageServiceHost;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new NativeLanguageServiceHost(cancellationToken, options);
@@ -209,6 +216,7 @@ namespace Harness.LanguageService {
private nativeHost: NativeLanguageServiceHost;
public getModuleResolutionsForFile: (fileName: string) => string;
public getTypeReferenceDirectiveResolutionsForFile: (fileName: string) => string;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
@@ -235,12 +243,25 @@ namespace Harness.LanguageService {
}
return JSON.stringify(imports);
};
this.getTypeReferenceDirectiveResolutionsForFile = (fileName) => {
const scriptInfo = this.getScriptInfo(fileName);
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false);
const resolutions: ts.Map<ts.ResolvedTypeReferenceDirective> = {};
const settings = this.nativeHost.getCompilationSettings();
for (const typeReferenceDirective of preprocessInfo.typeReferenceDirectives) {
const resolutionInfo = ts.resolveTypeReferenceDirective(typeReferenceDirective.fileName, fileName, settings, moduleResolutionHost);
if (resolutionInfo.resolvedTypeReferenceDirective.resolvedFileName) {
resolutions[typeReferenceDirective.fileName] = resolutionInfo.resolvedTypeReferenceDirective;
}
}
return JSON.stringify(resolutions);
};
}
}
getFilenames(): string[] { return this.nativeHost.getFilenames(); }
getScriptInfo(fileName: string): ScriptInfo { return this.nativeHost.getScriptInfo(fileName); }
addScript(fileName: string, content: string): void { this.nativeHost.addScript(fileName, content); }
addScript(fileName: string, content: string, isRootFile: boolean): void { this.nativeHost.addScript(fileName, content, isRootFile); }
editScript(fileName: string, start: number, end: number, newText: string): void { this.nativeHost.editScript(fileName, start, end, newText); }
positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter { return this.nativeHost.positionToLineAndCharacter(fileName, position); }
@@ -253,6 +274,7 @@ namespace Harness.LanguageService {
const nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
}
getScriptKind(fileName: string): ts.ScriptKind { return this.nativeHost.getScriptKind(fileName); }
getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); }
getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); }
@@ -415,19 +437,22 @@ namespace Harness.LanguageService {
getDocCommentTemplateAtPosition(fileName: string, position: number): ts.TextInsertion {
return unwrapJSONCallResult(this.shim.getDocCommentTemplateAtPosition(fileName, position));
}
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPostion(fileName, position, openingBrace));
}
getEmitOutput(fileName: string): ts.EmitOutput {
return unwrapJSONCallResult(this.shim.getEmitOutput(fileName));
}
getProgram(): ts.Program {
throw new Error("Program can not be marshaled across the shim layer.");
}
getSourceFile(fileName: string): ts.SourceFile {
getNonBoundSourceFile(fileName: string): ts.SourceFile {
throw new Error("SourceFile can not be marshaled across the shim layer.");
}
dispose(): void { this.shim.dispose({}); }
}
export class ShimLanugageServiceAdapter implements LanguageServiceAdapter {
export class ShimLanguageServiceAdapter implements LanguageServiceAdapter {
private host: ShimLanguageServiceHost;
private factory: ts.TypeScriptServicesFactory;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
@@ -440,6 +465,7 @@ namespace Harness.LanguageService {
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo {
let shimResult: {
referencedFiles: ts.IFileReference[];
typeReferenceDirectives: ts.IFileReference[];
importedFiles: ts.IFileReference[];
isLibFile: boolean;
};
@@ -451,7 +477,8 @@ namespace Harness.LanguageService {
referencedFiles: [],
importedFiles: [],
ambientExternalModules: [],
isLibFile: shimResult.isLibFile
isLibFile: shimResult.isLibFile,
typeReferenceDirectives: []
};
ts.forEach(shimResult.referencedFiles, refFile => {
@@ -470,6 +497,13 @@ namespace Harness.LanguageService {
});
});
ts.forEach(shimResult.typeReferenceDirectives, typeRefDirective => {
convertResult.importedFiles.push({
fileName: typeRefDirective.path,
pos: typeRefDirective.position,
end: typeRefDirective.position + typeRefDirective.length
});
});
return convertResult;
}
}
@@ -566,6 +600,10 @@ namespace Harness.LanguageService {
return this.host.getCurrentDirectory();
}
getEnvironmentVariable(name: string): string {
return ts.sys.getEnvironmentVariable(name);
}
readDirectory(path: string, extension?: string): string[] {
throw new Error("Not implemented Yet.");
}
@@ -609,7 +647,7 @@ namespace Harness.LanguageService {
}
}
export class ServerLanugageServiceAdapter implements LanguageServiceAdapter {
export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
private host: SessionClientHost;
private client: ts.server.SessionClient;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
@@ -642,4 +680,3 @@ namespace Harness.LanguageService {
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { throw new Error("getPreProcessedFileInfo is not available using the server interface."); }
}
}
+16 -5
View File
@@ -1,7 +1,7 @@
/// <reference path="..\..\src\compiler\sys.ts" />
/// <reference path="..\..\src\harness\harness.ts" />
/// <reference path="..\..\src\harness\runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
interface FileInformation {
contents: string;
@@ -136,7 +136,7 @@ namespace Playback {
};
wrapper.startReplayFromData = log => {
replayLog = log;
// Remove non-found files from the log (shouldn't really need them, but we still record them for diganostic purposes)
// Remove non-found files from the log (shouldn't really need them, but we still record them for diagnostic purposes)
replayLog.filesRead = replayLog.filesRead.filter(f => f.result.contents !== undefined);
};
@@ -223,11 +223,22 @@ namespace Playback {
recordLog.directoriesRead.push(logEntry);
return result;
},
(path, extension, exclude) => findResultByPath(wrapper, replayLog.directoriesRead.filter(d => d.extension === extension && ts.arrayIsEqualTo(d.exclude, exclude)), path));
(path, extension, exclude) => findResultByPath(wrapper,
replayLog.directoriesRead.filter(
d => {
if (d.extension === extension) {
if (d.exclude) {
return ts.arrayIsEqualTo(d.exclude, exclude);
}
return true;
}
return false;
}
), path));
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path, contents) => noOpReplay("writeFile"));
(path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path: string, contents: string) => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {
+32 -25
View File
@@ -1,6 +1,6 @@
///<reference path="harness.ts" />
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
// Test case is json of below type in tests/cases/project/
interface ProjectRunnerTestCase {
@@ -156,7 +156,7 @@ class ProjectRunner extends RunnerBase {
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile {
let sourceFile: ts.SourceFile = undefined;
if (fileName === Harness.Compiler.defaultLibFileName) {
sourceFile = languageVersion === ts.ScriptTarget.ES6 ? Harness.Compiler.defaultES6LibSourceFile : Harness.Compiler.defaultLibSourceFile;
sourceFile = Harness.Compiler.getDefaultLibrarySourceFile(Harness.Compiler.getDefaultLibFileName(compilerOptions));
}
else {
const text = getSourceFileText(fileName);
@@ -370,14 +370,14 @@ class ProjectRunner extends RunnerBase {
}
const outputDtsFileName = emitOutputFilePathWithoutExtension + ".d.ts";
const file = findOutpuDtsFile(outputDtsFileName);
const file = findOutputDtsFile(outputDtsFileName);
if (file) {
allInputFiles.unshift(file);
}
}
else {
const outputDtsFileName = ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts";
const outputDtsFile = findOutpuDtsFile(outputDtsFileName);
const outputDtsFile = findOutputDtsFile(outputDtsFileName);
if (!ts.contains(allInputFiles, outputDtsFile)) {
allInputFiles.unshift(outputDtsFile);
}
@@ -387,7 +387,7 @@ class ProjectRunner extends RunnerBase {
// Dont allow config files since we are compiling existing source options
return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile, compilerResult.compilerOptions);
function findOutpuDtsFile(fileName: string) {
function findOutputDtsFile(fileName: string) {
return ts.forEach(compilerResult.outputFiles, outputFile => outputFile.emittedFileName === fileName ? outputFile : undefined);
}
function getInputFiles() {
@@ -412,7 +412,7 @@ class ProjectRunner extends RunnerBase {
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
const inputFiles = compilerResult.program ? ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => !Harness.isDefaultLibraryFile(sourceFile.fileName)),
sourceFile => {
return {
unitName: ts.isRootedDiskPath(sourceFile.fileName) ?
@@ -463,32 +463,39 @@ class ProjectRunner extends RunnerBase {
}
});
it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (testCase.baselineCheck) {
var lastError: any = undefined;
ts.forEach(compilerResult.outputFiles, outputFile => {
Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return Harness.IO.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
}
});
try {
Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return Harness.IO.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
}
});
}
catch (e) {
lastError = e;
}
});
if (lastError) {
throw lastError;
}
}
});
it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline("SourceMapRecord for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
}
});
// it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
// if (compilerResult.sourceMapData) {
// Harness.Baseline.runBaseline("SourceMapRecord for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
// return Harness.SourceMapRecorder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
// ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
// });
// }
// });
// Verify that all the generated .d.ts files compile
+17 -4
View File
@@ -20,7 +20,7 @@
/// <reference path="rwcRunner.ts" />
/// <reference path="harness.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
let runners: RunnerBase[] = [];
let iterations = 1;
@@ -40,14 +40,27 @@ let testConfigFile =
Harness.IO.fileExists(mytestconfig) ? Harness.IO.readFile(mytestconfig) :
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : "");
type TestConfig = {
tests?: string[];
stackTraceLimit?: number | "full";
light?: boolean;
};
if (testConfigFile !== "") {
const testConfig = JSON.parse(testConfigFile);
const testConfig = <TestConfig>JSON.parse(testConfigFile);
if (testConfig.light) {
Harness.lightMode = true;
}
if (testConfig.test && testConfig.test.length > 0) {
for (const option of testConfig.test) {
if (testConfig.stackTraceLimit === "full") {
(<any>Error).stackTraceLimit = Infinity;
}
else if ((+testConfig.stackTraceLimit | 0) > 0) {
(<any>Error).stackTraceLimit = testConfig.stackTraceLimit;
}
if (testConfig.tests && testConfig.tests.length > 0) {
for (const option of testConfig.tests) {
if (!option) {
continue;
}
+10 -11
View File
@@ -2,7 +2,7 @@
/// <reference path="runnerbase.ts" />
/// <reference path="loggedIO.ts" />
/// <reference path="..\compiler\commandLineParser.ts"/>
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace RWC {
function runWithIOLog(ioLog: IOLog, fn: (oldIO: Harness.IO) => void) {
@@ -31,22 +31,20 @@ namespace RWC {
let otherFiles: Harness.Compiler.TestFile[] = [];
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
const baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: "rwc",
Baselinefolder: "internal/baselines"
};
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
const baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
let useCustomLibraryFile: boolean;
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
inputFiles = undefined;
otherFiles = undefined;
inputFiles = [];
otherFiles = [];
compilerResult = undefined;
compilerOptions = undefined;
baselineOpts = undefined;
baseName = undefined;
currentDirectory = undefined;
// useCustomLibraryFile is a flag specified in the json object to indicate whether to use built/local/lib.d.ts
// or to use lib.d.ts inside the json object. If the flag is true, use the lib.d.ts inside json file
@@ -97,13 +95,13 @@ namespace RWC {
continue;
}
if (!Harness.isLibraryFile(fileRead.path)) {
if (!Harness.isDefaultLibraryFile(fileRead.path)) {
if (inInputList) {
continue;
}
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
}
else if (!opts.options.noLib && Harness.isLibraryFile(fileRead.path)) {
else if (!opts.options.noLib && Harness.isDefaultLibraryFile(fileRead.path)) {
if (!inInputList) {
// If useCustomLibraryFile is true, we will use lib.d.ts from json object
// otherwise use the lib.d.ts from built/local
@@ -192,8 +190,9 @@ namespace RWC {
if (compilerResult.errors.length === 0) {
return null;
}
return Harness.Compiler.getErrorBaseline(inputFiles.concat(otherFiles), compilerResult.errors);
// Do not include the library in the baselines to avoid noise
const baselineFiles = inputFiles.concat(otherFiles).filter(f => !Harness.isDefaultLibraryFile(f.unitName));
return Harness.Compiler.getErrorBaseline(baselineFiles, compilerResult.errors);
}, false, baselineOpts);
});
+32 -32
View File
@@ -15,7 +15,7 @@
///<reference path="harness.ts"/>
namespace Harness.SourceMapRecoder {
namespace Harness.SourceMapRecorder {
interface SourceMapSpanWithDecodeErrors {
sourceMapSpan: ts.SourceMapSpan;
@@ -202,7 +202,7 @@ namespace Harness.SourceMapRecoder {
}
namespace SourceMapSpanWriter {
let sourceMapRecoder: Compiler.WriterAggregator;
let sourceMapRecorder: Compiler.WriterAggregator;
let sourceMapSources: string[];
let sourceMapNames: string[];
@@ -216,8 +216,8 @@ namespace Harness.SourceMapRecoder {
let prevWrittenJsLine: number;
let spanMarkerContinues: boolean;
export function intializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: Compiler.GeneratedFile) {
sourceMapRecoder = sourceMapRecordWriter;
export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: Compiler.GeneratedFile) {
sourceMapRecorder = sourceMapRecordWriter;
sourceMapSources = sourceMapData.sourceMapSources;
sourceMapNames = sourceMapData.sourceMapNames;
@@ -231,15 +231,15 @@ namespace Harness.SourceMapRecoder {
SourceMapDecoder.initializeSourceMapDecoding(sourceMapData);
sourceMapRecoder.WriteLine("===================================================================");
sourceMapRecoder.WriteLine("JsFile: " + sourceMapData.sourceMapFile);
sourceMapRecoder.WriteLine("mapUrl: " + sourceMapData.jsSourceMappingURL);
sourceMapRecoder.WriteLine("sourceRoot: " + sourceMapData.sourceMapSourceRoot);
sourceMapRecoder.WriteLine("sources: " + sourceMapData.sourceMapSources);
sourceMapRecorder.WriteLine("===================================================================");
sourceMapRecorder.WriteLine("JsFile: " + sourceMapData.sourceMapFile);
sourceMapRecorder.WriteLine("mapUrl: " + sourceMapData.jsSourceMappingURL);
sourceMapRecorder.WriteLine("sourceRoot: " + sourceMapData.sourceMapSourceRoot);
sourceMapRecorder.WriteLine("sources: " + sourceMapData.sourceMapSources);
if (sourceMapData.sourceMapSourcesContent) {
sourceMapRecoder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMapSourcesContent));
sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMapSourcesContent));
}
sourceMapRecoder.WriteLine("===================================================================");
sourceMapRecorder.WriteLine("===================================================================");
}
function getSourceMapSpanString(mapEntry: ts.SourceMapSpan, getAbsentNameIndex?: boolean) {
@@ -291,10 +291,10 @@ namespace Harness.SourceMapRecoder {
recordSourceMapSpan(sourceMapSpan);
assert.isTrue(spansOnSingleLine.length === 1);
sourceMapRecoder.WriteLine("-------------------------------------------------------------------");
sourceMapRecoder.WriteLine("emittedFile:" + jsFile.fileName);
sourceMapRecoder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex]);
sourceMapRecoder.WriteLine("-------------------------------------------------------------------");
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
sourceMapRecorder.WriteLine("emittedFile:" + jsFile.fileName);
sourceMapRecorder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex]);
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
tsLineMap = ts.computeLineStarts(newSourceFileCode);
tsCode = newSourceFileCode;
@@ -306,8 +306,8 @@ namespace Harness.SourceMapRecoder {
writeRecordedSpans();
if (!SourceMapDecoder.hasCompletedDecoding()) {
sourceMapRecoder.WriteLine("!!!! **** There are more source map entries in the sourceMap's mapping than what was encoded");
sourceMapRecoder.WriteLine("!!!! **** Remaining decoded string: " + SourceMapDecoder.getRemainingDecodeString());
sourceMapRecorder.WriteLine("!!!! **** There are more source map entries in the sourceMap's mapping than what was encoded");
sourceMapRecorder.WriteLine("!!!! **** Remaining decoded string: " + SourceMapDecoder.getRemainingDecodeString());
}
@@ -323,7 +323,7 @@ namespace Harness.SourceMapRecoder {
function writeJsFileLines(endJsLine: number) {
for (; prevWrittenJsLine < endJsLine; prevWrittenJsLine++) {
sourceMapRecoder.Write(">>>" + getTextOfLine(prevWrittenJsLine, jsLineMap, jsFile.code));
sourceMapRecorder.Write(">>>" + getTextOfLine(prevWrittenJsLine, jsLineMap, jsFile.code));
}
}
@@ -356,9 +356,9 @@ namespace Harness.SourceMapRecoder {
}
function writeSourceMapIndent(indentLength: number, indentPrefix: string) {
sourceMapRecoder.Write(indentPrefix);
sourceMapRecorder.Write(indentPrefix);
for (let i = 1; i < indentLength; i++) {
sourceMapRecoder.Write(" ");
sourceMapRecorder.Write(" ");
}
}
@@ -369,12 +369,12 @@ namespace Harness.SourceMapRecoder {
writeSourceMapIndent(prevEmittedCol, markerId);
for (let i = prevEmittedCol; i < endColumn; i++) {
sourceMapRecoder.Write("^");
sourceMapRecorder.Write("^");
}
if (endContinues) {
sourceMapRecoder.Write("->");
sourceMapRecorder.Write("->");
}
sourceMapRecoder.WriteLine("");
sourceMapRecorder.WriteLine("");
spanMarkerContinues = endContinues;
}
@@ -390,16 +390,16 @@ namespace Harness.SourceMapRecoder {
// If there are decode errors, write
for (let i = 0; i < currentSpan.decodeErrors.length; i++) {
writeSourceMapIndent(prevEmittedCol, markerIds[index]);
sourceMapRecoder.WriteLine(currentSpan.decodeErrors[i]);
sourceMapRecorder.WriteLine(currentSpan.decodeErrors[i]);
}
}
const tsCodeLineMap = ts.computeLineStarts(sourceText);
for (let i = 0; i < tsCodeLineMap.length; i++) {
writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >");
sourceMapRecoder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
sourceMapRecorder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
if (i === tsCodeLineMap.length - 1) {
sourceMapRecoder.WriteLine("");
sourceMapRecorder.WriteLine("");
}
}
@@ -407,7 +407,7 @@ namespace Harness.SourceMapRecoder {
}
function writeSpanDetails(currentSpan: SourceMapSpanWithDecodeErrors, index: number) {
sourceMapRecoder.WriteLine(markerIds[index] + getSourceMapSpanString(currentSpan.sourceMapSpan));
sourceMapRecorder.WriteLine(markerIds[index] + getSourceMapSpanString(currentSpan.sourceMapSpan));
}
if (spansOnSingleLine.length) {
@@ -431,19 +431,19 @@ namespace Harness.SourceMapRecoder {
// Emit column number etc
iterateSpans(writeSpanDetails);
sourceMapRecoder.WriteLine("---");
sourceMapRecorder.WriteLine("---");
}
}
}
export function getSourceMapRecord(sourceMapDataList: ts.SourceMapData[], program: ts.Program, jsFiles: Compiler.GeneratedFile[]) {
const sourceMapRecoder = new Compiler.WriterAggregator();
const sourceMapRecorder = new Compiler.WriterAggregator();
for (let i = 0; i < sourceMapDataList.length; i++) {
const sourceMapData = sourceMapDataList[i];
let prevSourceFile: ts.SourceFile;
SourceMapSpanWriter.intializeSourceMapSpanWriter(sourceMapRecoder, sourceMapData, jsFiles[i]);
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData, jsFiles[i]);
for (let j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
const decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
const currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
@@ -457,7 +457,7 @@ namespace Harness.SourceMapRecoder {
}
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
return sourceMapRecoder.lines.join("\r\n");
sourceMapRecorder.Close();
return sourceMapRecorder.lines.join("\r\n");
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
class Test262BaselineRunner extends RunnerBase {
private static basePath = "internal/cases/test262";
+3998 -2942
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -1,3 +1,5 @@
/// <reference path="lib.dom.generated.d.ts" />
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}
+70
View File
@@ -0,0 +1,70 @@
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
+483
View File
@@ -0,0 +1,483 @@
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
big(): string;
/** Returns a <blink> HTML element */
blink(): string;
/** Returns a <b> HTML element */
bold(): string;
/** Returns a <tt> HTML element */
fixed(): string
/** Returns a <font> HTML element and sets the color attribute value */
fontcolor(color: string): string
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an <i> HTML element */
italics(): string;
/** Returns an <a> HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a <small> HTML element */
small(): string;
/** Returns a <strike> HTML element */
strike(): string;
/** Returns a <sub> HTML element */
sub(): string;
/** Returns a <sup> HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />
+12
View File
@@ -0,0 +1,12 @@
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;
+373
View File
@@ -0,0 +1,373 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface IteratorResult<T> {
done: boolean;
value?: T;
}
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface IterableIterator<T> extends Iterator<T> { }
interface Array<T> {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
interface Map<K, V> {
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
}
interface MapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
}
interface WeakMap<K, V> { }
interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Promise<T> { }
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject(reason: any): Promise<void>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;
+22
View File
@@ -0,0 +1,22 @@
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
deleteProperty? (target: T, p: PropertyKey): boolean;
defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;
+16
View File
@@ -0,0 +1,16 @@
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
+36
View File
@@ -0,0 +1,36 @@
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string|number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;
+356
View File
@@ -0,0 +1,356 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
interface Symbol {
readonly [Symbol.toStringTag]: "Symbol";
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
[Symbol.unscopables](): {
copyWithin: boolean;
entries: boolean;
fill: boolean;
find: boolean;
findIndex: boolean;
keys: boolean;
values: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
interface Promise<T> {
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
readonly [Symbol.species]: Function;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
[Symbol.species](): RegExpConstructor;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
readonly [Symbol.toStringTag]: "DataView";
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />
+232 -33
View File
@@ -215,14 +215,16 @@ interface Function {
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(thisArg: any, argArray?: any): any;
apply<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U;
apply(this: Function, thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(thisArg: any, ...argArray: any[]): any;
call<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): U;
call(this: Function, thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body as the original function.
@@ -230,7 +232,8 @@ interface Function {
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;
bind<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): (this: void, ...argArray: any[]) => U;
bind(this: Function, thisArg: any, ...argArray: any[]): any;
prototype: any;
readonly length: number;
@@ -304,13 +307,13 @@ interface String {
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
match(regexp: string): RegExpMatchArray;
match(regexp: string): RegExpMatchArray | null;
/**
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
*/
match(regexp: RegExp): RegExpMatchArray;
match(regexp: RegExp): RegExpMatchArray | null;
/**
* Replaces text in a string, using a regular expression or search string.
@@ -813,7 +816,7 @@ interface RegExp {
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/
exec(string: string): RegExpExecArray;
exec(string: string): RegExpExecArray | null;
/**
* Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
@@ -836,7 +839,7 @@ interface RegExp {
lastIndex: number;
// Non-standard extensions
compile(): RegExp;
compile(): this;
}
interface RegExpConstructor {
@@ -1108,17 +1111,12 @@ interface Array<T> {
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
pop(): T | undefined;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat<U extends T[]>(...items: U[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: T[]): T[];
concat(...items: (T | T[])[]): T[];
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
@@ -1131,7 +1129,7 @@ interface Array<T> {
/**
* Removes the first element from an array and returns it.
*/
shift(): T;
shift(): T | undefined;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
@@ -1524,7 +1522,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -1535,7 +1533,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -1797,7 +1795,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -1808,7 +1806,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -2071,7 +2069,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -2082,7 +2080,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -2344,7 +2342,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -2355,7 +2353,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -2618,7 +2616,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -2629,7 +2627,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -2891,7 +2889,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -2902,7 +2900,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -3164,7 +3162,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -3175,7 +3173,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -3437,7 +3435,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -3448,7 +3446,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -3711,7 +3709,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -3722,7 +3720,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@@ -3909,3 +3907,204 @@ interface Float64ArrayConstructor {
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
declare const Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}
-1333
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1 +0,0 @@
/// <reference path="lib.core.d.ts" />
+1
View File
@@ -0,0 +1 @@
/// <reference path="lib.es5.d.ts" />
-201
View File
@@ -1,201 +0,0 @@
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}
+265 -265
View File
@@ -13,10 +13,12 @@ interface EventListener {
}
interface AudioBuffer {
duration: number;
length: number;
numberOfChannels: number;
sampleRate: number;
readonly duration: number;
readonly length: number;
readonly numberOfChannels: number;
readonly sampleRate: number;
copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;
copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;
getChannelData(channel: number): Float32Array;
}
@@ -26,8 +28,8 @@ declare var AudioBuffer: {
}
interface Blob {
size: number;
type: string;
readonly size: number;
readonly type: string;
msClose(): void;
msDetachStream(): any;
slice(start?: number, end?: number, contentType?: string): Blob;
@@ -39,9 +41,9 @@ declare var Blob: {
}
interface CloseEvent extends Event {
code: number;
reason: string;
wasClean: boolean;
readonly code: number;
readonly reason: string;
readonly wasClean: boolean;
initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;
}
@@ -58,6 +60,7 @@ interface Console {
dir(value?: any, ...optionalParams: any[]): void;
dirxml(value: any): void;
error(message?: any, ...optionalParams: any[]): void;
exception(message?: string, ...optionalParams: any[]): void;
group(groupTitle?: string): void;
groupCollapsed(groupTitle?: string): void;
groupEnd(): void;
@@ -67,6 +70,7 @@ interface Console {
profile(reportName?: string): void;
profileEnd(): void;
select(element: any): void;
table(...data: any[]): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(message?: any, ...optionalParams: any[]): void;
@@ -79,13 +83,13 @@ declare var Console: {
}
interface Coordinates {
accuracy: number;
altitude: number;
altitudeAccuracy: number;
heading: number;
latitude: number;
longitude: number;
speed: number;
readonly accuracy: number;
readonly altitude: number;
readonly altitudeAccuracy: number;
readonly heading: number;
readonly latitude: number;
readonly longitude: number;
readonly speed: number;
}
declare var Coordinates: {
@@ -94,7 +98,7 @@ declare var Coordinates: {
}
interface DOMError {
name: string;
readonly name: string;
toString(): string;
}
@@ -104,73 +108,73 @@ declare var DOMError: {
}
interface DOMException {
code: number;
message: string;
name: string;
readonly code: number;
readonly message: string;
readonly name: string;
toString(): string;
ABORT_ERR: number;
DATA_CLONE_ERR: number;
DOMSTRING_SIZE_ERR: number;
HIERARCHY_REQUEST_ERR: number;
INDEX_SIZE_ERR: number;
INUSE_ATTRIBUTE_ERR: number;
INVALID_ACCESS_ERR: number;
INVALID_CHARACTER_ERR: number;
INVALID_MODIFICATION_ERR: number;
INVALID_NODE_TYPE_ERR: number;
INVALID_STATE_ERR: number;
NAMESPACE_ERR: number;
NETWORK_ERR: number;
NOT_FOUND_ERR: number;
NOT_SUPPORTED_ERR: number;
NO_DATA_ALLOWED_ERR: number;
NO_MODIFICATION_ALLOWED_ERR: number;
PARSE_ERR: number;
QUOTA_EXCEEDED_ERR: number;
SECURITY_ERR: number;
SERIALIZE_ERR: number;
SYNTAX_ERR: number;
TIMEOUT_ERR: number;
TYPE_MISMATCH_ERR: number;
URL_MISMATCH_ERR: number;
VALIDATION_ERR: number;
WRONG_DOCUMENT_ERR: number;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
declare var DOMException: {
prototype: DOMException;
new(): DOMException;
ABORT_ERR: number;
DATA_CLONE_ERR: number;
DOMSTRING_SIZE_ERR: number;
HIERARCHY_REQUEST_ERR: number;
INDEX_SIZE_ERR: number;
INUSE_ATTRIBUTE_ERR: number;
INVALID_ACCESS_ERR: number;
INVALID_CHARACTER_ERR: number;
INVALID_MODIFICATION_ERR: number;
INVALID_NODE_TYPE_ERR: number;
INVALID_STATE_ERR: number;
NAMESPACE_ERR: number;
NETWORK_ERR: number;
NOT_FOUND_ERR: number;
NOT_SUPPORTED_ERR: number;
NO_DATA_ALLOWED_ERR: number;
NO_MODIFICATION_ALLOWED_ERR: number;
PARSE_ERR: number;
QUOTA_EXCEEDED_ERR: number;
SECURITY_ERR: number;
SERIALIZE_ERR: number;
SYNTAX_ERR: number;
TIMEOUT_ERR: number;
TYPE_MISMATCH_ERR: number;
URL_MISMATCH_ERR: number;
VALIDATION_ERR: number;
WRONG_DOCUMENT_ERR: number;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
interface DOMStringList {
length: number;
readonly length: number;
contains(str: string): boolean;
item(index: number): string;
[index: number]: string;
@@ -182,11 +186,11 @@ declare var DOMStringList: {
}
interface ErrorEvent extends Event {
colno: number;
error: any;
filename: string;
lineno: number;
message: string;
readonly colno: number;
readonly error: any;
readonly filename: string;
readonly lineno: number;
readonly message: string;
initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;
}
@@ -196,39 +200,39 @@ declare var ErrorEvent: {
}
interface Event {
bubbles: boolean;
readonly bubbles: boolean;
cancelBubble: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
readonly cancelable: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
readonly isTrusted: boolean;
returnValue: boolean;
srcElement: any;
target: EventTarget;
timeStamp: number;
type: string;
readonly srcElement: any;
readonly target: EventTarget;
readonly timeStamp: number;
readonly type: string;
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
declare var Event: {
prototype: Event;
new(type: string, eventInitDict?: EventInit): Event;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
interface EventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var EventTarget: {
@@ -237,8 +241,9 @@ declare var EventTarget: {
}
interface File extends Blob {
lastModifiedDate: any;
name: string;
readonly lastModifiedDate: any;
readonly name: string;
readonly webkitRelativePath: string;
}
declare var File: {
@@ -247,7 +252,7 @@ declare var File: {
}
interface FileList {
length: number;
readonly length: number;
item(index: number): File;
[index: number]: File;
}
@@ -258,7 +263,7 @@ declare var FileList: {
}
interface FileReader extends EventTarget, MSBaseReader {
error: DOMError;
readonly error: DOMError;
readAsArrayBuffer(blob: Blob): void;
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): void;
@@ -272,31 +277,31 @@ declare var FileReader: {
}
interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
readonly direction: string;
key: IDBKeyRange | IDBValidKey;
readonly primaryKey: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
continue(key?: IDBKeyRange | IDBValidKey): void;
delete(): IDBRequest;
update(value: any): IDBRequest;
NEXT: string;
NEXT_NO_DUPLICATE: string;
PREV: string;
PREV_NO_DUPLICATE: string;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
declare var IDBCursor: {
prototype: IDBCursor;
new(): IDBCursor;
NEXT: string;
NEXT_NO_DUPLICATE: string;
PREV: string;
PREV_NO_DUPLICATE: string;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
interface IDBCursorWithValue extends IDBCursor {
value: any;
readonly value: any;
}
declare var IDBCursorWithValue: {
@@ -305,15 +310,17 @@ declare var IDBCursorWithValue: {
}
interface IDBDatabase extends EventTarget {
name: string;
objectStoreNames: DOMStringList;
readonly name: string;
readonly objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: number;
onversionchange: (ev: IDBVersionChangeEvent) => any;
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -337,15 +344,15 @@ declare var IDBFactory: {
interface IDBIndex {
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
readonly name: string;
readonly objectStore: IDBObjectStore;
readonly unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
openCursor(range?: IDBKeyRange, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
get(key: IDBKeyRange | IDBValidKey): IDBRequest;
getKey(key: IDBKeyRange | IDBValidKey): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
}
declare var IDBIndex: {
@@ -354,37 +361,37 @@ declare var IDBIndex: {
}
interface IDBKeyRange {
lower: any;
lowerOpen: boolean;
upper: any;
upperOpen: boolean;
readonly lower: any;
readonly lowerOpen: boolean;
readonly upper: any;
readonly upperOpen: boolean;
}
declare var IDBKeyRange: {
prototype: IDBKeyRange;
new(): IDBKeyRange;
bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;
lowerBound(bound: any, open?: boolean): IDBKeyRange;
lowerBound(lower: any, open?: boolean): IDBKeyRange;
only(value: any): IDBKeyRange;
upperBound(bound: any, open?: boolean): IDBKeyRange;
upperBound(upper: any, open?: boolean): IDBKeyRange;
}
interface IDBObjectStore {
indexNames: DOMStringList;
readonly indexNames: DOMStringList;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
readonly name: string;
readonly transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
delete(key: IDBKeyRange | IDBValidKey): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
index(name: string): IDBIndex;
openCursor(range?: any, direction?: string): IDBRequest;
put(value: any, key?: any): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
}
declare var IDBObjectStore: {
@@ -408,13 +415,13 @@ declare var IDBOpenDBRequest: {
}
interface IDBRequest extends EventTarget {
error: DOMError;
readonly error: DOMError;
onerror: (ev: Event) => any;
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
readonly readyState: string;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
readonly transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -426,17 +433,17 @@ declare var IDBRequest: {
}
interface IDBTransaction extends EventTarget {
db: IDBDatabase;
error: DOMError;
mode: string;
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
onabort: (ev: Event) => any;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
abort(): void;
objectStore(name: string): IDBObjectStore;
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
@@ -446,14 +453,14 @@ interface IDBTransaction extends EventTarget {
declare var IDBTransaction: {
prototype: IDBTransaction;
new(): IDBTransaction;
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
}
interface IDBVersionChangeEvent extends Event {
newVersion: number;
oldVersion: number;
readonly newVersion: number;
readonly oldVersion: number;
}
declare var IDBVersionChangeEvent: {
@@ -463,8 +470,8 @@ declare var IDBVersionChangeEvent: {
interface ImageData {
data: Uint8ClampedArray;
height: number;
width: number;
readonly height: number;
readonly width: number;
}
declare var ImageData: {
@@ -483,29 +490,29 @@ interface MSApp {
execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void;
execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any;
getCurrentPriority(): string;
getHtmlPrintDocumentSourceAsync(htmlDoc: any): any;
getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike<any>;
getViewId(view: any): any;
isTaskScheduledAtPriorityOrHigher(priority: string): boolean;
pageHandlesAllApplicationActivations(enabled: boolean): void;
suppressSubdownloadCredentialPrompts(suppress: boolean): void;
terminateApp(exceptionObject: any): void;
CURRENT: string;
HIGH: string;
IDLE: string;
NORMAL: string;
readonly CURRENT: string;
readonly HIGH: string;
readonly IDLE: string;
readonly NORMAL: string;
}
declare var MSApp: MSApp;
interface MSAppAsyncOperation extends EventTarget {
error: DOMError;
readonly error: DOMError;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
readyState: number;
result: any;
readonly readyState: number;
readonly result: any;
start(): void;
COMPLETED: number;
ERROR: number;
STARTED: number;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -514,9 +521,9 @@ interface MSAppAsyncOperation extends EventTarget {
declare var MSAppAsyncOperation: {
prototype: MSAppAsyncOperation;
new(): MSAppAsyncOperation;
COMPLETED: number;
ERROR: number;
STARTED: number;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
}
interface MSBlobBuilder {
@@ -530,7 +537,7 @@ declare var MSBlobBuilder: {
}
interface MSStream {
type: string;
readonly type: string;
msClose(): void;
msDetachStream(): any;
}
@@ -541,7 +548,7 @@ declare var MSStream: {
}
interface MSStreamReader extends EventTarget, MSBaseReader {
error: DOMError;
readonly error: DOMError;
readAsArrayBuffer(stream: MSStream, size?: number): void;
readAsBinaryString(stream: MSStream, size?: number): void;
readAsBlob(stream: MSStream, size?: number): void;
@@ -556,8 +563,8 @@ declare var MSStreamReader: {
}
interface MediaQueryList {
matches: boolean;
media: string;
readonly matches: boolean;
readonly media: string;
addListener(listener: MediaQueryListListener): void;
removeListener(listener: MediaQueryListListener): void;
}
@@ -568,8 +575,8 @@ declare var MediaQueryList: {
}
interface MessageChannel {
port1: MessagePort;
port2: MessagePort;
readonly port1: MessagePort;
readonly port2: MessagePort;
}
declare var MessageChannel: {
@@ -578,10 +585,10 @@ declare var MessageChannel: {
}
interface MessageEvent extends Event {
data: any;
origin: string;
ports: any;
source: any;
readonly data: any;
readonly origin: string;
readonly ports: any;
readonly source: any;
initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void;
}
@@ -605,8 +612,8 @@ declare var MessagePort: {
}
interface Position {
coords: Coordinates;
timestamp: number;
readonly coords: Coordinates;
readonly timestamp: number;
}
declare var Position: {
@@ -615,26 +622,26 @@ declare var Position: {
}
interface PositionError {
code: number;
message: string;
readonly code: number;
readonly message: string;
toString(): string;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
declare var PositionError: {
prototype: PositionError;
new(): PositionError;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
interface ProgressEvent extends Event {
lengthComputable: boolean;
loaded: number;
total: number;
readonly lengthComputable: boolean;
readonly loaded: number;
readonly total: number;
initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void;
}
@@ -645,21 +652,21 @@ declare var ProgressEvent: {
interface WebSocket extends EventTarget {
binaryType: string;
bufferedAmount: number;
extensions: string;
readonly bufferedAmount: number;
readonly extensions: string;
onclose: (ev: CloseEvent) => any;
onerror: (ev: Event) => any;
onmessage: (ev: MessageEvent) => any;
onopen: (ev: Event) => any;
protocol: string;
readyState: number;
url: string;
readonly protocol: string;
readonly readyState: number;
readonly url: string;
close(code?: number, reason?: string): void;
send(data: any): void;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
OPEN: number;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
@@ -670,10 +677,10 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
OPEN: number;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
}
interface Worker extends EventTarget, AbstractWorker {
@@ -693,16 +700,15 @@ declare var Worker: {
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
msCaching: string;
onreadystatechange: (ev: ProgressEvent) => any;
readyState: number;
response: any;
responseBody: any;
responseText: string;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
responseType: string;
responseXML: any;
status: number;
statusText: string;
readonly responseXML: any;
readonly status: number;
readonly statusText: string;
timeout: number;
upload: XMLHttpRequestUpload;
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
abort(): void;
getAllResponseHeaders(): string;
@@ -713,11 +719,11 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
send(data?: string): void;
send(data?: any): void;
setRequestHeader(header: string, value: string): void;
DONE: number;
HEADERS_RECEIVED: number;
LOADING: number;
OPENED: number;
UNSENT: number;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -732,11 +738,11 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
declare var XMLHttpRequest: {
prototype: XMLHttpRequest;
new(): XMLHttpRequest;
DONE: number;
HEADERS_RECEIVED: number;
LOADING: number;
OPENED: number;
UNSENT: number;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
create(): XMLHttpRequest;
}
@@ -762,12 +768,12 @@ interface MSBaseReader {
onloadend: (ev: ProgressEvent) => any;
onloadstart: (ev: Event) => any;
onprogress: (ev: ProgressEvent) => any;
readyState: number;
result: any;
readonly readyState: number;
readonly result: any;
abort(): void;
DONE: number;
EMPTY: number;
LOADING: number;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: number;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -778,18 +784,18 @@ interface MSBaseReader {
}
interface NavigatorID {
appName: string;
appVersion: string;
platform: string;
product: string;
productSub: string;
userAgent: string;
vendor: string;
vendorSub: string;
readonly appName: string;
readonly appVersion: string;
readonly platform: string;
readonly product: string;
readonly productSub: string;
readonly userAgent: string;
readonly vendor: string;
readonly vendorSub: string;
}
interface NavigatorOnLine {
onLine: boolean;
readonly onLine: boolean;
}
interface WindowBase64 {
@@ -798,7 +804,7 @@ interface WindowBase64 {
}
interface WindowConsole {
console: Console;
readonly console: Console;
}
interface XMLHttpRequestEventTarget {
@@ -832,9 +838,9 @@ declare var FileReaderSync: {
}
interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole {
location: WorkerLocation;
readonly location: WorkerLocation;
onerror: (ev: Event) => any;
self: WorkerGlobalScope;
readonly self: WorkerGlobalScope;
close(): void;
msWriteProfilerMark(profilerMarkName: string): void;
toString(): string;
@@ -849,14 +855,14 @@ declare var WorkerGlobalScope: {
}
interface WorkerLocation {
hash: string;
host: string;
hostname: string;
href: string;
pathname: string;
port: string;
protocol: string;
search: string;
readonly hash: string;
readonly host: string;
readonly hostname: string;
readonly href: string;
readonly pathname: string;
readonly port: string;
readonly protocol: string;
readonly search: string;
toString(): string;
}
@@ -882,9 +888,9 @@ interface DedicatedWorkerGlobalScope {
}
interface WorkerUtils extends Object, WindowBase64 {
indexedDB: IDBFactory;
msIndexedDB: IDBFactory;
navigator: WorkerNavigator;
readonly indexedDB: IDBFactory;
readonly msIndexedDB: IDBFactory;
readonly navigator: WorkerNavigator;
clearImmediate(handle: number): void;
clearInterval(handle: number): void;
clearTimeout(handle: number): void;
@@ -894,16 +900,6 @@ interface WorkerUtils extends Object, WindowBase64 {
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
@@ -933,6 +929,9 @@ interface ProgressEventInit extends EventInit {
total?: number;
}
interface IDBArrayKey extends Array<IDBValidKey> {
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@@ -971,9 +970,9 @@ declare var self: WorkerGlobalScope;
declare function close(): void;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function toString(): string;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare var indexedDB: IDBFactory;
declare var msIndexedDB: IDBFactory;
declare var navigator: WorkerNavigator;
@@ -991,4 +990,5 @@ declare function postMessage(data: any): void;
declare var console: Console;
declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type IDBValidKey = number | string | Date | IDBArrayKey;
+7 -3
View File
@@ -83,7 +83,7 @@ namespace ts.server {
private processResponse<T extends protocol.Response>(request: protocol.Request): T {
var lastMessage = this.messages.shift();
Debug.assert(!!lastMessage, "Did not recieve any responses.");
Debug.assert(!!lastMessage, "Did not receive any responses.");
// Read the content length
var contentLengthPrefix = "Content-Length: ";
@@ -108,7 +108,7 @@ namespace ts.server {
}
// verify the sequence numbers
Debug.assert(response.request_seq === request.seq, "Malformed response: response sequance number did not match request sequence number.");
Debug.assert(response.request_seq === request.seq, "Malformed response: response sequence number did not match request sequence number.");
// unmarshal errors
if (!response.success) {
@@ -568,6 +568,10 @@ namespace ts.server {
throw new Error("Not Implemented Yet.");
}
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
throw new Error("Not Implemented Yet.");
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
@@ -613,7 +617,7 @@ namespace ts.server {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
getSourceFile(fileName: string): SourceFile {
getNonBoundSourceFile(fileName: string): SourceFile {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
+50 -24
View File
@@ -81,8 +81,14 @@ namespace ts.server {
}
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations {
lastCheckTime: number;
interface Timestamped {
lastCheckTime?: number;
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations, Timestamped {
}
interface TimestampedResolvedTypeReferenceDirective extends ResolvedTypeReferenceDirectiveWithFailedLookupLocations, Timestamped {
}
export class LSHost implements ts.LanguageServiceHost {
@@ -90,13 +96,16 @@ namespace ts.server {
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.FileMap<ScriptInfo>;
roots: ScriptInfo[] = [];
private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>;
private resolvedTypeReferenceDirectives: ts.FileMap<Map<TimestampedResolvedTypeReferenceDirective>>;
private moduleResolutionHost: ts.ModuleResolutionHost;
private getCanonicalFileName: (fileName: string) => string;
constructor(public host: ServerHost, public project: Project) {
this.getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
this.resolvedModuleNames = createFileMap<Map<TimestampedResolvedModule>>();
this.resolvedTypeReferenceDirectives = createFileMap<Map<TimestampedResolvedTypeReferenceDirective>>();
this.filenameToScript = createFileMap<ScriptInfo>();
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
@@ -105,46 +114,51 @@ namespace ts.server {
};
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
private resolveNamesWithLocalCache<T extends Timestamped & { failedLookupLocations: string[] }, R>(
names: string[],
containingFile: string,
cache: ts.FileMap<Map<T>>,
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T,
getResult: (s: T) => R): R[] {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = this.resolvedModuleNames.get(path);
const newResolutions: Map<TimestampedResolvedModule> = {};
const resolvedModules: ResolvedModule[] = [];
const currentResolutionsInFile = cache.get(path);
const newResolutions: Map<T> = {};
const resolvedModules: R[] = [];
const compilerOptions = this.getCompilationSettings();
for (const moduleName of moduleNames) {
for (const name of names) {
// check if this is a duplicate entry in the list
let resolution = lookUp(newResolutions, moduleName);
let resolution = lookUp(newResolutions, name);
if (!resolution) {
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
// ok, it is safe to use existing name resolution results
resolution = existingResolution;
}
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution = loader(name, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
newResolutions[name] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedModules.push(resolution.resolvedModule);
resolvedModules.push(getResult(resolution));
}
// replace old results with a new one
this.resolvedModuleNames.set(path, newResolutions);
cache.set(path, newResolutions);
return resolvedModules;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
function moduleResolutionIsValid(resolution: T): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedModule) {
if (getResult(resolution)) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
@@ -156,6 +170,14 @@ namespace ts.server {
}
}
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective, m => m.resolvedTypeReferenceDirective);
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, resolveModuleName, m => m.resolvedModule);
}
getDefaultLibFileName() {
const nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
@@ -172,6 +194,7 @@ namespace ts.server {
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
this.resolvedTypeReferenceDirectives.clear();
}
lineAffectsRefs(filename: string, line: number) {
@@ -192,6 +215,10 @@ namespace ts.server {
return this.roots.map(root => root.fileName);
}
getScriptKind() {
return ScriptKind.Unknown;
}
getScriptVersion(filename: string) {
return this.getScriptInfo(filename).svc.latestVersion().toString();
}
@@ -208,6 +235,7 @@ namespace ts.server {
if (!info.isOpen) {
this.filenameToScript.remove(info.path);
this.resolvedModuleNames.remove(info.path);
this.resolvedTypeReferenceDirectives.remove(info.path);
}
}
@@ -235,6 +263,7 @@ namespace ts.server {
this.filenameToScript.remove(info.path);
this.roots = copyListRemovingItem(info, this.roots);
this.resolvedModuleNames.remove(info.path);
this.resolvedTypeReferenceDirectives.remove(info.path);
}
}
@@ -1002,9 +1031,7 @@ namespace ts.server {
info.setFormatOptions(this.getFormatCodeOptions());
this.filenameToScriptInfo[fileName] = info;
if (!info.isOpen) {
info.fileWatcher = this.host.watchFile(
toPath(fileName, fileName, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
_ => { this.watchedFileChanged(fileName); });
info.fileWatcher = this.host.watchFile(fileName, _ => { this.watchedFileChanged(fileName); });
}
}
}
@@ -1223,9 +1250,7 @@ namespace ts.server {
}
}
project.finishGraph();
project.projectFileWatcher = this.host.watchFile(
toPath(configFilename, configFilename, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
_ => this.watchedProjectConfigFileChanged(project));
project.projectFileWatcher = this.host.watchFile(configFilename, _ => this.watchedProjectConfigFileChanged(project));
this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename));
project.directoryWatcher = this.host.watchDirectory(
ts.getDirectoryPath(configFilename),
@@ -1313,6 +1338,7 @@ namespace ts.server {
else {
const defaultOpts = ts.getDefaultCompilerOptions();
defaultOpts.allowNonTsExtensions = true;
defaultOpts.allowJs = true;
this.setCompilerOptions(defaultOpts);
}
this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
@@ -1325,7 +1351,7 @@ namespace ts.server {
}
isExternalModule(filename: string): boolean {
const sourceFile = this.languageService.getSourceFile(filename);
const sourceFile = this.languageService.getNonBoundSourceFile(filename);
return ts.isExternalModule(sourceFile);
}

Some files were not shown because too many files have changed in this diff Show More