mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge branch 'master' into umd_export
This commit is contained in:
@@ -9,12 +9,14 @@ test-args.txt
|
||||
\#*\#
|
||||
.\#*
|
||||
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/authors.js
|
||||
|
||||
+27
-3
@@ -7,9 +7,33 @@ node_js:
|
||||
|
||||
sudo: false
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
env:
|
||||
- workerCount=3
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
include:
|
||||
- os: osx
|
||||
node_js: stable
|
||||
osx_image: xcode7.3
|
||||
env: workerCount=2
|
||||
allow_failures:
|
||||
- os: osx
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- release.2.0
|
||||
|
||||
install:
|
||||
- npm uninstall typescript
|
||||
- npm uninstall tslint
|
||||
- npm install
|
||||
- npm update
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- node_modules
|
||||
|
||||
git:
|
||||
depth: 1
|
||||
|
||||
+140
-130
@@ -17,7 +17,7 @@ declare module "gulp-typescript" {
|
||||
stripInternal?: boolean;
|
||||
types?: string[];
|
||||
}
|
||||
interface CompileStream extends NodeJS.ReadWriteStream {} // Either gulp or gulp-typescript has some odd typings which don't reflect reality, making this required
|
||||
interface CompileStream extends NodeJS.ReadWriteStream { } // Either gulp or gulp-typescript has some odd typings which don't reflect reality, making this required
|
||||
}
|
||||
import * as insert from "gulp-insert";
|
||||
import * as sourcemaps from "gulp-sourcemaps";
|
||||
@@ -34,11 +34,13 @@ import through2 = require("through2");
|
||||
import merge2 = require("merge2");
|
||||
import intoStream = require("into-stream");
|
||||
import * as os from "os";
|
||||
import Linter = require("tslint");
|
||||
import fold = require("travis-fold");
|
||||
const gulp = helpMaker(originalGulp);
|
||||
const mochaParallel = require("./scripts/mocha-parallel.js");
|
||||
const {runTestsInParallel} = mochaParallel;
|
||||
|
||||
Error.stackTraceLimit = 1000;
|
||||
|
||||
const cmdLineOptions = minimist(process.argv.slice(2), {
|
||||
boolean: ["debug", "light", "colors", "lint", "soft"],
|
||||
string: ["browser", "tests", "host", "reporter"],
|
||||
@@ -59,14 +61,13 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
|
||||
browser: process.env.browser || process.env.b || "IE",
|
||||
tests: process.env.test || process.env.tests || process.env.t,
|
||||
light: process.env.light || false,
|
||||
port: process.env.port || process.env.p || "8888",
|
||||
reporter: process.env.reporter || process.env.r,
|
||||
lint: process.env.lint || true,
|
||||
files: process.env.f || process.env.file || process.env.files || "",
|
||||
}
|
||||
});
|
||||
|
||||
function exec(cmd: string, args: string[], complete: () => void = (() => {}), error: (e: any, status: number) => void = (() => {})) {
|
||||
function exec(cmd: string, args: string[], complete: () => void = (() => { }), error: (e: any, status: number) => void = (() => { })) {
|
||||
console.log(`${cmd} ${args.join(" ")}`);
|
||||
// TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition
|
||||
const subshellFlag = isWin ? "/c" : "-c";
|
||||
@@ -117,12 +118,12 @@ const es2015LibrarySources = [
|
||||
];
|
||||
|
||||
const es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
|
||||
return { target: "lib." + source, sources: ["header.d.ts", source] };
|
||||
return { target: "lib." + source, sources: ["header.d.ts", source] };
|
||||
});
|
||||
|
||||
const es2016LibrarySource = [ "es2016.array.include.d.ts" ];
|
||||
const es2016LibrarySource = ["es2016.array.include.d.ts"];
|
||||
|
||||
const es2016LibrarySourceMap = es2016LibrarySource.map(function (source) {
|
||||
const es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
|
||||
return { target: "lib." + source, sources: ["header.d.ts", source] };
|
||||
});
|
||||
|
||||
@@ -131,38 +132,38 @@ const es2017LibrarySource = [
|
||||
"es2017.sharedmemory.d.ts"
|
||||
];
|
||||
|
||||
const es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
|
||||
const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) {
|
||||
return { target: "lib." + source, sources: ["header.d.ts", source] };
|
||||
});
|
||||
|
||||
const hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"];
|
||||
|
||||
const 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"] },
|
||||
// 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"] },
|
||||
{ target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.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"] },
|
||||
{ target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.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, "dom.iterable.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, "dom.iterable.d.ts") }
|
||||
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap);
|
||||
|
||||
const libraryTargets = librarySourceMap.map(function (f) {
|
||||
const libraryTargets = librarySourceMap.map(function(f) {
|
||||
return path.join(builtLocalDirectory, f.target);
|
||||
});
|
||||
|
||||
for (const i in libraryTargets) {
|
||||
const entry = librarySourceMap[i];
|
||||
const target = libraryTargets[i];
|
||||
const sources = [copyright].concat(entry.sources.map(function (s) {
|
||||
const sources = [copyright].concat(entry.sources.map(function(s) {
|
||||
return path.join(libraryDirectory, s);
|
||||
}));
|
||||
gulp.task(target, false, [], function() {
|
||||
@@ -392,7 +393,7 @@ gulp.task(servicesFile, false, ["lib", "generate-diagnostics"], () => {
|
||||
.pipe(sourcemaps.init())
|
||||
.pipe(tsc(servicesProject));
|
||||
const completedJs = js.pipe(prependCopyright())
|
||||
.pipe(sourcemaps.write("."));
|
||||
.pipe(sourcemaps.write("."));
|
||||
const completedDts = dts.pipe(prependCopyright(/*outputCopyright*/true))
|
||||
.pipe(insert.transform((contents, file) => {
|
||||
file.path = standaloneDefinitionsFile;
|
||||
@@ -435,22 +436,22 @@ const tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverli
|
||||
|
||||
gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => {
|
||||
const serverLibraryProject = tsc.createProject("src/server/tsconfig.library.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
|
||||
const {js, dts}: {js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream} = serverLibraryProject.src()
|
||||
const {js, dts}: { js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream } = serverLibraryProject.src()
|
||||
.pipe(sourcemaps.init())
|
||||
.pipe(newer(tsserverLibraryFile))
|
||||
.pipe(tsc(serverLibraryProject));
|
||||
|
||||
return merge2([
|
||||
js.pipe(prependCopyright())
|
||||
.pipe(sourcemaps.write("."))
|
||||
.pipe(gulp.dest(builtLocalDirectory)),
|
||||
.pipe(sourcemaps.write("."))
|
||||
.pipe(gulp.dest(builtLocalDirectory)),
|
||||
dts.pipe(prependCopyright())
|
||||
.pipe(gulp.dest(builtLocalDirectory))
|
||||
.pipe(gulp.dest(builtLocalDirectory))
|
||||
]);
|
||||
});
|
||||
|
||||
gulp.task("lssl", "Builds language service server library", [tsserverLibraryFile]);
|
||||
gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON]);
|
||||
gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON, tsserverLibraryFile]);
|
||||
gulp.task("tsc", "Builds only the compiler", [builtLocalCompiler]);
|
||||
|
||||
|
||||
@@ -477,7 +478,7 @@ gulp.task(specMd, false, [word2mdJs], (done) => {
|
||||
const specMDFullPath = path.resolve(specMd);
|
||||
const cmd = "cscript //nologo " + word2mdJs + " \"" + specWordFullPath + "\" " + "\"" + specMDFullPath + "\"";
|
||||
console.log(cmd);
|
||||
cp.exec(cmd, function () {
|
||||
cp.exec(cmd, function() {
|
||||
done();
|
||||
});
|
||||
});
|
||||
@@ -493,18 +494,18 @@ gulp.task("dontUseDebugMode", false, [], (done) => { useDebugMode = false; done(
|
||||
|
||||
gulp.task("VerifyLKG", false, [], () => {
|
||||
const expectedFiles = [builtLocalCompiler, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets);
|
||||
const missingFiles = expectedFiles.filter(function (f) {
|
||||
const missingFiles = expectedFiles.filter(function(f) {
|
||||
return !fs.existsSync(f);
|
||||
});
|
||||
if (missingFiles.length > 0) {
|
||||
throw new Error("Cannot replace the LKG unless all built targets are present in directory " + builtLocalDirectory +
|
||||
". The following files are missing:\n" + missingFiles.join("\n"));
|
||||
". The following files are missing:\n" + missingFiles.join("\n"));
|
||||
}
|
||||
// Copy all the targets into the LKG directory
|
||||
return gulp.src(expectedFiles).pipe(gulp.dest(LKGDirectory));
|
||||
});
|
||||
|
||||
gulp.task("LKGInternal", false, ["lib", "local", "lssl"]);
|
||||
gulp.task("LKGInternal", false, ["lib", "local"]);
|
||||
|
||||
gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUseDebugMode"], () => {
|
||||
return runSequence("LKGInternal", "VerifyLKG");
|
||||
@@ -532,8 +533,6 @@ const localRwcBaseline = path.join(internalTests, "baselines/rwc/local");
|
||||
const refRwcBaseline = path.join(internalTests, "baselines/rwc/reference");
|
||||
|
||||
const localTest262Baseline = path.join(internalTests, "baselines/test262/local");
|
||||
const refTest262Baseline = path.join(internalTests, "baselines/test262/reference");
|
||||
|
||||
|
||||
gulp.task("tests", "Builds the test infrastructure using the built compiler", [run]);
|
||||
gulp.task("tests-debug", "Builds the test sources and automation in debug mode", () => {
|
||||
@@ -554,7 +553,7 @@ function restoreSavedNodeEnv() {
|
||||
process.env.NODE_ENV = savedNodeEnv;
|
||||
}
|
||||
|
||||
let testTimeout = 20000;
|
||||
let testTimeout = 40000;
|
||||
function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: (e?: any) => void) {
|
||||
const lintFlag = cmdLineOptions["lint"];
|
||||
cleanTestDirs((err) => {
|
||||
@@ -628,7 +627,7 @@ function runConsoleTests(defaultReporter: string, runInParallel: boolean, done:
|
||||
}
|
||||
args.push(run);
|
||||
setNodeEnvToDevelopment();
|
||||
runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function (err) {
|
||||
runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function(err) {
|
||||
// last worker clean everything and runs linter in case if there were no errors
|
||||
del(taskConfigsFolder).then(() => {
|
||||
if (!err) {
|
||||
@@ -680,7 +679,7 @@ gulp.task("runtests",
|
||||
["build-rules", "tests"],
|
||||
(done) => {
|
||||
runConsoleTests("mocha-fivemat-progress-reporter", /*runInParallel*/ false, done);
|
||||
});
|
||||
});
|
||||
|
||||
const nodeServerOutFile = "tests/webTestServer.js";
|
||||
const nodeServerInFile = "tests/webTestServer.ts";
|
||||
@@ -710,7 +709,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo
|
||||
const originalMap = file.sourceMap;
|
||||
const prebundledContent = file.contents.toString();
|
||||
// Make paths absolute to help sorcery deal with all the terrible paths being thrown around
|
||||
originalMap.sources = originalMap.sources.map(s => path.resolve(s));
|
||||
originalMap.sources = originalMap.sources.map(s => path.resolve("src", s));
|
||||
// intoStream (below) makes browserify think the input file is named this, so this is what it puts in the sourcemap
|
||||
originalMap.file = "built/local/_stream_0.js";
|
||||
|
||||
@@ -730,6 +729,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo
|
||||
sourcemaps: {
|
||||
"built/local/_stream_0.js": originalMap,
|
||||
"built/local/bundle.js": maps,
|
||||
"node_modules/source-map-support/source-map-support.js": undefined,
|
||||
}
|
||||
});
|
||||
const finalMap = chain.apply();
|
||||
@@ -766,7 +766,7 @@ function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?:
|
||||
}
|
||||
|
||||
|
||||
gulp.task("runtests-browser", "Runs the tests using the built run.js file like 'gulp runtests'. Syntax is gulp runtests-browser. Additional optional parameters --tests=[regex], --port=, --browser=[chrome|IE]", ["browserify", nodeServerOutFile], (done) => {
|
||||
gulp.task("runtests-browser", "Runs the tests using the built run.js file like 'gulp runtests'. Syntax is gulp runtests-browser. Additional optional parameters --tests=[regex], --browser=[chrome|IE]", ["browserify", nodeServerOutFile], (done) => {
|
||||
cleanTestDirs((err) => {
|
||||
if (err) { console.error(err); done(err); process.exit(1); }
|
||||
host = "node";
|
||||
@@ -781,9 +781,6 @@ gulp.task("runtests-browser", "Runs the tests using the built run.js file like '
|
||||
}
|
||||
|
||||
const args = [nodeServerOutFile];
|
||||
if (cmdLineOptions["port"]) {
|
||||
args.push(cmdLineOptions["port"]);
|
||||
}
|
||||
if (cmdLineOptions["browser"]) {
|
||||
args.push(cmdLineOptions["browser"]);
|
||||
}
|
||||
@@ -815,32 +812,36 @@ gulp.task("diff-rwc", "Diffs the RWC baselines using the diff tool specified by
|
||||
exec(getDiffTool(), [refRwcBaseline, localRwcBaseline], done, done);
|
||||
});
|
||||
|
||||
gulp.task("baseline-accept", "Makes the most recent test results the new baseline, overwriting the old baseline", () => {
|
||||
return baselineAccept("");
|
||||
});
|
||||
|
||||
function baselineAccept(subfolder = "") {
|
||||
return merge2(baselineCopy(subfolder), baselineDelete(subfolder));
|
||||
}
|
||||
|
||||
function baselineCopy(subfolder = "") {
|
||||
return gulp.src([`tests/baselines/local/${subfolder}/**`, `!tests/baselines/local/${subfolder}/**/*.delete`])
|
||||
.pipe(gulp.dest(refBaseline));
|
||||
}
|
||||
|
||||
function baselineDelete(subfolder = "") {
|
||||
return gulp.src(["tests/baselines/local/**/*.delete"])
|
||||
.pipe(insert.transform((content, fileObj) => {
|
||||
const target = path.join(refBaseline, fileObj.relative.substr(0, fileObj.relative.length - ".delete".length));
|
||||
del.sync(target);
|
||||
del.sync(fileObj.path);
|
||||
return "";
|
||||
}));
|
||||
}
|
||||
|
||||
gulp.task("baseline-accept", "Makes the most recent test results the new baseline, overwriting the old baseline", (done) => {
|
||||
const softAccept = cmdLineOptions["soft"];
|
||||
if (!softAccept) {
|
||||
del(refBaseline).then(() => {
|
||||
fs.renameSync(localBaseline, refBaseline);
|
||||
done();
|
||||
}, done);
|
||||
}
|
||||
else {
|
||||
gulp.src(localBaseline)
|
||||
.pipe(gulp.dest(refBaseline))
|
||||
.on("end", () => {
|
||||
del(path.join(refBaseline, "local")).then(() => done(), done);
|
||||
});
|
||||
}
|
||||
});
|
||||
gulp.task("baseline-accept-rwc", "Makes the most recent rwc test results the new baseline, overwriting the old baseline", () => {
|
||||
return del(refRwcBaseline).then(() => {
|
||||
fs.renameSync(localRwcBaseline, refRwcBaseline);
|
||||
});
|
||||
return baselineAccept("rwc");
|
||||
});
|
||||
|
||||
|
||||
gulp.task("baseline-accept-test262", "Makes the most recent test262 test results the new baseline, overwriting the old baseline", () => {
|
||||
return del(refTest262Baseline).then(() => {
|
||||
fs.renameSync(localTest262Baseline, refTest262Baseline);
|
||||
});
|
||||
return baselineAccept("test262");
|
||||
});
|
||||
|
||||
|
||||
@@ -918,56 +919,19 @@ gulp.task("update-sublime", "Updates the sublime plugin's tsserver", ["local", s
|
||||
return gulp.src([serverFile, serverFile + ".map"]).pipe(gulp.dest("../TypeScript-Sublime-Plugin/tsserver/"));
|
||||
});
|
||||
|
||||
|
||||
const tslintRuleDir = "scripts/tslint";
|
||||
const tslintRules = [
|
||||
"nextLineRule",
|
||||
"preferConstRule",
|
||||
"booleanTriviaRule",
|
||||
"typeOperatorSpacingRule",
|
||||
"noInOperatorRule",
|
||||
"noIncrementDecrementRule",
|
||||
"objectLiteralSurroundingSpaceRule",
|
||||
];
|
||||
const tslintRulesFiles = tslintRules.map(function(p) {
|
||||
return path.join(tslintRuleDir, p + ".ts");
|
||||
gulp.task("build-rules", "Compiles tslint rules to js", () => {
|
||||
const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ false);
|
||||
const dest = path.join(builtLocalDirectory, "tslint");
|
||||
return gulp.src("scripts/tslint/**/*.ts")
|
||||
.pipe(newer({
|
||||
dest,
|
||||
ext: ".js"
|
||||
}))
|
||||
.pipe(sourcemaps.init())
|
||||
.pipe(tsc(settings))
|
||||
.pipe(sourcemaps.write("."))
|
||||
.pipe(gulp.dest(dest));
|
||||
});
|
||||
const tslintRulesOutFiles = tslintRules.map(function(p, i) {
|
||||
const pathname = path.join(builtLocalDirectory, "tslint", p + ".js");
|
||||
gulp.task(pathname, false, [], () => {
|
||||
const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ false);
|
||||
return gulp.src(tslintRulesFiles[i])
|
||||
.pipe(newer(pathname))
|
||||
.pipe(sourcemaps.init())
|
||||
.pipe(tsc(settings))
|
||||
.pipe(sourcemaps.write("."))
|
||||
.pipe(gulp.dest(path.join(builtLocalDirectory, "tslint")));
|
||||
});
|
||||
return pathname;
|
||||
});
|
||||
|
||||
gulp.task("build-rules", "Compiles tslint rules to js", tslintRulesOutFiles);
|
||||
|
||||
|
||||
function getLinterOptions() {
|
||||
return {
|
||||
configuration: require("./tslint.json"),
|
||||
formatter: "prose",
|
||||
formattersDirectory: undefined,
|
||||
rulesDirectory: "built/local/tslint"
|
||||
};
|
||||
}
|
||||
|
||||
function lintFileContents(options, path, contents) {
|
||||
const ll = new Linter(path, contents, options);
|
||||
console.log("Linting '" + path + "'.");
|
||||
return ll.lint();
|
||||
}
|
||||
|
||||
function lintFile(options, path) {
|
||||
const contents = fs.readFileSync(path, "utf8");
|
||||
return lintFileContents(options, path, contents);
|
||||
}
|
||||
|
||||
const lintTargets = [
|
||||
"Gulpfile.ts",
|
||||
@@ -977,29 +941,75 @@ const lintTargets = [
|
||||
"src/server/**/*.ts",
|
||||
"scripts/tslint/**/*.ts",
|
||||
"src/services/**/*.ts",
|
||||
"tests/*.ts", "tests/webhost/*.ts" // Note: does *not* descend recursively
|
||||
];
|
||||
|
||||
function sendNextFile(files: {path: string}[], child: cp.ChildProcess, callback: (failures: number) => void, failures: number) {
|
||||
const file = files.pop();
|
||||
if (file) {
|
||||
console.log(`Linting '${file.path}'.`);
|
||||
child.send({ kind: "file", name: file.path });
|
||||
}
|
||||
else {
|
||||
child.send({ kind: "close" });
|
||||
callback(failures);
|
||||
}
|
||||
}
|
||||
|
||||
function spawnLintWorker(files: {path: string}[], callback: (failures: number) => void) {
|
||||
const child = cp.fork("./scripts/parallel-lint");
|
||||
let failures = 0;
|
||||
child.on("message", function(data) {
|
||||
switch (data.kind) {
|
||||
case "result":
|
||||
if (data.failures > 0) {
|
||||
failures += data.failures;
|
||||
console.log(data.output);
|
||||
}
|
||||
sendNextFile(files, child, callback, failures);
|
||||
break;
|
||||
case "error":
|
||||
console.error(data.error);
|
||||
failures++;
|
||||
sendNextFile(files, child, callback, failures);
|
||||
break;
|
||||
}
|
||||
});
|
||||
sendNextFile(files, child, callback, failures);
|
||||
}
|
||||
|
||||
gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => {
|
||||
const fileMatcher = RegExp(cmdLineOptions["files"]);
|
||||
const lintOptions = getLinterOptions();
|
||||
let failed = 0;
|
||||
return gulp.src(lintTargets)
|
||||
.pipe(insert.transform((contents, file) => {
|
||||
if (!fileMatcher.test(file.path)) return contents;
|
||||
const result = lintFile(lintOptions, file.path);
|
||||
if (result.failureCount > 0) {
|
||||
console.log(result.output);
|
||||
failed += result.failureCount;
|
||||
if (fold.isTravis()) console.log(fold.start("lint"));
|
||||
|
||||
let files: {stat: fs.Stats, path: string}[] = [];
|
||||
return gulp.src(lintTargets, { read: false })
|
||||
.pipe(through2.obj((chunk, enc, cb) => {
|
||||
files.push(chunk);
|
||||
cb();
|
||||
}, (cb) => {
|
||||
files = files.filter(file => fileMatcher.test(file.path)).sort((filea, fileb) => filea.stat.size - fileb.stat.size);
|
||||
const workerCount = (process.env.workerCount && +process.env.workerCount) || os.cpus().length;
|
||||
for (let i = 0; i < workerCount; i++) {
|
||||
spawnLintWorker(files, finished);
|
||||
}
|
||||
return contents; // TODO (weswig): Automatically apply fixes? :3
|
||||
}))
|
||||
.on("end", () => {
|
||||
if (failed > 0) {
|
||||
console.error("Linter errors.");
|
||||
process.exit(1);
|
||||
|
||||
let completed = 0;
|
||||
let failures = 0;
|
||||
function finished(fails) {
|
||||
completed++;
|
||||
failures += fails;
|
||||
if (completed === workerCount) {
|
||||
if (fold.isTravis()) console.log(fold.end("lint"));
|
||||
if (failures > 0) {
|
||||
throw new Error(`Linter errors: ${failures}`);
|
||||
}
|
||||
else {
|
||||
cb();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
|
||||
+337
-242
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,7 @@
|
||||
|
||||
[](https://gitter.im/Microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [Twitter account](https://twitter.com/typescriptlang).
|
||||
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescriptlang).
|
||||
|
||||
## Installing
|
||||
|
||||
|
||||
Vendored
+2
-2
@@ -20,7 +20,7 @@ interface Map<K, V> {
|
||||
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): this;
|
||||
set(key: K, value: V): this;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ interface WeakMap<K, V> {
|
||||
delete(key: K): boolean;
|
||||
get(key: K): V | undefined;
|
||||
has(key: K): boolean;
|
||||
set(key: K, value?: V): this;
|
||||
set(key: K, value: V): this;
|
||||
}
|
||||
|
||||
interface WeakMapConstructor {
|
||||
|
||||
+76
-120
@@ -825,17 +825,10 @@ var ts;
|
||||
return true;
|
||||
}
|
||||
ts.containsPath = containsPath;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
function fileExtensionIs(path, extension) {
|
||||
return path.length > extension.length && endsWith(path, extension);
|
||||
var pathLen = path.length;
|
||||
var extLen = extension.length;
|
||||
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
|
||||
}
|
||||
ts.fileExtensionIs = fileExtensionIs;
|
||||
function fileExtensionIsAny(path, extensions) {
|
||||
@@ -1100,8 +1093,6 @@ var ts;
|
||||
}
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return Node; },
|
||||
getTokenConstructor: function () { return Node; },
|
||||
getIdentifierConstructor: function () { return Node; },
|
||||
getSourceFileConstructor: function () { return Node; },
|
||||
getSymbolConstructor: function () { return Symbol; },
|
||||
getTypeConstructor: function () { return Type; },
|
||||
@@ -1233,7 +1224,7 @@ var ts;
|
||||
function readDirectory(path, extensions, excludes, includes) {
|
||||
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
|
||||
}
|
||||
var wscriptSystem = {
|
||||
return {
|
||||
args: args,
|
||||
newLine: "\r\n",
|
||||
useCaseSensitiveFileNames: false,
|
||||
@@ -1252,7 +1243,7 @@ var ts;
|
||||
return fso.FolderExists(path);
|
||||
},
|
||||
createDirectory: function (directoryName) {
|
||||
if (!wscriptSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
fso.CreateFolder(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -1272,7 +1263,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
};
|
||||
return wscriptSystem;
|
||||
}
|
||||
function getNodeSystem() {
|
||||
var _fs = require("fs");
|
||||
@@ -1445,7 +1435,7 @@ var ts;
|
||||
function getDirectories(path) {
|
||||
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
|
||||
}
|
||||
var nodeSystem = {
|
||||
return {
|
||||
args: process.argv.slice(2),
|
||||
newLine: _os.EOL,
|
||||
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
|
||||
@@ -1495,7 +1485,7 @@ var ts;
|
||||
fileExists: fileExists,
|
||||
directoryExists: directoryExists,
|
||||
createDirectory: function (directoryName) {
|
||||
if (!nodeSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
_fs.mkdirSync(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -1543,7 +1533,6 @@ var ts;
|
||||
return _fs.realpathSync(path);
|
||||
}
|
||||
};
|
||||
return nodeSystem;
|
||||
}
|
||||
function getChakraSystem() {
|
||||
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
|
||||
@@ -2293,8 +2282,8 @@ var ts;
|
||||
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
|
||||
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
|
||||
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
|
||||
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
|
||||
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
|
||||
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
|
||||
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
|
||||
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
|
||||
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
|
||||
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
|
||||
@@ -4847,7 +4836,7 @@ var ts;
|
||||
}
|
||||
ts.isExpression = isExpression;
|
||||
function isExternalModuleNameRelative(moduleName) {
|
||||
return /^\.\.?($|[\\/])/.test(moduleName);
|
||||
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
|
||||
}
|
||||
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
|
||||
function isInstantiatedModule(node, preserveConstEnums) {
|
||||
@@ -6355,24 +6344,25 @@ var ts;
|
||||
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
|
||||
}
|
||||
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
})(ts || (ts = {}));
|
||||
var ts;
|
||||
(function (ts) {
|
||||
ts.parseTime = 0;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
function createNode(kind, pos, end) {
|
||||
if (kind === 256) {
|
||||
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind === 69) {
|
||||
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind < 139) {
|
||||
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
|
||||
}
|
||||
else {
|
||||
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
|
||||
}
|
||||
@@ -6795,8 +6785,6 @@ var ts;
|
||||
var scanner = ts.createScanner(2, true);
|
||||
var disallowInAndDecoratorContext = 4194304 | 16777216;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
var sourceFile;
|
||||
var parseDiagnostics;
|
||||
@@ -6822,8 +6810,6 @@ var ts;
|
||||
}
|
||||
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
|
||||
NodeConstructor = ts.objectAllocator.getNodeConstructor();
|
||||
TokenConstructor = ts.objectAllocator.getTokenConstructor();
|
||||
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
|
||||
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
|
||||
sourceText = _sourceText;
|
||||
syntaxCursor = _syntaxCursor;
|
||||
@@ -7130,9 +7116,7 @@ var ts;
|
||||
if (!(pos >= 0)) {
|
||||
pos = scanner.getStartPos();
|
||||
}
|
||||
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
|
||||
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
|
||||
new TokenConstructor(kind, pos, pos);
|
||||
return new NodeConstructor(kind, pos, pos);
|
||||
}
|
||||
function finishNode(node, end) {
|
||||
node.end = end === undefined ? scanner.getStartPos() : end;
|
||||
@@ -10908,9 +10892,6 @@ var ts;
|
||||
case 55:
|
||||
if (canParseTag) {
|
||||
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
|
||||
if (!parentTagTerminated) {
|
||||
resumePos = scanner.getStartPos();
|
||||
}
|
||||
}
|
||||
seenAsterisk = false;
|
||||
break;
|
||||
@@ -15437,18 +15418,17 @@ var ts;
|
||||
if (declaration.kind === 235) {
|
||||
return links.type = checkExpression(declaration.expression);
|
||||
}
|
||||
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
|
||||
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
|
||||
}
|
||||
if (!pushTypeResolution(symbol, 0)) {
|
||||
return unknownType;
|
||||
}
|
||||
var type = undefined;
|
||||
if (declaration.kind === 187 ||
|
||||
declaration.kind === 172 && declaration.parent.kind === 187) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
|
||||
checkExpressionCached(decl.right) :
|
||||
checkExpressionCached(decl.parent.right); }));
|
||||
if (declaration.kind === 187) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
|
||||
}
|
||||
else if (declaration.kind === 172) {
|
||||
if (declaration.parent.kind === 187) {
|
||||
type = checkExpressionCached(declaration.parent.right);
|
||||
}
|
||||
}
|
||||
if (type === undefined) {
|
||||
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
|
||||
@@ -21955,7 +21935,7 @@ var ts;
|
||||
function getInferredClassType(symbol) {
|
||||
var links = getSymbolLinks(symbol);
|
||||
if (!links.inferredClassType) {
|
||||
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
|
||||
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
|
||||
}
|
||||
return links.inferredClassType;
|
||||
}
|
||||
@@ -23175,7 +23155,7 @@ var ts;
|
||||
checkAsyncFunctionReturnType(node);
|
||||
}
|
||||
}
|
||||
if (noUnusedIdentifiers && !node.body) {
|
||||
if (!node.body) {
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
@@ -24071,7 +24051,6 @@ var ts;
|
||||
var parameter = local_1.valueDeclaration;
|
||||
if (compilerOptions.noUnusedParameters &&
|
||||
!ts.isParameterPropertyDeclaration(parameter) &&
|
||||
!parameterIsThisKeyword(parameter) &&
|
||||
!parameterNameStartsWithUnderscore(parameter)) {
|
||||
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
|
||||
}
|
||||
@@ -24087,9 +24066,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parameterIsThisKeyword(parameter) {
|
||||
return parameter.name && parameter.name.originalKeywordKind === 97;
|
||||
}
|
||||
function parameterNameStartsWithUnderscore(parameter) {
|
||||
return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95;
|
||||
}
|
||||
@@ -24118,14 +24094,9 @@ var ts;
|
||||
function checkUnusedTypeParameters(node) {
|
||||
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
|
||||
if (node.typeParameters) {
|
||||
var symbol = getSymbolOfNode(node);
|
||||
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
|
||||
if (lastDeclaration !== node) {
|
||||
return;
|
||||
}
|
||||
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
|
||||
var typeParameter = _a[_i];
|
||||
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
|
||||
if (!typeParameter.symbol.isReferenced) {
|
||||
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
|
||||
}
|
||||
}
|
||||
@@ -25202,7 +25173,7 @@ var ts;
|
||||
ts.forEach(node.members, checkSourceElement);
|
||||
if (produceDiagnostics) {
|
||||
checkTypeForDuplicateIndexSignatures(node);
|
||||
registerForUnusedIdentifiersCheck(node);
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
function checkTypeAliasDeclaration(node) {
|
||||
@@ -29925,7 +29896,7 @@ var ts;
|
||||
writeLine();
|
||||
var sourceMappingURL = sourceMap.getSourceMappingURL();
|
||||
if (sourceMappingURL) {
|
||||
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
|
||||
write("//# sourceMappingURL=" + sourceMappingURL);
|
||||
}
|
||||
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
|
||||
sourceMap.reset();
|
||||
@@ -33575,13 +33546,13 @@ var ts;
|
||||
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
|
||||
write("export ");
|
||||
}
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
if (decoratedClassAlias !== undefined) {
|
||||
write("let " + decoratedClassAlias);
|
||||
write("" + decoratedClassAlias);
|
||||
}
|
||||
else {
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
emitDeclarationName(node);
|
||||
}
|
||||
write(" = ");
|
||||
@@ -35825,7 +35796,7 @@ var ts;
|
||||
ts.emitTime = 0;
|
||||
ts.ioReadTime = 0;
|
||||
ts.ioWriteTime = 0;
|
||||
ts.version = "2.1.0";
|
||||
ts.version = "2.0.0";
|
||||
var emptyArray = [];
|
||||
var defaultTypeRoots = ["node_modules/@types"];
|
||||
function findConfigFile(searchPath, fileExists) {
|
||||
@@ -35905,7 +35876,12 @@ var ts;
|
||||
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
|
||||
}
|
||||
function moduleHasNonRelativeName(moduleName) {
|
||||
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
|
||||
if (ts.isRootedDiskPath(moduleName)) {
|
||||
return false;
|
||||
}
|
||||
var i = moduleName.lastIndexOf("./", 1);
|
||||
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
|
||||
return !startsWithDotSlashOrDotDotSlash;
|
||||
}
|
||||
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
|
||||
var jsonContent;
|
||||
@@ -36561,22 +36537,6 @@ var ts;
|
||||
return ts.sortAndDeduplicateDiagnostics(diagnostics);
|
||||
}
|
||||
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
|
||||
function formatDiagnostics(diagnostics, host) {
|
||||
var output = "";
|
||||
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
|
||||
var diagnostic = diagnostics_1[_i];
|
||||
if (diagnostic.file) {
|
||||
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
|
||||
var fileName = diagnostic.file.fileName;
|
||||
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
|
||||
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
|
||||
}
|
||||
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
ts.formatDiagnostics = formatDiagnostics;
|
||||
function flattenDiagnosticMessageText(messageText, newLine) {
|
||||
if (typeof messageText === "string") {
|
||||
return messageText;
|
||||
@@ -36652,7 +36612,7 @@ var ts;
|
||||
var resolvedTypeReferenceDirectives = {};
|
||||
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
|
||||
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
|
||||
var currentNodeModulesDepth = 0;
|
||||
var currentNodeModulesJsDepth = 0;
|
||||
var modulesWithElidedImports = {};
|
||||
var sourceFilesFoundSearchingNodeModules = {};
|
||||
var start = new Date().getTime();
|
||||
@@ -36876,7 +36836,8 @@ var ts;
|
||||
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
|
||||
}
|
||||
function emit(sourceFile, writeFileCallback, cancellationToken) {
|
||||
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
|
||||
var _this = this;
|
||||
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
|
||||
}
|
||||
function isEmitBlocked(emitFileName) {
|
||||
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
|
||||
@@ -37283,17 +37244,8 @@ var ts;
|
||||
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
|
||||
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
|
||||
}
|
||||
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
|
||||
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
|
||||
if (!options.noResolve) {
|
||||
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
|
||||
processTypeReferenceDirectives(file_1);
|
||||
}
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
|
||||
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
@@ -37310,7 +37262,6 @@ var ts;
|
||||
});
|
||||
filesByName.set(path, file);
|
||||
if (file) {
|
||||
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
|
||||
file.path = path;
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
var existingFile = filesByNameIgnoreCase.get(path);
|
||||
@@ -37411,9 +37362,12 @@ var ts;
|
||||
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
|
||||
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth++;
|
||||
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth++;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
|
||||
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
|
||||
if (elideImport) {
|
||||
modulesWithElidedImports[file.path] = true;
|
||||
@@ -37421,8 +37375,8 @@ var ts;
|
||||
else if (shouldAddFile) {
|
||||
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
|
||||
}
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth--;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37741,12 +37695,12 @@ var ts;
|
||||
{
|
||||
name: "noUnusedLocals",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_locals
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_parameters
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -38525,18 +38479,10 @@ var ts;
|
||||
})(ts || (ts = {}));
|
||||
var ts;
|
||||
(function (ts) {
|
||||
var defaultFormatDiagnosticsHost = {
|
||||
getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
|
||||
getNewLine: function () { return ts.sys.newLine; },
|
||||
getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
|
||||
};
|
||||
var reportDiagnosticWorker = reportDiagnosticSimply;
|
||||
function reportDiagnostic(diagnostic, host) {
|
||||
reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost);
|
||||
}
|
||||
var reportDiagnostic = reportDiagnosticSimply;
|
||||
function reportDiagnostics(diagnostics, host) {
|
||||
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
|
||||
var diagnostic = diagnostics_2[_i];
|
||||
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
|
||||
var diagnostic = diagnostics_1[_i];
|
||||
reportDiagnostic(diagnostic, host);
|
||||
}
|
||||
}
|
||||
@@ -38607,8 +38553,19 @@ var ts;
|
||||
var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
|
||||
return diagnostic.messageText;
|
||||
}
|
||||
function getRelativeFileName(fileName, host) {
|
||||
return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName;
|
||||
}
|
||||
function reportDiagnosticSimply(diagnostic, host) {
|
||||
ts.sys.write(ts.formatDiagnostics([diagnostic], host));
|
||||
var output = "";
|
||||
if (diagnostic.file) {
|
||||
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
|
||||
var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host);
|
||||
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
|
||||
}
|
||||
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine;
|
||||
ts.sys.write(output);
|
||||
}
|
||||
var redForegroundEscapeSequence = "\u001b[91m";
|
||||
var yellowForegroundEscapeSequence = "\u001b[93m";
|
||||
@@ -38633,7 +38590,7 @@ var ts;
|
||||
var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
|
||||
var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character;
|
||||
var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
|
||||
var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
|
||||
var relativeFileName = getRelativeFileName(file.fileName, host);
|
||||
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
|
||||
var gutterWidth = (lastLine + 1 + "").length;
|
||||
if (hasMoreThanFiveLines) {
|
||||
@@ -38822,8 +38779,7 @@ var ts;
|
||||
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
|
||||
return;
|
||||
}
|
||||
var cwd = ts.sys.getCurrentDirectory();
|
||||
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd));
|
||||
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName);
|
||||
if (configParseResult.errors.length > 0) {
|
||||
reportDiagnostics(configParseResult.errors, undefined);
|
||||
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
|
||||
@@ -38860,7 +38816,7 @@ var ts;
|
||||
compilerHost.fileExists = cachedFileExists;
|
||||
}
|
||||
if (compilerOptions.pretty) {
|
||||
reportDiagnosticWorker = reportDiagnosticWithColorAndContext;
|
||||
reportDiagnostic = reportDiagnosticWithColorAndContext;
|
||||
}
|
||||
cachedExistingFiles = {};
|
||||
var compileResult = compile(rootFileNames, compilerOptions, compilerHost);
|
||||
@@ -39023,7 +38979,7 @@ var ts;
|
||||
output += ts.sys.newLine + ts.sys.newLine;
|
||||
var padding = makePadding(marginLength);
|
||||
output += getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine;
|
||||
output += padding + "tsc --outFile file.js file.ts" + ts.sys.newLine;
|
||||
output += padding + "tsc --out file.js file.ts" + ts.sys.newLine;
|
||||
output += padding + "tsc @args.txt" + ts.sys.newLine;
|
||||
output += ts.sys.newLine;
|
||||
output += getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine;
|
||||
|
||||
+77
-193
@@ -830,17 +830,10 @@ var ts;
|
||||
return true;
|
||||
}
|
||||
ts.containsPath = containsPath;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
function fileExtensionIs(path, extension) {
|
||||
return path.length > extension.length && endsWith(path, extension);
|
||||
var pathLen = path.length;
|
||||
var extLen = extension.length;
|
||||
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
|
||||
}
|
||||
ts.fileExtensionIs = fileExtensionIs;
|
||||
function fileExtensionIsAny(path, extensions) {
|
||||
@@ -1105,8 +1098,6 @@ var ts;
|
||||
}
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return Node; },
|
||||
getTokenConstructor: function () { return Node; },
|
||||
getIdentifierConstructor: function () { return Node; },
|
||||
getSourceFileConstructor: function () { return Node; },
|
||||
getSymbolConstructor: function () { return Symbol; },
|
||||
getTypeConstructor: function () { return Type; },
|
||||
@@ -1238,7 +1229,7 @@ var ts;
|
||||
function readDirectory(path, extensions, excludes, includes) {
|
||||
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
|
||||
}
|
||||
var wscriptSystem = {
|
||||
return {
|
||||
args: args,
|
||||
newLine: "\r\n",
|
||||
useCaseSensitiveFileNames: false,
|
||||
@@ -1257,7 +1248,7 @@ var ts;
|
||||
return fso.FolderExists(path);
|
||||
},
|
||||
createDirectory: function (directoryName) {
|
||||
if (!wscriptSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
fso.CreateFolder(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -1277,7 +1268,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
};
|
||||
return wscriptSystem;
|
||||
}
|
||||
function getNodeSystem() {
|
||||
var _fs = require("fs");
|
||||
@@ -1450,7 +1440,7 @@ var ts;
|
||||
function getDirectories(path) {
|
||||
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
|
||||
}
|
||||
var nodeSystem = {
|
||||
return {
|
||||
args: process.argv.slice(2),
|
||||
newLine: _os.EOL,
|
||||
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
|
||||
@@ -1500,7 +1490,7 @@ var ts;
|
||||
fileExists: fileExists,
|
||||
directoryExists: directoryExists,
|
||||
createDirectory: function (directoryName) {
|
||||
if (!nodeSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
_fs.mkdirSync(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -1548,7 +1538,6 @@ var ts;
|
||||
return _fs.realpathSync(path);
|
||||
}
|
||||
};
|
||||
return nodeSystem;
|
||||
}
|
||||
function getChakraSystem() {
|
||||
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
|
||||
@@ -2298,8 +2287,8 @@ var ts;
|
||||
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
|
||||
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
|
||||
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
|
||||
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
|
||||
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
|
||||
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
|
||||
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
|
||||
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
|
||||
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
|
||||
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
|
||||
@@ -3977,12 +3966,12 @@ var ts;
|
||||
{
|
||||
name: "noUnusedLocals",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_locals
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_parameters
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -5765,7 +5754,7 @@ var ts;
|
||||
}
|
||||
ts.isExpression = isExpression;
|
||||
function isExternalModuleNameRelative(moduleName) {
|
||||
return /^\.\.?($|[\\/])/.test(moduleName);
|
||||
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
|
||||
}
|
||||
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
|
||||
function isInstantiatedModule(node, preserveConstEnums) {
|
||||
@@ -7273,24 +7262,25 @@ var ts;
|
||||
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
|
||||
}
|
||||
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
})(ts || (ts = {}));
|
||||
var ts;
|
||||
(function (ts) {
|
||||
ts.parseTime = 0;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
function createNode(kind, pos, end) {
|
||||
if (kind === 256) {
|
||||
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind === 69) {
|
||||
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind < 139) {
|
||||
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
|
||||
}
|
||||
else {
|
||||
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
|
||||
}
|
||||
@@ -7713,8 +7703,6 @@ var ts;
|
||||
var scanner = ts.createScanner(2, true);
|
||||
var disallowInAndDecoratorContext = 4194304 | 16777216;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
var sourceFile;
|
||||
var parseDiagnostics;
|
||||
@@ -7740,8 +7728,6 @@ var ts;
|
||||
}
|
||||
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
|
||||
NodeConstructor = ts.objectAllocator.getNodeConstructor();
|
||||
TokenConstructor = ts.objectAllocator.getTokenConstructor();
|
||||
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
|
||||
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
|
||||
sourceText = _sourceText;
|
||||
syntaxCursor = _syntaxCursor;
|
||||
@@ -8048,9 +8034,7 @@ var ts;
|
||||
if (!(pos >= 0)) {
|
||||
pos = scanner.getStartPos();
|
||||
}
|
||||
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
|
||||
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
|
||||
new TokenConstructor(kind, pos, pos);
|
||||
return new NodeConstructor(kind, pos, pos);
|
||||
}
|
||||
function finishNode(node, end) {
|
||||
node.end = end === undefined ? scanner.getStartPos() : end;
|
||||
@@ -11826,9 +11810,6 @@ var ts;
|
||||
case 55:
|
||||
if (canParseTag) {
|
||||
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
|
||||
if (!parentTagTerminated) {
|
||||
resumePos = scanner.getStartPos();
|
||||
}
|
||||
}
|
||||
seenAsterisk = false;
|
||||
break;
|
||||
@@ -16355,18 +16336,17 @@ var ts;
|
||||
if (declaration.kind === 235) {
|
||||
return links.type = checkExpression(declaration.expression);
|
||||
}
|
||||
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
|
||||
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
|
||||
}
|
||||
if (!pushTypeResolution(symbol, 0)) {
|
||||
return unknownType;
|
||||
}
|
||||
var type = undefined;
|
||||
if (declaration.kind === 187 ||
|
||||
declaration.kind === 172 && declaration.parent.kind === 187) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
|
||||
checkExpressionCached(decl.right) :
|
||||
checkExpressionCached(decl.parent.right); }));
|
||||
if (declaration.kind === 187) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
|
||||
}
|
||||
else if (declaration.kind === 172) {
|
||||
if (declaration.parent.kind === 187) {
|
||||
type = checkExpressionCached(declaration.parent.right);
|
||||
}
|
||||
}
|
||||
if (type === undefined) {
|
||||
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
|
||||
@@ -22873,7 +22853,7 @@ var ts;
|
||||
function getInferredClassType(symbol) {
|
||||
var links = getSymbolLinks(symbol);
|
||||
if (!links.inferredClassType) {
|
||||
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
|
||||
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
|
||||
}
|
||||
return links.inferredClassType;
|
||||
}
|
||||
@@ -24093,7 +24073,7 @@ var ts;
|
||||
checkAsyncFunctionReturnType(node);
|
||||
}
|
||||
}
|
||||
if (noUnusedIdentifiers && !node.body) {
|
||||
if (!node.body) {
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
@@ -24989,7 +24969,6 @@ var ts;
|
||||
var parameter = local_1.valueDeclaration;
|
||||
if (compilerOptions.noUnusedParameters &&
|
||||
!ts.isParameterPropertyDeclaration(parameter) &&
|
||||
!parameterIsThisKeyword(parameter) &&
|
||||
!parameterNameStartsWithUnderscore(parameter)) {
|
||||
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
|
||||
}
|
||||
@@ -25005,9 +24984,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parameterIsThisKeyword(parameter) {
|
||||
return parameter.name && parameter.name.originalKeywordKind === 97;
|
||||
}
|
||||
function parameterNameStartsWithUnderscore(parameter) {
|
||||
return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95;
|
||||
}
|
||||
@@ -25036,14 +25012,9 @@ var ts;
|
||||
function checkUnusedTypeParameters(node) {
|
||||
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
|
||||
if (node.typeParameters) {
|
||||
var symbol = getSymbolOfNode(node);
|
||||
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
|
||||
if (lastDeclaration !== node) {
|
||||
return;
|
||||
}
|
||||
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
|
||||
var typeParameter = _a[_i];
|
||||
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
|
||||
if (!typeParameter.symbol.isReferenced) {
|
||||
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
|
||||
}
|
||||
}
|
||||
@@ -26120,7 +26091,7 @@ var ts;
|
||||
ts.forEach(node.members, checkSourceElement);
|
||||
if (produceDiagnostics) {
|
||||
checkTypeForDuplicateIndexSignatures(node);
|
||||
registerForUnusedIdentifiersCheck(node);
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
function checkTypeAliasDeclaration(node) {
|
||||
@@ -30843,7 +30814,7 @@ var ts;
|
||||
writeLine();
|
||||
var sourceMappingURL = sourceMap.getSourceMappingURL();
|
||||
if (sourceMappingURL) {
|
||||
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
|
||||
write("//# sourceMappingURL=" + sourceMappingURL);
|
||||
}
|
||||
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
|
||||
sourceMap.reset();
|
||||
@@ -34493,13 +34464,13 @@ var ts;
|
||||
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
|
||||
write("export ");
|
||||
}
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
if (decoratedClassAlias !== undefined) {
|
||||
write("let " + decoratedClassAlias);
|
||||
write("" + decoratedClassAlias);
|
||||
}
|
||||
else {
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
emitDeclarationName(node);
|
||||
}
|
||||
write(" = ");
|
||||
@@ -36743,7 +36714,7 @@ var ts;
|
||||
ts.emitTime = 0;
|
||||
ts.ioReadTime = 0;
|
||||
ts.ioWriteTime = 0;
|
||||
ts.version = "2.1.0";
|
||||
ts.version = "2.0.0";
|
||||
var emptyArray = [];
|
||||
var defaultTypeRoots = ["node_modules/@types"];
|
||||
function findConfigFile(searchPath, fileExists) {
|
||||
@@ -36823,7 +36794,12 @@ var ts;
|
||||
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
|
||||
}
|
||||
function moduleHasNonRelativeName(moduleName) {
|
||||
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
|
||||
if (ts.isRootedDiskPath(moduleName)) {
|
||||
return false;
|
||||
}
|
||||
var i = moduleName.lastIndexOf("./", 1);
|
||||
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
|
||||
return !startsWithDotSlashOrDotDotSlash;
|
||||
}
|
||||
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
|
||||
var jsonContent;
|
||||
@@ -37479,22 +37455,6 @@ var ts;
|
||||
return ts.sortAndDeduplicateDiagnostics(diagnostics);
|
||||
}
|
||||
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
|
||||
function formatDiagnostics(diagnostics, host) {
|
||||
var output = "";
|
||||
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
|
||||
var diagnostic = diagnostics_1[_i];
|
||||
if (diagnostic.file) {
|
||||
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
|
||||
var fileName = diagnostic.file.fileName;
|
||||
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
|
||||
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
|
||||
}
|
||||
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
ts.formatDiagnostics = formatDiagnostics;
|
||||
function flattenDiagnosticMessageText(messageText, newLine) {
|
||||
if (typeof messageText === "string") {
|
||||
return messageText;
|
||||
@@ -37570,7 +37530,7 @@ var ts;
|
||||
var resolvedTypeReferenceDirectives = {};
|
||||
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
|
||||
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
|
||||
var currentNodeModulesDepth = 0;
|
||||
var currentNodeModulesJsDepth = 0;
|
||||
var modulesWithElidedImports = {};
|
||||
var sourceFilesFoundSearchingNodeModules = {};
|
||||
var start = new Date().getTime();
|
||||
@@ -37794,7 +37754,8 @@ var ts;
|
||||
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
|
||||
}
|
||||
function emit(sourceFile, writeFileCallback, cancellationToken) {
|
||||
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
|
||||
var _this = this;
|
||||
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
|
||||
}
|
||||
function isEmitBlocked(emitFileName) {
|
||||
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
|
||||
@@ -38201,17 +38162,8 @@ var ts;
|
||||
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
|
||||
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
|
||||
}
|
||||
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
|
||||
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
|
||||
if (!options.noResolve) {
|
||||
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
|
||||
processTypeReferenceDirectives(file_1);
|
||||
}
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
|
||||
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
@@ -38228,7 +38180,6 @@ var ts;
|
||||
});
|
||||
filesByName.set(path, file);
|
||||
if (file) {
|
||||
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
|
||||
file.path = path;
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
var existingFile = filesByNameIgnoreCase.get(path);
|
||||
@@ -38329,9 +38280,12 @@ var ts;
|
||||
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
|
||||
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth++;
|
||||
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth++;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
|
||||
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
|
||||
if (elideImport) {
|
||||
modulesWithElidedImports[file.path] = true;
|
||||
@@ -38339,8 +38293,8 @@ var ts;
|
||||
else if (shouldAddFile) {
|
||||
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
|
||||
}
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth--;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39933,7 +39887,7 @@ var ts;
|
||||
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
|
||||
}
|
||||
else {
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
|
||||
}
|
||||
}
|
||||
var isLowercase = chunk.isLowerCase;
|
||||
@@ -40105,6 +40059,14 @@ var ts;
|
||||
var str = String.fromCharCode(ch);
|
||||
return str === str.toLowerCase();
|
||||
}
|
||||
function startsWith(string, search) {
|
||||
for (var i = 0, n = search.length; i < n; i++) {
|
||||
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function indexOfIgnoringCase(string, value) {
|
||||
for (var i = 0, n = string.length - value.length; i <= n; i++) {
|
||||
if (startsWithIgnoringCase(string, value, i)) {
|
||||
@@ -41589,9 +41551,6 @@ var ts;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function shouldRescanJsxText(node) {
|
||||
return node && node.kind === 244;
|
||||
}
|
||||
function shouldRescanSlashToken(container) {
|
||||
return container.kind === 10;
|
||||
}
|
||||
@@ -41619,9 +41578,7 @@ var ts;
|
||||
? 3
|
||||
: shouldRescanJsxIdentifier(n)
|
||||
? 4
|
||||
: shouldRescanJsxText(n)
|
||||
? 5
|
||||
: 0;
|
||||
: 0;
|
||||
if (lastTokenInfo && expectedScanAction === lastScanAction) {
|
||||
return fixTokenKind(lastTokenInfo, n);
|
||||
}
|
||||
@@ -41649,10 +41606,6 @@ var ts;
|
||||
currentToken = scanner.scanJsxIdentifier();
|
||||
lastScanAction = 4;
|
||||
}
|
||||
else if (expectedScanAction === 5) {
|
||||
currentToken = scanner.reScanJsxToken();
|
||||
lastScanAction = 5;
|
||||
}
|
||||
else {
|
||||
lastScanAction = 0;
|
||||
}
|
||||
@@ -43901,20 +43854,19 @@ var ts;
|
||||
"version"
|
||||
];
|
||||
var jsDocCompletionEntries;
|
||||
function createNode(kind, pos, end, parent) {
|
||||
var node = kind >= 139 ? new NodeObject(kind, pos, end) :
|
||||
kind === 69 ? new IdentifierObject(kind, pos, end) :
|
||||
new TokenObject(kind, pos, end);
|
||||
function createNode(kind, pos, end, flags, parent) {
|
||||
var node = new NodeObject(kind, pos, end);
|
||||
node.flags = flags;
|
||||
node.parent = parent;
|
||||
return node;
|
||||
}
|
||||
var NodeObject = (function () {
|
||||
function NodeObject(kind, pos, end) {
|
||||
this.kind = kind;
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0;
|
||||
this.parent = undefined;
|
||||
this.kind = kind;
|
||||
}
|
||||
NodeObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
@@ -43949,14 +43901,14 @@ var ts;
|
||||
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
|
||||
var textPos = scanner.getTextPos();
|
||||
if (textPos <= end) {
|
||||
nodes.push(createNode(token, pos, textPos, this));
|
||||
nodes.push(createNode(token, pos, textPos, 0, this));
|
||||
}
|
||||
pos = textPos;
|
||||
}
|
||||
return pos;
|
||||
};
|
||||
NodeObject.prototype.createSyntaxList = function (nodes) {
|
||||
var list = createNode(282, nodes.pos, nodes.end, this);
|
||||
var list = createNode(282, nodes.pos, nodes.end, 0, this);
|
||||
list._children = [];
|
||||
var pos = nodes.pos;
|
||||
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
|
||||
@@ -44041,73 +43993,6 @@ var ts;
|
||||
};
|
||||
return NodeObject;
|
||||
}());
|
||||
var TokenOrIdentifierObject = (function () {
|
||||
function TokenOrIdentifierObject(pos, end) {
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0;
|
||||
this.parent = undefined;
|
||||
}
|
||||
TokenOrIdentifierObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
|
||||
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullStart = function () {
|
||||
return this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getEnd = function () {
|
||||
return this.end;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
|
||||
return this.getEnd() - this.getStart(sourceFile);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullWidth = function () {
|
||||
return this.end - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
|
||||
return this.getStart(sourceFile) - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
|
||||
return 0;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
|
||||
return emptyArray;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
return TokenOrIdentifierObject;
|
||||
}());
|
||||
var TokenObject = (function (_super) {
|
||||
__extends(TokenObject, _super);
|
||||
function TokenObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
this.kind = kind;
|
||||
}
|
||||
return TokenObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
var IdentifierObject = (function (_super) {
|
||||
__extends(IdentifierObject, _super);
|
||||
function IdentifierObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
}
|
||||
return IdentifierObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
IdentifierObject.prototype.kind = 69;
|
||||
var SymbolObject = (function () {
|
||||
function SymbolObject(flags, name) {
|
||||
this.flags = flags;
|
||||
@@ -49788,8 +49673,6 @@ var ts;
|
||||
function initializeServices() {
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return NodeObject; },
|
||||
getTokenConstructor: function () { return TokenObject; },
|
||||
getIdentifierConstructor: function () { return IdentifierObject; },
|
||||
getSourceFileConstructor: function () { return SourceFileObject; },
|
||||
getSymbolConstructor: function () { return SymbolObject; },
|
||||
getTypeConstructor: function () { return TypeObject; },
|
||||
@@ -50910,6 +50793,7 @@ var ts;
|
||||
if (isOpen === void 0) { isOpen = false; }
|
||||
this.host = host;
|
||||
this.fileName = fileName;
|
||||
this.content = content;
|
||||
this.isOpen = isOpen;
|
||||
this.children = [];
|
||||
this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
|
||||
@@ -52535,7 +52419,7 @@ var ts;
|
||||
done: false,
|
||||
leaf: function (relativeStart, relativeLength, ll) {
|
||||
if (!f(ll, relativeStart, relativeLength)) {
|
||||
walkFns.done = true;
|
||||
this.done = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -53185,7 +53069,7 @@ var ts;
|
||||
ioSession.listen();
|
||||
})(server = ts.server || (ts.server = {}));
|
||||
})(ts || (ts = {}));
|
||||
var debugObjectHost = new Function("return this")();
|
||||
var debugObjectHost = this;
|
||||
var ts;
|
||||
(function (ts) {
|
||||
function logInternalError(logger, err) {
|
||||
@@ -53313,7 +53197,7 @@ var ts;
|
||||
return this.shimHost.getCurrentDirectory();
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
|
||||
return JSON.parse(this.shimHost.getDirectories(path));
|
||||
return this.shimHost.getDirectories(path);
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
|
||||
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
|
||||
|
||||
Vendored
+8
-17
@@ -405,10 +405,7 @@ declare namespace ts {
|
||||
interface ModifiersArray extends NodeArray<Modifier> {
|
||||
flags: NodeFlags;
|
||||
}
|
||||
interface Token extends Node {
|
||||
__tokenTag: any;
|
||||
}
|
||||
interface Modifier extends Token {
|
||||
interface Modifier extends Node {
|
||||
}
|
||||
interface Identifier extends PrimaryExpression {
|
||||
text: string;
|
||||
@@ -2053,6 +2050,7 @@ declare namespace ts {
|
||||
getCancellationToken?(): CancellationToken;
|
||||
getDefaultLibFileName(options: CompilerOptions): string;
|
||||
getDefaultLibLocation?(): string;
|
||||
getDefaultTypeDirectiveNames?(rootPath: string): string[];
|
||||
writeFile: WriteFileCallback;
|
||||
getCurrentDirectory(): string;
|
||||
getDirectories(path: string): string[];
|
||||
@@ -2158,8 +2156,6 @@ declare namespace ts {
|
||||
function ensureTrailingDirectorySeparator(path: string): string;
|
||||
function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
|
||||
function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
|
||||
function startsWith(str: string, prefix: string): boolean;
|
||||
function endsWith(str: string, suffix: string): boolean;
|
||||
function fileExtensionIs(path: string, extension: string): boolean;
|
||||
function fileExtensionIsAny(path: string, extensions: string[]): boolean;
|
||||
function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string;
|
||||
@@ -2197,8 +2193,6 @@ declare namespace ts {
|
||||
function changeExtension<T extends string | Path>(path: T, newExtension: string): T;
|
||||
interface ObjectAllocator {
|
||||
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
|
||||
getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
|
||||
getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
|
||||
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
|
||||
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
|
||||
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
|
||||
@@ -6462,13 +6456,13 @@ declare namespace ts {
|
||||
key: string;
|
||||
message: string;
|
||||
};
|
||||
Report_errors_on_unused_locals: {
|
||||
Report_Errors_on_Unused_Locals: {
|
||||
code: number;
|
||||
category: DiagnosticCategory;
|
||||
key: string;
|
||||
message: string;
|
||||
};
|
||||
Report_errors_on_unused_parameters: {
|
||||
Report_Errors_on_Unused_Parameters: {
|
||||
code: number;
|
||||
category: DiagnosticCategory;
|
||||
key: string;
|
||||
@@ -7149,6 +7143,8 @@ 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 {
|
||||
let parseTime: number;
|
||||
@@ -7229,12 +7225,6 @@ declare namespace ts {
|
||||
const defaultInitCompilerOptions: CompilerOptions;
|
||||
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
|
||||
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
|
||||
interface FormatDiagnosticsHost {
|
||||
getCurrentDirectory(): string;
|
||||
getCanonicalFileName(fileName: string): string;
|
||||
getNewLine(): string;
|
||||
}
|
||||
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
|
||||
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
|
||||
function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[];
|
||||
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
|
||||
@@ -8398,6 +8388,7 @@ declare namespace ts.server {
|
||||
class ScriptInfo {
|
||||
private host;
|
||||
fileName: string;
|
||||
content: string;
|
||||
isOpen: boolean;
|
||||
svc: ScriptVersionCache;
|
||||
children: ScriptInfo[];
|
||||
@@ -8738,7 +8729,7 @@ declare namespace ts {
|
||||
getLocalizedDiagnosticMessages(): string;
|
||||
getCancellationToken(): HostCancellationToken;
|
||||
getCurrentDirectory(): string;
|
||||
getDirectories(path: string): string;
|
||||
getDirectories(path: string): string[];
|
||||
getDefaultLibFileName(options: string): string;
|
||||
getNewLine?(): string;
|
||||
getProjectVersion?(): string;
|
||||
|
||||
+77
-193
@@ -830,17 +830,10 @@ var ts;
|
||||
return true;
|
||||
}
|
||||
ts.containsPath = containsPath;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
function fileExtensionIs(path, extension) {
|
||||
return path.length > extension.length && endsWith(path, extension);
|
||||
var pathLen = path.length;
|
||||
var extLen = extension.length;
|
||||
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
|
||||
}
|
||||
ts.fileExtensionIs = fileExtensionIs;
|
||||
function fileExtensionIsAny(path, extensions) {
|
||||
@@ -1105,8 +1098,6 @@ var ts;
|
||||
}
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return Node; },
|
||||
getTokenConstructor: function () { return Node; },
|
||||
getIdentifierConstructor: function () { return Node; },
|
||||
getSourceFileConstructor: function () { return Node; },
|
||||
getSymbolConstructor: function () { return Symbol; },
|
||||
getTypeConstructor: function () { return Type; },
|
||||
@@ -1238,7 +1229,7 @@ var ts;
|
||||
function readDirectory(path, extensions, excludes, includes) {
|
||||
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
|
||||
}
|
||||
var wscriptSystem = {
|
||||
return {
|
||||
args: args,
|
||||
newLine: "\r\n",
|
||||
useCaseSensitiveFileNames: false,
|
||||
@@ -1257,7 +1248,7 @@ var ts;
|
||||
return fso.FolderExists(path);
|
||||
},
|
||||
createDirectory: function (directoryName) {
|
||||
if (!wscriptSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
fso.CreateFolder(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -1277,7 +1268,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
};
|
||||
return wscriptSystem;
|
||||
}
|
||||
function getNodeSystem() {
|
||||
var _fs = require("fs");
|
||||
@@ -1450,7 +1440,7 @@ var ts;
|
||||
function getDirectories(path) {
|
||||
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
|
||||
}
|
||||
var nodeSystem = {
|
||||
return {
|
||||
args: process.argv.slice(2),
|
||||
newLine: _os.EOL,
|
||||
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
|
||||
@@ -1500,7 +1490,7 @@ var ts;
|
||||
fileExists: fileExists,
|
||||
directoryExists: directoryExists,
|
||||
createDirectory: function (directoryName) {
|
||||
if (!nodeSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
_fs.mkdirSync(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -1548,7 +1538,6 @@ var ts;
|
||||
return _fs.realpathSync(path);
|
||||
}
|
||||
};
|
||||
return nodeSystem;
|
||||
}
|
||||
function getChakraSystem() {
|
||||
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
|
||||
@@ -2298,8 +2287,8 @@ var ts;
|
||||
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
|
||||
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
|
||||
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
|
||||
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
|
||||
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
|
||||
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
|
||||
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
|
||||
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
|
||||
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
|
||||
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
|
||||
@@ -3977,12 +3966,12 @@ var ts;
|
||||
{
|
||||
name: "noUnusedLocals",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_locals
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_parameters
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -5765,7 +5754,7 @@ var ts;
|
||||
}
|
||||
ts.isExpression = isExpression;
|
||||
function isExternalModuleNameRelative(moduleName) {
|
||||
return /^\.\.?($|[\\/])/.test(moduleName);
|
||||
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
|
||||
}
|
||||
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
|
||||
function isInstantiatedModule(node, preserveConstEnums) {
|
||||
@@ -7273,24 +7262,25 @@ var ts;
|
||||
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
|
||||
}
|
||||
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
})(ts || (ts = {}));
|
||||
var ts;
|
||||
(function (ts) {
|
||||
ts.parseTime = 0;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
function createNode(kind, pos, end) {
|
||||
if (kind === 256) {
|
||||
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind === 69) {
|
||||
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind < 139) {
|
||||
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
|
||||
}
|
||||
else {
|
||||
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
|
||||
}
|
||||
@@ -7713,8 +7703,6 @@ var ts;
|
||||
var scanner = ts.createScanner(2, true);
|
||||
var disallowInAndDecoratorContext = 4194304 | 16777216;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
var sourceFile;
|
||||
var parseDiagnostics;
|
||||
@@ -7740,8 +7728,6 @@ var ts;
|
||||
}
|
||||
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
|
||||
NodeConstructor = ts.objectAllocator.getNodeConstructor();
|
||||
TokenConstructor = ts.objectAllocator.getTokenConstructor();
|
||||
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
|
||||
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
|
||||
sourceText = _sourceText;
|
||||
syntaxCursor = _syntaxCursor;
|
||||
@@ -8048,9 +8034,7 @@ var ts;
|
||||
if (!(pos >= 0)) {
|
||||
pos = scanner.getStartPos();
|
||||
}
|
||||
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
|
||||
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
|
||||
new TokenConstructor(kind, pos, pos);
|
||||
return new NodeConstructor(kind, pos, pos);
|
||||
}
|
||||
function finishNode(node, end) {
|
||||
node.end = end === undefined ? scanner.getStartPos() : end;
|
||||
@@ -11826,9 +11810,6 @@ var ts;
|
||||
case 55:
|
||||
if (canParseTag) {
|
||||
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
|
||||
if (!parentTagTerminated) {
|
||||
resumePos = scanner.getStartPos();
|
||||
}
|
||||
}
|
||||
seenAsterisk = false;
|
||||
break;
|
||||
@@ -16355,18 +16336,17 @@ var ts;
|
||||
if (declaration.kind === 235) {
|
||||
return links.type = checkExpression(declaration.expression);
|
||||
}
|
||||
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
|
||||
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
|
||||
}
|
||||
if (!pushTypeResolution(symbol, 0)) {
|
||||
return unknownType;
|
||||
}
|
||||
var type = undefined;
|
||||
if (declaration.kind === 187 ||
|
||||
declaration.kind === 172 && declaration.parent.kind === 187) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
|
||||
checkExpressionCached(decl.right) :
|
||||
checkExpressionCached(decl.parent.right); }));
|
||||
if (declaration.kind === 187) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
|
||||
}
|
||||
else if (declaration.kind === 172) {
|
||||
if (declaration.parent.kind === 187) {
|
||||
type = checkExpressionCached(declaration.parent.right);
|
||||
}
|
||||
}
|
||||
if (type === undefined) {
|
||||
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
|
||||
@@ -22873,7 +22853,7 @@ var ts;
|
||||
function getInferredClassType(symbol) {
|
||||
var links = getSymbolLinks(symbol);
|
||||
if (!links.inferredClassType) {
|
||||
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
|
||||
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
|
||||
}
|
||||
return links.inferredClassType;
|
||||
}
|
||||
@@ -24093,7 +24073,7 @@ var ts;
|
||||
checkAsyncFunctionReturnType(node);
|
||||
}
|
||||
}
|
||||
if (noUnusedIdentifiers && !node.body) {
|
||||
if (!node.body) {
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
@@ -24989,7 +24969,6 @@ var ts;
|
||||
var parameter = local_1.valueDeclaration;
|
||||
if (compilerOptions.noUnusedParameters &&
|
||||
!ts.isParameterPropertyDeclaration(parameter) &&
|
||||
!parameterIsThisKeyword(parameter) &&
|
||||
!parameterNameStartsWithUnderscore(parameter)) {
|
||||
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
|
||||
}
|
||||
@@ -25005,9 +24984,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parameterIsThisKeyword(parameter) {
|
||||
return parameter.name && parameter.name.originalKeywordKind === 97;
|
||||
}
|
||||
function parameterNameStartsWithUnderscore(parameter) {
|
||||
return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95;
|
||||
}
|
||||
@@ -25036,14 +25012,9 @@ var ts;
|
||||
function checkUnusedTypeParameters(node) {
|
||||
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
|
||||
if (node.typeParameters) {
|
||||
var symbol = getSymbolOfNode(node);
|
||||
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
|
||||
if (lastDeclaration !== node) {
|
||||
return;
|
||||
}
|
||||
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
|
||||
var typeParameter = _a[_i];
|
||||
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
|
||||
if (!typeParameter.symbol.isReferenced) {
|
||||
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
|
||||
}
|
||||
}
|
||||
@@ -26120,7 +26091,7 @@ var ts;
|
||||
ts.forEach(node.members, checkSourceElement);
|
||||
if (produceDiagnostics) {
|
||||
checkTypeForDuplicateIndexSignatures(node);
|
||||
registerForUnusedIdentifiersCheck(node);
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
function checkTypeAliasDeclaration(node) {
|
||||
@@ -30843,7 +30814,7 @@ var ts;
|
||||
writeLine();
|
||||
var sourceMappingURL = sourceMap.getSourceMappingURL();
|
||||
if (sourceMappingURL) {
|
||||
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
|
||||
write("//# sourceMappingURL=" + sourceMappingURL);
|
||||
}
|
||||
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
|
||||
sourceMap.reset();
|
||||
@@ -34493,13 +34464,13 @@ var ts;
|
||||
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
|
||||
write("export ");
|
||||
}
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
if (decoratedClassAlias !== undefined) {
|
||||
write("let " + decoratedClassAlias);
|
||||
write("" + decoratedClassAlias);
|
||||
}
|
||||
else {
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
emitDeclarationName(node);
|
||||
}
|
||||
write(" = ");
|
||||
@@ -36743,7 +36714,7 @@ var ts;
|
||||
ts.emitTime = 0;
|
||||
ts.ioReadTime = 0;
|
||||
ts.ioWriteTime = 0;
|
||||
ts.version = "2.1.0";
|
||||
ts.version = "2.0.0";
|
||||
var emptyArray = [];
|
||||
var defaultTypeRoots = ["node_modules/@types"];
|
||||
function findConfigFile(searchPath, fileExists) {
|
||||
@@ -36823,7 +36794,12 @@ var ts;
|
||||
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
|
||||
}
|
||||
function moduleHasNonRelativeName(moduleName) {
|
||||
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
|
||||
if (ts.isRootedDiskPath(moduleName)) {
|
||||
return false;
|
||||
}
|
||||
var i = moduleName.lastIndexOf("./", 1);
|
||||
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
|
||||
return !startsWithDotSlashOrDotDotSlash;
|
||||
}
|
||||
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
|
||||
var jsonContent;
|
||||
@@ -37479,22 +37455,6 @@ var ts;
|
||||
return ts.sortAndDeduplicateDiagnostics(diagnostics);
|
||||
}
|
||||
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
|
||||
function formatDiagnostics(diagnostics, host) {
|
||||
var output = "";
|
||||
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
|
||||
var diagnostic = diagnostics_1[_i];
|
||||
if (diagnostic.file) {
|
||||
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
|
||||
var fileName = diagnostic.file.fileName;
|
||||
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
|
||||
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
|
||||
}
|
||||
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
ts.formatDiagnostics = formatDiagnostics;
|
||||
function flattenDiagnosticMessageText(messageText, newLine) {
|
||||
if (typeof messageText === "string") {
|
||||
return messageText;
|
||||
@@ -37570,7 +37530,7 @@ var ts;
|
||||
var resolvedTypeReferenceDirectives = {};
|
||||
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
|
||||
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
|
||||
var currentNodeModulesDepth = 0;
|
||||
var currentNodeModulesJsDepth = 0;
|
||||
var modulesWithElidedImports = {};
|
||||
var sourceFilesFoundSearchingNodeModules = {};
|
||||
var start = new Date().getTime();
|
||||
@@ -37794,7 +37754,8 @@ var ts;
|
||||
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
|
||||
}
|
||||
function emit(sourceFile, writeFileCallback, cancellationToken) {
|
||||
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
|
||||
var _this = this;
|
||||
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
|
||||
}
|
||||
function isEmitBlocked(emitFileName) {
|
||||
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
|
||||
@@ -38201,17 +38162,8 @@ var ts;
|
||||
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
|
||||
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
|
||||
}
|
||||
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
|
||||
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
|
||||
if (!options.noResolve) {
|
||||
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
|
||||
processTypeReferenceDirectives(file_1);
|
||||
}
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
|
||||
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
@@ -38228,7 +38180,6 @@ var ts;
|
||||
});
|
||||
filesByName.set(path, file);
|
||||
if (file) {
|
||||
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
|
||||
file.path = path;
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
var existingFile = filesByNameIgnoreCase.get(path);
|
||||
@@ -38329,9 +38280,12 @@ var ts;
|
||||
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
|
||||
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth++;
|
||||
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth++;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
|
||||
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
|
||||
if (elideImport) {
|
||||
modulesWithElidedImports[file.path] = true;
|
||||
@@ -38339,8 +38293,8 @@ var ts;
|
||||
else if (shouldAddFile) {
|
||||
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
|
||||
}
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth--;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39933,7 +39887,7 @@ var ts;
|
||||
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
|
||||
}
|
||||
else {
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
|
||||
}
|
||||
}
|
||||
var isLowercase = chunk.isLowerCase;
|
||||
@@ -40105,6 +40059,14 @@ var ts;
|
||||
var str = String.fromCharCode(ch);
|
||||
return str === str.toLowerCase();
|
||||
}
|
||||
function startsWith(string, search) {
|
||||
for (var i = 0, n = search.length; i < n; i++) {
|
||||
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function indexOfIgnoringCase(string, value) {
|
||||
for (var i = 0, n = string.length - value.length; i <= n; i++) {
|
||||
if (startsWithIgnoringCase(string, value, i)) {
|
||||
@@ -41589,9 +41551,6 @@ var ts;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function shouldRescanJsxText(node) {
|
||||
return node && node.kind === 244;
|
||||
}
|
||||
function shouldRescanSlashToken(container) {
|
||||
return container.kind === 10;
|
||||
}
|
||||
@@ -41619,9 +41578,7 @@ var ts;
|
||||
? 3
|
||||
: shouldRescanJsxIdentifier(n)
|
||||
? 4
|
||||
: shouldRescanJsxText(n)
|
||||
? 5
|
||||
: 0;
|
||||
: 0;
|
||||
if (lastTokenInfo && expectedScanAction === lastScanAction) {
|
||||
return fixTokenKind(lastTokenInfo, n);
|
||||
}
|
||||
@@ -41649,10 +41606,6 @@ var ts;
|
||||
currentToken = scanner.scanJsxIdentifier();
|
||||
lastScanAction = 4;
|
||||
}
|
||||
else if (expectedScanAction === 5) {
|
||||
currentToken = scanner.reScanJsxToken();
|
||||
lastScanAction = 5;
|
||||
}
|
||||
else {
|
||||
lastScanAction = 0;
|
||||
}
|
||||
@@ -43901,20 +43854,19 @@ var ts;
|
||||
"version"
|
||||
];
|
||||
var jsDocCompletionEntries;
|
||||
function createNode(kind, pos, end, parent) {
|
||||
var node = kind >= 139 ? new NodeObject(kind, pos, end) :
|
||||
kind === 69 ? new IdentifierObject(kind, pos, end) :
|
||||
new TokenObject(kind, pos, end);
|
||||
function createNode(kind, pos, end, flags, parent) {
|
||||
var node = new NodeObject(kind, pos, end);
|
||||
node.flags = flags;
|
||||
node.parent = parent;
|
||||
return node;
|
||||
}
|
||||
var NodeObject = (function () {
|
||||
function NodeObject(kind, pos, end) {
|
||||
this.kind = kind;
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0;
|
||||
this.parent = undefined;
|
||||
this.kind = kind;
|
||||
}
|
||||
NodeObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
@@ -43949,14 +43901,14 @@ var ts;
|
||||
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
|
||||
var textPos = scanner.getTextPos();
|
||||
if (textPos <= end) {
|
||||
nodes.push(createNode(token, pos, textPos, this));
|
||||
nodes.push(createNode(token, pos, textPos, 0, this));
|
||||
}
|
||||
pos = textPos;
|
||||
}
|
||||
return pos;
|
||||
};
|
||||
NodeObject.prototype.createSyntaxList = function (nodes) {
|
||||
var list = createNode(282, nodes.pos, nodes.end, this);
|
||||
var list = createNode(282, nodes.pos, nodes.end, 0, this);
|
||||
list._children = [];
|
||||
var pos = nodes.pos;
|
||||
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
|
||||
@@ -44041,73 +43993,6 @@ var ts;
|
||||
};
|
||||
return NodeObject;
|
||||
}());
|
||||
var TokenOrIdentifierObject = (function () {
|
||||
function TokenOrIdentifierObject(pos, end) {
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0;
|
||||
this.parent = undefined;
|
||||
}
|
||||
TokenOrIdentifierObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
|
||||
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullStart = function () {
|
||||
return this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getEnd = function () {
|
||||
return this.end;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
|
||||
return this.getEnd() - this.getStart(sourceFile);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullWidth = function () {
|
||||
return this.end - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
|
||||
return this.getStart(sourceFile) - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
|
||||
return 0;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
|
||||
return emptyArray;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
return TokenOrIdentifierObject;
|
||||
}());
|
||||
var TokenObject = (function (_super) {
|
||||
__extends(TokenObject, _super);
|
||||
function TokenObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
this.kind = kind;
|
||||
}
|
||||
return TokenObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
var IdentifierObject = (function (_super) {
|
||||
__extends(IdentifierObject, _super);
|
||||
function IdentifierObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
}
|
||||
return IdentifierObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
IdentifierObject.prototype.kind = 69;
|
||||
var SymbolObject = (function () {
|
||||
function SymbolObject(flags, name) {
|
||||
this.flags = flags;
|
||||
@@ -49788,8 +49673,6 @@ var ts;
|
||||
function initializeServices() {
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return NodeObject; },
|
||||
getTokenConstructor: function () { return TokenObject; },
|
||||
getIdentifierConstructor: function () { return IdentifierObject; },
|
||||
getSourceFileConstructor: function () { return SourceFileObject; },
|
||||
getSymbolConstructor: function () { return SymbolObject; },
|
||||
getTypeConstructor: function () { return TypeObject; },
|
||||
@@ -50910,6 +50793,7 @@ var ts;
|
||||
if (isOpen === void 0) { isOpen = false; }
|
||||
this.host = host;
|
||||
this.fileName = fileName;
|
||||
this.content = content;
|
||||
this.isOpen = isOpen;
|
||||
this.children = [];
|
||||
this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
|
||||
@@ -52535,7 +52419,7 @@ var ts;
|
||||
done: false,
|
||||
leaf: function (relativeStart, relativeLength, ll) {
|
||||
if (!f(ll, relativeStart, relativeLength)) {
|
||||
walkFns.done = true;
|
||||
this.done = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -52951,7 +52835,7 @@ var ts;
|
||||
server.LineLeaf = LineLeaf;
|
||||
})(server = ts.server || (ts.server = {}));
|
||||
})(ts || (ts = {}));
|
||||
var debugObjectHost = new Function("return this")();
|
||||
var debugObjectHost = this;
|
||||
var ts;
|
||||
(function (ts) {
|
||||
function logInternalError(logger, err) {
|
||||
@@ -53079,7 +52963,7 @@ var ts;
|
||||
return this.shimHost.getCurrentDirectory();
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
|
||||
return JSON.parse(this.shimHost.getDirectories(path));
|
||||
return this.shimHost.getDirectories(path);
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
|
||||
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
|
||||
|
||||
Vendored
+4
-10
@@ -409,10 +409,7 @@ declare namespace ts {
|
||||
interface ModifiersArray extends NodeArray<Modifier> {
|
||||
flags: NodeFlags;
|
||||
}
|
||||
interface Token extends Node {
|
||||
__tokenTag: any;
|
||||
}
|
||||
interface Modifier extends Token {
|
||||
interface Modifier extends Node {
|
||||
}
|
||||
interface Identifier extends PrimaryExpression {
|
||||
text: string;
|
||||
@@ -1699,6 +1696,7 @@ declare namespace ts {
|
||||
getCancellationToken?(): CancellationToken;
|
||||
getDefaultLibFileName(options: CompilerOptions): string;
|
||||
getDefaultLibLocation?(): string;
|
||||
getDefaultTypeDirectiveNames?(rootPath: string): string[];
|
||||
writeFile: WriteFileCallback;
|
||||
getCurrentDirectory(): string;
|
||||
getDirectories(path: string): string[];
|
||||
@@ -1844,6 +1842,8 @@ 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;
|
||||
@@ -1868,12 +1868,6 @@ declare namespace ts {
|
||||
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
|
||||
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
|
||||
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
|
||||
interface FormatDiagnosticsHost {
|
||||
getCurrentDirectory(): string;
|
||||
getCanonicalFileName(fileName: string): string;
|
||||
getNewLine(): string;
|
||||
}
|
||||
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
|
||||
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
|
||||
/**
|
||||
* Given a set of options and a set of root files, returns the set of type directive names
|
||||
|
||||
+83
-210
@@ -1756,19 +1756,10 @@ var ts;
|
||||
return true;
|
||||
}
|
||||
ts.containsPath = containsPath;
|
||||
/* @internal */
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
/* @internal */
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
function fileExtensionIs(path, extension) {
|
||||
return path.length > extension.length && endsWith(path, extension);
|
||||
var pathLen = path.length;
|
||||
var extLen = extension.length;
|
||||
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
|
||||
}
|
||||
ts.fileExtensionIs = fileExtensionIs;
|
||||
function fileExtensionIsAny(path, extensions) {
|
||||
@@ -2079,8 +2070,6 @@ var ts;
|
||||
}
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return Node; },
|
||||
getTokenConstructor: function () { return Node; },
|
||||
getIdentifierConstructor: function () { return Node; },
|
||||
getSourceFileConstructor: function () { return Node; },
|
||||
getSymbolConstructor: function () { return Symbol; },
|
||||
getTypeConstructor: function () { return Type; },
|
||||
@@ -2227,7 +2216,7 @@ var ts;
|
||||
function readDirectory(path, extensions, excludes, includes) {
|
||||
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
|
||||
}
|
||||
var wscriptSystem = {
|
||||
return {
|
||||
args: args,
|
||||
newLine: "\r\n",
|
||||
useCaseSensitiveFileNames: false,
|
||||
@@ -2246,7 +2235,7 @@ var ts;
|
||||
return fso.FolderExists(path);
|
||||
},
|
||||
createDirectory: function (directoryName) {
|
||||
if (!wscriptSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
fso.CreateFolder(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -2266,7 +2255,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
};
|
||||
return wscriptSystem;
|
||||
}
|
||||
function getNodeSystem() {
|
||||
var _fs = require("fs");
|
||||
@@ -2456,7 +2444,7 @@ var ts;
|
||||
function getDirectories(path) {
|
||||
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
|
||||
}
|
||||
var nodeSystem = {
|
||||
return {
|
||||
args: process.argv.slice(2),
|
||||
newLine: _os.EOL,
|
||||
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
|
||||
@@ -2512,7 +2500,7 @@ var ts;
|
||||
fileExists: fileExists,
|
||||
directoryExists: directoryExists,
|
||||
createDirectory: function (directoryName) {
|
||||
if (!nodeSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
_fs.mkdirSync(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -2560,7 +2548,6 @@ var ts;
|
||||
return _fs.realpathSync(path);
|
||||
}
|
||||
};
|
||||
return nodeSystem;
|
||||
}
|
||||
function getChakraSystem() {
|
||||
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
|
||||
@@ -3317,8 +3304,8 @@ var ts;
|
||||
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
|
||||
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
|
||||
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
|
||||
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
|
||||
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
|
||||
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
|
||||
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
|
||||
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
|
||||
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
|
||||
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
|
||||
@@ -6166,7 +6153,7 @@ var ts;
|
||||
function isExternalModuleNameRelative(moduleName) {
|
||||
// TypeScript 1.0 spec (April 2014): 11.2.1
|
||||
// An external module name is "relative" if the first term is "." or "..".
|
||||
return /^\.\.?($|[\\/])/.test(moduleName);
|
||||
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
|
||||
}
|
||||
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
|
||||
function isInstantiatedModule(node, preserveConstEnums) {
|
||||
@@ -7929,6 +7916,15 @@ var ts;
|
||||
return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent);
|
||||
}
|
||||
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
})(ts || (ts = {}));
|
||||
/// <reference path="utilities.ts"/>
|
||||
/// <reference path="scanner.ts"/>
|
||||
@@ -7936,19 +7932,11 @@ var ts;
|
||||
(function (ts) {
|
||||
/* @internal */ ts.parseTime = 0;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
function createNode(kind, pos, end) {
|
||||
if (kind === 256 /* SourceFile */) {
|
||||
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind === 69 /* Identifier */) {
|
||||
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind < 139 /* FirstNode */) {
|
||||
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
|
||||
}
|
||||
else {
|
||||
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
|
||||
}
|
||||
@@ -8398,8 +8386,6 @@ var ts;
|
||||
var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */;
|
||||
// capture constructors in 'initializeState' to avoid null checks
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
var sourceFile;
|
||||
var parseDiagnostics;
|
||||
@@ -8499,8 +8485,6 @@ var ts;
|
||||
}
|
||||
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
|
||||
NodeConstructor = ts.objectAllocator.getNodeConstructor();
|
||||
TokenConstructor = ts.objectAllocator.getTokenConstructor();
|
||||
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
|
||||
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
|
||||
sourceText = _sourceText;
|
||||
syntaxCursor = _syntaxCursor;
|
||||
@@ -8871,9 +8855,7 @@ var ts;
|
||||
if (!(pos >= 0)) {
|
||||
pos = scanner.getStartPos();
|
||||
}
|
||||
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
|
||||
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
|
||||
new TokenConstructor(kind, pos, pos);
|
||||
return new NodeConstructor(kind, pos, pos);
|
||||
}
|
||||
function finishNode(node, end) {
|
||||
node.end = end === undefined ? scanner.getStartPos() : end;
|
||||
@@ -13542,9 +13524,6 @@ var ts;
|
||||
case 55 /* AtToken */:
|
||||
if (canParseTag) {
|
||||
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
|
||||
if (!parentTagTerminated) {
|
||||
resumePos = scanner.getStartPos();
|
||||
}
|
||||
}
|
||||
seenAsterisk = false;
|
||||
break;
|
||||
@@ -19012,24 +18991,22 @@ var ts;
|
||||
if (declaration.kind === 235 /* ExportAssignment */) {
|
||||
return links.type = checkExpression(declaration.expression);
|
||||
}
|
||||
if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) {
|
||||
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
|
||||
}
|
||||
// Handle variable, parameter or property
|
||||
if (!pushTypeResolution(symbol, 0 /* Type */)) {
|
||||
return unknownType;
|
||||
}
|
||||
var type = undefined;
|
||||
// Handle certain special assignment kinds, which happen to union across multiple declarations:
|
||||
// * module.exports = expr
|
||||
// * exports.p = expr
|
||||
// * this.p = expr
|
||||
// * className.prototype.method = expr
|
||||
if (declaration.kind === 187 /* BinaryExpression */ ||
|
||||
declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ?
|
||||
checkExpressionCached(decl.right) :
|
||||
checkExpressionCached(decl.parent.right); }));
|
||||
// Handle module.exports = expr or this.p = expr
|
||||
if (declaration.kind === 187 /* BinaryExpression */) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
|
||||
}
|
||||
else if (declaration.kind === 172 /* PropertyAccessExpression */) {
|
||||
// Declarations only exist for property access expressions for certain
|
||||
// special assignment kinds
|
||||
if (declaration.parent.kind === 187 /* BinaryExpression */) {
|
||||
// Handle exports.p = expr or className.prototype.method = expr
|
||||
type = checkExpressionCached(declaration.parent.right);
|
||||
}
|
||||
}
|
||||
if (type === undefined) {
|
||||
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
|
||||
@@ -26784,7 +26761,7 @@ var ts;
|
||||
function getInferredClassType(symbol) {
|
||||
var links = getSymbolLinks(symbol);
|
||||
if (!links.inferredClassType) {
|
||||
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
|
||||
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
|
||||
}
|
||||
return links.inferredClassType;
|
||||
}
|
||||
@@ -28225,7 +28202,7 @@ var ts;
|
||||
checkAsyncFunctionReturnType(node);
|
||||
}
|
||||
}
|
||||
if (noUnusedIdentifiers && !node.body) {
|
||||
if (!node.body) {
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
@@ -29364,7 +29341,6 @@ var ts;
|
||||
var parameter = local_1.valueDeclaration;
|
||||
if (compilerOptions.noUnusedParameters &&
|
||||
!ts.isParameterPropertyDeclaration(parameter) &&
|
||||
!parameterIsThisKeyword(parameter) &&
|
||||
!parameterNameStartsWithUnderscore(parameter)) {
|
||||
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
|
||||
}
|
||||
@@ -29380,9 +29356,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parameterIsThisKeyword(parameter) {
|
||||
return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */;
|
||||
}
|
||||
function parameterNameStartsWithUnderscore(parameter) {
|
||||
return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */;
|
||||
}
|
||||
@@ -29411,16 +29384,9 @@ var ts;
|
||||
function checkUnusedTypeParameters(node) {
|
||||
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
|
||||
if (node.typeParameters) {
|
||||
// Only report errors on the last declaration for the type parameter container;
|
||||
// this ensures that all uses have been accounted for.
|
||||
var symbol = getSymbolOfNode(node);
|
||||
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
|
||||
if (lastDeclaration !== node) {
|
||||
return;
|
||||
}
|
||||
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
|
||||
var typeParameter = _a[_i];
|
||||
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
|
||||
if (!typeParameter.symbol.isReferenced) {
|
||||
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
|
||||
}
|
||||
}
|
||||
@@ -30753,7 +30719,7 @@ var ts;
|
||||
ts.forEach(node.members, checkSourceElement);
|
||||
if (produceDiagnostics) {
|
||||
checkTypeForDuplicateIndexSignatures(node);
|
||||
registerForUnusedIdentifiersCheck(node);
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
function checkTypeAliasDeclaration(node) {
|
||||
@@ -36017,7 +35983,7 @@ var ts;
|
||||
writeLine();
|
||||
var sourceMappingURL = sourceMap.getSourceMappingURL();
|
||||
if (sourceMappingURL) {
|
||||
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
|
||||
write("//# sourceMappingURL=" + sourceMappingURL);
|
||||
}
|
||||
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
|
||||
// reset the state
|
||||
@@ -37914,7 +37880,7 @@ var ts;
|
||||
* if we should also export the value after its it changed
|
||||
* - check if node is a source level declaration to emit it differently,
|
||||
* i.e non-exported variable statement 'var x = 1' is hoisted so
|
||||
* when we emit variable statement 'var' should be dropped.
|
||||
* we we emit variable statement 'var' should be dropped.
|
||||
*/
|
||||
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
|
||||
if (!node || !isCurrentFileSystemExternalModule()) {
|
||||
@@ -40381,13 +40347,13 @@ var ts;
|
||||
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
|
||||
write("export ");
|
||||
}
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
if (decoratedClassAlias !== undefined) {
|
||||
write("let " + decoratedClassAlias);
|
||||
write("" + decoratedClassAlias);
|
||||
}
|
||||
else {
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
emitDeclarationName(node);
|
||||
}
|
||||
write(" = ");
|
||||
@@ -40406,9 +40372,7 @@ var ts;
|
||||
//
|
||||
// We'll emit:
|
||||
//
|
||||
// let C_1 = class C{};
|
||||
// C_1.a = 1;
|
||||
// C_1.b = 2; // so forth and so on
|
||||
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
|
||||
//
|
||||
// This keeps the expression as an expression, while ensuring that the static parts
|
||||
// of it have been initialized by the time it is used.
|
||||
@@ -42972,7 +42936,7 @@ var ts;
|
||||
/* @internal */ ts.ioReadTime = 0;
|
||||
/* @internal */ ts.ioWriteTime = 0;
|
||||
/** The version of the TypeScript compiler release */
|
||||
ts.version = "2.1.0";
|
||||
ts.version = "2.0.0";
|
||||
var emptyArray = [];
|
||||
var defaultTypeRoots = ["node_modules/@types"];
|
||||
function findConfigFile(searchPath, fileExists) {
|
||||
@@ -43061,7 +43025,12 @@ var ts;
|
||||
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
|
||||
}
|
||||
function moduleHasNonRelativeName(moduleName) {
|
||||
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
|
||||
if (ts.isRootedDiskPath(moduleName)) {
|
||||
return false;
|
||||
}
|
||||
var i = moduleName.lastIndexOf("./", 1);
|
||||
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */);
|
||||
return !startsWithDotSlashOrDotDotSlash;
|
||||
}
|
||||
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
|
||||
var jsonContent;
|
||||
@@ -43828,22 +43797,6 @@ var ts;
|
||||
return ts.sortAndDeduplicateDiagnostics(diagnostics);
|
||||
}
|
||||
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
|
||||
function formatDiagnostics(diagnostics, host) {
|
||||
var output = "";
|
||||
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
|
||||
var diagnostic = diagnostics_1[_i];
|
||||
if (diagnostic.file) {
|
||||
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
|
||||
var fileName = diagnostic.file.fileName;
|
||||
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
|
||||
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
|
||||
}
|
||||
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
ts.formatDiagnostics = formatDiagnostics;
|
||||
function flattenDiagnosticMessageText(messageText, newLine) {
|
||||
if (typeof messageText === "string") {
|
||||
return messageText;
|
||||
@@ -43936,11 +43889,11 @@ var ts;
|
||||
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
|
||||
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
|
||||
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
|
||||
var currentNodeModulesDepth = 0;
|
||||
var currentNodeModulesJsDepth = 0;
|
||||
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
|
||||
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
|
||||
var modulesWithElidedImports = {};
|
||||
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
|
||||
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
|
||||
var sourceFilesFoundSearchingNodeModules = {};
|
||||
var start = new Date().getTime();
|
||||
host = host || createCompilerHost(options);
|
||||
@@ -44197,7 +44150,8 @@ var ts;
|
||||
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
|
||||
}
|
||||
function emit(sourceFile, writeFileCallback, cancellationToken) {
|
||||
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
|
||||
var _this = this;
|
||||
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
|
||||
}
|
||||
function isEmitBlocked(emitFileName) {
|
||||
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
|
||||
@@ -44649,19 +44603,9 @@ var ts;
|
||||
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
|
||||
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
|
||||
}
|
||||
// If the file was previously found via a node_modules search, but is now being processed as a root file,
|
||||
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
|
||||
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
|
||||
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
|
||||
if (!options.noResolve) {
|
||||
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
|
||||
processTypeReferenceDirectives(file_1);
|
||||
}
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
|
||||
// See if we need to reprocess the imports due to prior skipped imports
|
||||
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
@@ -44679,7 +44623,6 @@ var ts;
|
||||
});
|
||||
filesByName.set(path, file);
|
||||
if (file) {
|
||||
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
|
||||
file.path = path;
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
|
||||
@@ -44794,9 +44737,12 @@ var ts;
|
||||
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
|
||||
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth++;
|
||||
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth++;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
|
||||
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
|
||||
if (elideImport) {
|
||||
modulesWithElidedImports[file.path] = true;
|
||||
@@ -44805,8 +44751,8 @@ var ts;
|
||||
findSourceFile(resolution.resolvedFileName, resolvedPath,
|
||||
/*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
|
||||
}
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth--;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45144,12 +45090,12 @@ var ts;
|
||||
{
|
||||
name: "noUnusedLocals",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_locals
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_parameters
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -47141,7 +47087,7 @@ var ts;
|
||||
else {
|
||||
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
|
||||
// manner. If it does, return that there was a prefix match.
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
|
||||
}
|
||||
}
|
||||
var isLowercase = chunk.isLowerCase;
|
||||
@@ -47407,6 +47353,14 @@ var ts;
|
||||
var str = String.fromCharCode(ch);
|
||||
return str === str.toLowerCase();
|
||||
}
|
||||
function startsWith(string, search) {
|
||||
for (var i = 0, n = search.length; i < n; i++) {
|
||||
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Assumes 'value' is already lowercase.
|
||||
function indexOfIgnoringCase(string, value) {
|
||||
for (var i = 0, n = string.length - value.length; i <= n; i++) {
|
||||
@@ -49251,7 +49205,6 @@ var ts;
|
||||
ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
|
||||
ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
|
||||
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
|
||||
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
|
||||
})(ScanAction || (ScanAction = {}));
|
||||
function getFormattingScanner(sourceFile, startPos, endPos) {
|
||||
ts.Debug.assert(scanner === undefined);
|
||||
@@ -49343,9 +49296,6 @@ var ts;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function shouldRescanJsxText(node) {
|
||||
return node && node.kind === 244 /* JsxText */;
|
||||
}
|
||||
function shouldRescanSlashToken(container) {
|
||||
return container.kind === 10 /* RegularExpressionLiteral */;
|
||||
}
|
||||
@@ -49376,9 +49326,7 @@ var ts;
|
||||
? 3 /* RescanTemplateToken */
|
||||
: shouldRescanJsxIdentifier(n)
|
||||
? 4 /* RescanJsxIdentifier */
|
||||
: shouldRescanJsxText(n)
|
||||
? 5 /* RescanJsxText */
|
||||
: 0 /* Scan */;
|
||||
: 0 /* Scan */;
|
||||
if (lastTokenInfo && expectedScanAction === lastScanAction) {
|
||||
// readTokenInfo was called before with the same expected scan action.
|
||||
// No need to re-scan text, return existing 'lastTokenInfo'
|
||||
@@ -49413,10 +49361,6 @@ var ts;
|
||||
currentToken = scanner.scanJsxIdentifier();
|
||||
lastScanAction = 4 /* RescanJsxIdentifier */;
|
||||
}
|
||||
else if (expectedScanAction === 5 /* RescanJsxText */) {
|
||||
currentToken = scanner.reScanJsxToken();
|
||||
lastScanAction = 5 /* RescanJsxText */;
|
||||
}
|
||||
else {
|
||||
lastScanAction = 0 /* Scan */;
|
||||
}
|
||||
@@ -52089,20 +52033,19 @@ var ts;
|
||||
"version"
|
||||
];
|
||||
var jsDocCompletionEntries;
|
||||
function createNode(kind, pos, end, parent) {
|
||||
var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) :
|
||||
kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) :
|
||||
new TokenObject(kind, pos, end);
|
||||
function createNode(kind, pos, end, flags, parent) {
|
||||
var node = new NodeObject(kind, pos, end);
|
||||
node.flags = flags;
|
||||
node.parent = parent;
|
||||
return node;
|
||||
}
|
||||
var NodeObject = (function () {
|
||||
function NodeObject(kind, pos, end) {
|
||||
this.kind = kind;
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0 /* None */;
|
||||
this.parent = undefined;
|
||||
this.kind = kind;
|
||||
}
|
||||
NodeObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
@@ -52137,14 +52080,14 @@ var ts;
|
||||
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
|
||||
var textPos = scanner.getTextPos();
|
||||
if (textPos <= end) {
|
||||
nodes.push(createNode(token, pos, textPos, this));
|
||||
nodes.push(createNode(token, pos, textPos, 0, this));
|
||||
}
|
||||
pos = textPos;
|
||||
}
|
||||
return pos;
|
||||
};
|
||||
NodeObject.prototype.createSyntaxList = function (nodes) {
|
||||
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
|
||||
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
|
||||
list._children = [];
|
||||
var pos = nodes.pos;
|
||||
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
|
||||
@@ -52230,74 +52173,6 @@ var ts;
|
||||
};
|
||||
return NodeObject;
|
||||
}());
|
||||
var TokenOrIdentifierObject = (function () {
|
||||
function TokenOrIdentifierObject(pos, end) {
|
||||
// Set properties in same order as NodeObject
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0 /* None */;
|
||||
this.parent = undefined;
|
||||
}
|
||||
TokenOrIdentifierObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
|
||||
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullStart = function () {
|
||||
return this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getEnd = function () {
|
||||
return this.end;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
|
||||
return this.getEnd() - this.getStart(sourceFile);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullWidth = function () {
|
||||
return this.end - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
|
||||
return this.getStart(sourceFile) - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
|
||||
return 0;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
|
||||
return emptyArray;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
return TokenOrIdentifierObject;
|
||||
}());
|
||||
var TokenObject = (function (_super) {
|
||||
__extends(TokenObject, _super);
|
||||
function TokenObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
this.kind = kind;
|
||||
}
|
||||
return TokenObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
var IdentifierObject = (function (_super) {
|
||||
__extends(IdentifierObject, _super);
|
||||
function IdentifierObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
}
|
||||
return IdentifierObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
IdentifierObject.prototype.kind = 69 /* Identifier */;
|
||||
var SymbolObject = (function () {
|
||||
function SymbolObject(flags, name) {
|
||||
this.flags = flags;
|
||||
@@ -59062,8 +58937,6 @@ var ts;
|
||||
function initializeServices() {
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return NodeObject; },
|
||||
getTokenConstructor: function () { return TokenObject; },
|
||||
getIdentifierConstructor: function () { return IdentifierObject; },
|
||||
getSourceFileConstructor: function () { return SourceFileObject; },
|
||||
getSymbolConstructor: function () { return SymbolObject; },
|
||||
getTypeConstructor: function () { return TypeObject; },
|
||||
@@ -59689,7 +59562,7 @@ var ts;
|
||||
//
|
||||
/// <reference path='services.ts' />
|
||||
/* @internal */
|
||||
var debugObjectHost = new Function("return this")();
|
||||
var debugObjectHost = this;
|
||||
// We need to use 'null' to interface with the managed side.
|
||||
/* tslint:disable:no-null-keyword */
|
||||
/* tslint:disable:no-in-operator */
|
||||
@@ -59828,7 +59701,7 @@ var ts;
|
||||
return this.shimHost.getCurrentDirectory();
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
|
||||
return JSON.parse(this.shimHost.getDirectories(path));
|
||||
return this.shimHost.getDirectories(path);
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
|
||||
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
|
||||
|
||||
Vendored
+4
-10
@@ -409,10 +409,7 @@ declare namespace ts {
|
||||
interface ModifiersArray extends NodeArray<Modifier> {
|
||||
flags: NodeFlags;
|
||||
}
|
||||
interface Token extends Node {
|
||||
__tokenTag: any;
|
||||
}
|
||||
interface Modifier extends Token {
|
||||
interface Modifier extends Node {
|
||||
}
|
||||
interface Identifier extends PrimaryExpression {
|
||||
text: string;
|
||||
@@ -1699,6 +1696,7 @@ declare namespace ts {
|
||||
getCancellationToken?(): CancellationToken;
|
||||
getDefaultLibFileName(options: CompilerOptions): string;
|
||||
getDefaultLibLocation?(): string;
|
||||
getDefaultTypeDirectiveNames?(rootPath: string): string[];
|
||||
writeFile: WriteFileCallback;
|
||||
getCurrentDirectory(): string;
|
||||
getDirectories(path: string): string[];
|
||||
@@ -1844,6 +1842,8 @@ 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;
|
||||
@@ -1868,12 +1868,6 @@ declare namespace ts {
|
||||
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
|
||||
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
|
||||
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
|
||||
interface FormatDiagnosticsHost {
|
||||
getCurrentDirectory(): string;
|
||||
getCanonicalFileName(fileName: string): string;
|
||||
getNewLine(): string;
|
||||
}
|
||||
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
|
||||
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
|
||||
/**
|
||||
* Given a set of options and a set of root files, returns the set of type directive names
|
||||
|
||||
+83
-210
@@ -1756,19 +1756,10 @@ var ts;
|
||||
return true;
|
||||
}
|
||||
ts.containsPath = containsPath;
|
||||
/* @internal */
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
/* @internal */
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
function fileExtensionIs(path, extension) {
|
||||
return path.length > extension.length && endsWith(path, extension);
|
||||
var pathLen = path.length;
|
||||
var extLen = extension.length;
|
||||
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
|
||||
}
|
||||
ts.fileExtensionIs = fileExtensionIs;
|
||||
function fileExtensionIsAny(path, extensions) {
|
||||
@@ -2079,8 +2070,6 @@ var ts;
|
||||
}
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return Node; },
|
||||
getTokenConstructor: function () { return Node; },
|
||||
getIdentifierConstructor: function () { return Node; },
|
||||
getSourceFileConstructor: function () { return Node; },
|
||||
getSymbolConstructor: function () { return Symbol; },
|
||||
getTypeConstructor: function () { return Type; },
|
||||
@@ -2227,7 +2216,7 @@ var ts;
|
||||
function readDirectory(path, extensions, excludes, includes) {
|
||||
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
|
||||
}
|
||||
var wscriptSystem = {
|
||||
return {
|
||||
args: args,
|
||||
newLine: "\r\n",
|
||||
useCaseSensitiveFileNames: false,
|
||||
@@ -2246,7 +2235,7 @@ var ts;
|
||||
return fso.FolderExists(path);
|
||||
},
|
||||
createDirectory: function (directoryName) {
|
||||
if (!wscriptSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
fso.CreateFolder(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -2266,7 +2255,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
};
|
||||
return wscriptSystem;
|
||||
}
|
||||
function getNodeSystem() {
|
||||
var _fs = require("fs");
|
||||
@@ -2456,7 +2444,7 @@ var ts;
|
||||
function getDirectories(path) {
|
||||
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
|
||||
}
|
||||
var nodeSystem = {
|
||||
return {
|
||||
args: process.argv.slice(2),
|
||||
newLine: _os.EOL,
|
||||
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
|
||||
@@ -2512,7 +2500,7 @@ var ts;
|
||||
fileExists: fileExists,
|
||||
directoryExists: directoryExists,
|
||||
createDirectory: function (directoryName) {
|
||||
if (!nodeSystem.directoryExists(directoryName)) {
|
||||
if (!this.directoryExists(directoryName)) {
|
||||
_fs.mkdirSync(directoryName);
|
||||
}
|
||||
},
|
||||
@@ -2560,7 +2548,6 @@ var ts;
|
||||
return _fs.realpathSync(path);
|
||||
}
|
||||
};
|
||||
return nodeSystem;
|
||||
}
|
||||
function getChakraSystem() {
|
||||
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
|
||||
@@ -3317,8 +3304,8 @@ var ts;
|
||||
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
|
||||
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
|
||||
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
|
||||
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
|
||||
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
|
||||
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
|
||||
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
|
||||
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
|
||||
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
|
||||
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
|
||||
@@ -6166,7 +6153,7 @@ var ts;
|
||||
function isExternalModuleNameRelative(moduleName) {
|
||||
// TypeScript 1.0 spec (April 2014): 11.2.1
|
||||
// An external module name is "relative" if the first term is "." or "..".
|
||||
return /^\.\.?($|[\\/])/.test(moduleName);
|
||||
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
|
||||
}
|
||||
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
|
||||
function isInstantiatedModule(node, preserveConstEnums) {
|
||||
@@ -7929,6 +7916,15 @@ var ts;
|
||||
return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent);
|
||||
}
|
||||
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
|
||||
function startsWith(str, prefix) {
|
||||
return str.lastIndexOf(prefix, 0) === 0;
|
||||
}
|
||||
ts.startsWith = startsWith;
|
||||
function endsWith(str, suffix) {
|
||||
var expectedPos = str.length - suffix.length;
|
||||
return str.indexOf(suffix, expectedPos) === expectedPos;
|
||||
}
|
||||
ts.endsWith = endsWith;
|
||||
})(ts || (ts = {}));
|
||||
/// <reference path="utilities.ts"/>
|
||||
/// <reference path="scanner.ts"/>
|
||||
@@ -7936,19 +7932,11 @@ var ts;
|
||||
(function (ts) {
|
||||
/* @internal */ ts.parseTime = 0;
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
function createNode(kind, pos, end) {
|
||||
if (kind === 256 /* SourceFile */) {
|
||||
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind === 69 /* Identifier */) {
|
||||
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
|
||||
}
|
||||
else if (kind < 139 /* FirstNode */) {
|
||||
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
|
||||
}
|
||||
else {
|
||||
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
|
||||
}
|
||||
@@ -8398,8 +8386,6 @@ var ts;
|
||||
var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */;
|
||||
// capture constructors in 'initializeState' to avoid null checks
|
||||
var NodeConstructor;
|
||||
var TokenConstructor;
|
||||
var IdentifierConstructor;
|
||||
var SourceFileConstructor;
|
||||
var sourceFile;
|
||||
var parseDiagnostics;
|
||||
@@ -8499,8 +8485,6 @@ var ts;
|
||||
}
|
||||
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
|
||||
NodeConstructor = ts.objectAllocator.getNodeConstructor();
|
||||
TokenConstructor = ts.objectAllocator.getTokenConstructor();
|
||||
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
|
||||
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
|
||||
sourceText = _sourceText;
|
||||
syntaxCursor = _syntaxCursor;
|
||||
@@ -8871,9 +8855,7 @@ var ts;
|
||||
if (!(pos >= 0)) {
|
||||
pos = scanner.getStartPos();
|
||||
}
|
||||
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
|
||||
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
|
||||
new TokenConstructor(kind, pos, pos);
|
||||
return new NodeConstructor(kind, pos, pos);
|
||||
}
|
||||
function finishNode(node, end) {
|
||||
node.end = end === undefined ? scanner.getStartPos() : end;
|
||||
@@ -13542,9 +13524,6 @@ var ts;
|
||||
case 55 /* AtToken */:
|
||||
if (canParseTag) {
|
||||
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
|
||||
if (!parentTagTerminated) {
|
||||
resumePos = scanner.getStartPos();
|
||||
}
|
||||
}
|
||||
seenAsterisk = false;
|
||||
break;
|
||||
@@ -19012,24 +18991,22 @@ var ts;
|
||||
if (declaration.kind === 235 /* ExportAssignment */) {
|
||||
return links.type = checkExpression(declaration.expression);
|
||||
}
|
||||
if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) {
|
||||
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
|
||||
}
|
||||
// Handle variable, parameter or property
|
||||
if (!pushTypeResolution(symbol, 0 /* Type */)) {
|
||||
return unknownType;
|
||||
}
|
||||
var type = undefined;
|
||||
// Handle certain special assignment kinds, which happen to union across multiple declarations:
|
||||
// * module.exports = expr
|
||||
// * exports.p = expr
|
||||
// * this.p = expr
|
||||
// * className.prototype.method = expr
|
||||
if (declaration.kind === 187 /* BinaryExpression */ ||
|
||||
declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ?
|
||||
checkExpressionCached(decl.right) :
|
||||
checkExpressionCached(decl.parent.right); }));
|
||||
// Handle module.exports = expr or this.p = expr
|
||||
if (declaration.kind === 187 /* BinaryExpression */) {
|
||||
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
|
||||
}
|
||||
else if (declaration.kind === 172 /* PropertyAccessExpression */) {
|
||||
// Declarations only exist for property access expressions for certain
|
||||
// special assignment kinds
|
||||
if (declaration.parent.kind === 187 /* BinaryExpression */) {
|
||||
// Handle exports.p = expr or className.prototype.method = expr
|
||||
type = checkExpressionCached(declaration.parent.right);
|
||||
}
|
||||
}
|
||||
if (type === undefined) {
|
||||
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
|
||||
@@ -26784,7 +26761,7 @@ var ts;
|
||||
function getInferredClassType(symbol) {
|
||||
var links = getSymbolLinks(symbol);
|
||||
if (!links.inferredClassType) {
|
||||
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
|
||||
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
|
||||
}
|
||||
return links.inferredClassType;
|
||||
}
|
||||
@@ -28225,7 +28202,7 @@ var ts;
|
||||
checkAsyncFunctionReturnType(node);
|
||||
}
|
||||
}
|
||||
if (noUnusedIdentifiers && !node.body) {
|
||||
if (!node.body) {
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
@@ -29364,7 +29341,6 @@ var ts;
|
||||
var parameter = local_1.valueDeclaration;
|
||||
if (compilerOptions.noUnusedParameters &&
|
||||
!ts.isParameterPropertyDeclaration(parameter) &&
|
||||
!parameterIsThisKeyword(parameter) &&
|
||||
!parameterNameStartsWithUnderscore(parameter)) {
|
||||
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
|
||||
}
|
||||
@@ -29380,9 +29356,6 @@ var ts;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parameterIsThisKeyword(parameter) {
|
||||
return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */;
|
||||
}
|
||||
function parameterNameStartsWithUnderscore(parameter) {
|
||||
return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */;
|
||||
}
|
||||
@@ -29411,16 +29384,9 @@ var ts;
|
||||
function checkUnusedTypeParameters(node) {
|
||||
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
|
||||
if (node.typeParameters) {
|
||||
// Only report errors on the last declaration for the type parameter container;
|
||||
// this ensures that all uses have been accounted for.
|
||||
var symbol = getSymbolOfNode(node);
|
||||
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
|
||||
if (lastDeclaration !== node) {
|
||||
return;
|
||||
}
|
||||
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
|
||||
var typeParameter = _a[_i];
|
||||
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
|
||||
if (!typeParameter.symbol.isReferenced) {
|
||||
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
|
||||
}
|
||||
}
|
||||
@@ -30753,7 +30719,7 @@ var ts;
|
||||
ts.forEach(node.members, checkSourceElement);
|
||||
if (produceDiagnostics) {
|
||||
checkTypeForDuplicateIndexSignatures(node);
|
||||
registerForUnusedIdentifiersCheck(node);
|
||||
checkUnusedTypeParameters(node);
|
||||
}
|
||||
}
|
||||
function checkTypeAliasDeclaration(node) {
|
||||
@@ -36017,7 +35983,7 @@ var ts;
|
||||
writeLine();
|
||||
var sourceMappingURL = sourceMap.getSourceMappingURL();
|
||||
if (sourceMappingURL) {
|
||||
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
|
||||
write("//# sourceMappingURL=" + sourceMappingURL);
|
||||
}
|
||||
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
|
||||
// reset the state
|
||||
@@ -37914,7 +37880,7 @@ var ts;
|
||||
* if we should also export the value after its it changed
|
||||
* - check if node is a source level declaration to emit it differently,
|
||||
* i.e non-exported variable statement 'var x = 1' is hoisted so
|
||||
* when we emit variable statement 'var' should be dropped.
|
||||
* we we emit variable statement 'var' should be dropped.
|
||||
*/
|
||||
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
|
||||
if (!node || !isCurrentFileSystemExternalModule()) {
|
||||
@@ -40381,13 +40347,13 @@ var ts;
|
||||
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
|
||||
write("export ");
|
||||
}
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
if (decoratedClassAlias !== undefined) {
|
||||
write("let " + decoratedClassAlias);
|
||||
write("" + decoratedClassAlias);
|
||||
}
|
||||
else {
|
||||
if (!isHoistedDeclarationInSystemModule) {
|
||||
write("let ");
|
||||
}
|
||||
emitDeclarationName(node);
|
||||
}
|
||||
write(" = ");
|
||||
@@ -40406,9 +40372,7 @@ var ts;
|
||||
//
|
||||
// We'll emit:
|
||||
//
|
||||
// let C_1 = class C{};
|
||||
// C_1.a = 1;
|
||||
// C_1.b = 2; // so forth and so on
|
||||
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
|
||||
//
|
||||
// This keeps the expression as an expression, while ensuring that the static parts
|
||||
// of it have been initialized by the time it is used.
|
||||
@@ -42972,7 +42936,7 @@ var ts;
|
||||
/* @internal */ ts.ioReadTime = 0;
|
||||
/* @internal */ ts.ioWriteTime = 0;
|
||||
/** The version of the TypeScript compiler release */
|
||||
ts.version = "2.1.0";
|
||||
ts.version = "2.0.0";
|
||||
var emptyArray = [];
|
||||
var defaultTypeRoots = ["node_modules/@types"];
|
||||
function findConfigFile(searchPath, fileExists) {
|
||||
@@ -43061,7 +43025,12 @@ var ts;
|
||||
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
|
||||
}
|
||||
function moduleHasNonRelativeName(moduleName) {
|
||||
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
|
||||
if (ts.isRootedDiskPath(moduleName)) {
|
||||
return false;
|
||||
}
|
||||
var i = moduleName.lastIndexOf("./", 1);
|
||||
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */);
|
||||
return !startsWithDotSlashOrDotDotSlash;
|
||||
}
|
||||
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
|
||||
var jsonContent;
|
||||
@@ -43828,22 +43797,6 @@ var ts;
|
||||
return ts.sortAndDeduplicateDiagnostics(diagnostics);
|
||||
}
|
||||
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
|
||||
function formatDiagnostics(diagnostics, host) {
|
||||
var output = "";
|
||||
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
|
||||
var diagnostic = diagnostics_1[_i];
|
||||
if (diagnostic.file) {
|
||||
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
|
||||
var fileName = diagnostic.file.fileName;
|
||||
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
|
||||
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
|
||||
}
|
||||
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
ts.formatDiagnostics = formatDiagnostics;
|
||||
function flattenDiagnosticMessageText(messageText, newLine) {
|
||||
if (typeof messageText === "string") {
|
||||
return messageText;
|
||||
@@ -43936,11 +43889,11 @@ var ts;
|
||||
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
|
||||
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
|
||||
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
|
||||
var currentNodeModulesDepth = 0;
|
||||
var currentNodeModulesJsDepth = 0;
|
||||
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
|
||||
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
|
||||
var modulesWithElidedImports = {};
|
||||
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
|
||||
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
|
||||
var sourceFilesFoundSearchingNodeModules = {};
|
||||
var start = new Date().getTime();
|
||||
host = host || createCompilerHost(options);
|
||||
@@ -44197,7 +44150,8 @@ var ts;
|
||||
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
|
||||
}
|
||||
function emit(sourceFile, writeFileCallback, cancellationToken) {
|
||||
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
|
||||
var _this = this;
|
||||
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
|
||||
}
|
||||
function isEmitBlocked(emitFileName) {
|
||||
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
|
||||
@@ -44649,19 +44603,9 @@ var ts;
|
||||
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
|
||||
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
|
||||
}
|
||||
// If the file was previously found via a node_modules search, but is now being processed as a root file,
|
||||
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
|
||||
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
|
||||
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
|
||||
if (!options.noResolve) {
|
||||
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
|
||||
processTypeReferenceDirectives(file_1);
|
||||
}
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
|
||||
// See if we need to reprocess the imports due to prior skipped imports
|
||||
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
|
||||
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
|
||||
modulesWithElidedImports[file_1.path] = false;
|
||||
processImportedModules(file_1, ts.getDirectoryPath(fileName));
|
||||
}
|
||||
@@ -44679,7 +44623,6 @@ var ts;
|
||||
});
|
||||
filesByName.set(path, file);
|
||||
if (file) {
|
||||
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
|
||||
file.path = path;
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
|
||||
@@ -44794,9 +44737,12 @@ var ts;
|
||||
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
|
||||
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth++;
|
||||
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth++;
|
||||
}
|
||||
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
|
||||
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
|
||||
if (elideImport) {
|
||||
modulesWithElidedImports[file.path] = true;
|
||||
@@ -44805,8 +44751,8 @@ var ts;
|
||||
findSourceFile(resolution.resolvedFileName, resolvedPath,
|
||||
/*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
|
||||
}
|
||||
if (isFromNodeModulesSearch) {
|
||||
currentNodeModulesDepth--;
|
||||
if (isJsFileFromNodeModules) {
|
||||
currentNodeModulesJsDepth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45144,12 +45090,12 @@ var ts;
|
||||
{
|
||||
name: "noUnusedLocals",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_locals
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
type: "boolean",
|
||||
description: ts.Diagnostics.Report_errors_on_unused_parameters
|
||||
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -47141,7 +47087,7 @@ var ts;
|
||||
else {
|
||||
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
|
||||
// manner. If it does, return that there was a prefix match.
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
|
||||
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
|
||||
}
|
||||
}
|
||||
var isLowercase = chunk.isLowerCase;
|
||||
@@ -47407,6 +47353,14 @@ var ts;
|
||||
var str = String.fromCharCode(ch);
|
||||
return str === str.toLowerCase();
|
||||
}
|
||||
function startsWith(string, search) {
|
||||
for (var i = 0, n = search.length; i < n; i++) {
|
||||
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Assumes 'value' is already lowercase.
|
||||
function indexOfIgnoringCase(string, value) {
|
||||
for (var i = 0, n = string.length - value.length; i <= n; i++) {
|
||||
@@ -49251,7 +49205,6 @@ var ts;
|
||||
ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
|
||||
ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
|
||||
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
|
||||
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
|
||||
})(ScanAction || (ScanAction = {}));
|
||||
function getFormattingScanner(sourceFile, startPos, endPos) {
|
||||
ts.Debug.assert(scanner === undefined);
|
||||
@@ -49343,9 +49296,6 @@ var ts;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function shouldRescanJsxText(node) {
|
||||
return node && node.kind === 244 /* JsxText */;
|
||||
}
|
||||
function shouldRescanSlashToken(container) {
|
||||
return container.kind === 10 /* RegularExpressionLiteral */;
|
||||
}
|
||||
@@ -49376,9 +49326,7 @@ var ts;
|
||||
? 3 /* RescanTemplateToken */
|
||||
: shouldRescanJsxIdentifier(n)
|
||||
? 4 /* RescanJsxIdentifier */
|
||||
: shouldRescanJsxText(n)
|
||||
? 5 /* RescanJsxText */
|
||||
: 0 /* Scan */;
|
||||
: 0 /* Scan */;
|
||||
if (lastTokenInfo && expectedScanAction === lastScanAction) {
|
||||
// readTokenInfo was called before with the same expected scan action.
|
||||
// No need to re-scan text, return existing 'lastTokenInfo'
|
||||
@@ -49413,10 +49361,6 @@ var ts;
|
||||
currentToken = scanner.scanJsxIdentifier();
|
||||
lastScanAction = 4 /* RescanJsxIdentifier */;
|
||||
}
|
||||
else if (expectedScanAction === 5 /* RescanJsxText */) {
|
||||
currentToken = scanner.reScanJsxToken();
|
||||
lastScanAction = 5 /* RescanJsxText */;
|
||||
}
|
||||
else {
|
||||
lastScanAction = 0 /* Scan */;
|
||||
}
|
||||
@@ -52089,20 +52033,19 @@ var ts;
|
||||
"version"
|
||||
];
|
||||
var jsDocCompletionEntries;
|
||||
function createNode(kind, pos, end, parent) {
|
||||
var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) :
|
||||
kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) :
|
||||
new TokenObject(kind, pos, end);
|
||||
function createNode(kind, pos, end, flags, parent) {
|
||||
var node = new NodeObject(kind, pos, end);
|
||||
node.flags = flags;
|
||||
node.parent = parent;
|
||||
return node;
|
||||
}
|
||||
var NodeObject = (function () {
|
||||
function NodeObject(kind, pos, end) {
|
||||
this.kind = kind;
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0 /* None */;
|
||||
this.parent = undefined;
|
||||
this.kind = kind;
|
||||
}
|
||||
NodeObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
@@ -52137,14 +52080,14 @@ var ts;
|
||||
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
|
||||
var textPos = scanner.getTextPos();
|
||||
if (textPos <= end) {
|
||||
nodes.push(createNode(token, pos, textPos, this));
|
||||
nodes.push(createNode(token, pos, textPos, 0, this));
|
||||
}
|
||||
pos = textPos;
|
||||
}
|
||||
return pos;
|
||||
};
|
||||
NodeObject.prototype.createSyntaxList = function (nodes) {
|
||||
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
|
||||
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
|
||||
list._children = [];
|
||||
var pos = nodes.pos;
|
||||
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
|
||||
@@ -52230,74 +52173,6 @@ var ts;
|
||||
};
|
||||
return NodeObject;
|
||||
}());
|
||||
var TokenOrIdentifierObject = (function () {
|
||||
function TokenOrIdentifierObject(pos, end) {
|
||||
// Set properties in same order as NodeObject
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = 0 /* None */;
|
||||
this.parent = undefined;
|
||||
}
|
||||
TokenOrIdentifierObject.prototype.getSourceFile = function () {
|
||||
return ts.getSourceFileOfNode(this);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
|
||||
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullStart = function () {
|
||||
return this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getEnd = function () {
|
||||
return this.end;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
|
||||
return this.getEnd() - this.getStart(sourceFile);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullWidth = function () {
|
||||
return this.end - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
|
||||
return this.getStart(sourceFile) - this.pos;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
|
||||
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
|
||||
return 0;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
|
||||
return emptyArray;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
|
||||
return undefined;
|
||||
};
|
||||
return TokenOrIdentifierObject;
|
||||
}());
|
||||
var TokenObject = (function (_super) {
|
||||
__extends(TokenObject, _super);
|
||||
function TokenObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
this.kind = kind;
|
||||
}
|
||||
return TokenObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
var IdentifierObject = (function (_super) {
|
||||
__extends(IdentifierObject, _super);
|
||||
function IdentifierObject(kind, pos, end) {
|
||||
_super.call(this, pos, end);
|
||||
}
|
||||
return IdentifierObject;
|
||||
}(TokenOrIdentifierObject));
|
||||
IdentifierObject.prototype.kind = 69 /* Identifier */;
|
||||
var SymbolObject = (function () {
|
||||
function SymbolObject(flags, name) {
|
||||
this.flags = flags;
|
||||
@@ -59062,8 +58937,6 @@ var ts;
|
||||
function initializeServices() {
|
||||
ts.objectAllocator = {
|
||||
getNodeConstructor: function () { return NodeObject; },
|
||||
getTokenConstructor: function () { return TokenObject; },
|
||||
getIdentifierConstructor: function () { return IdentifierObject; },
|
||||
getSourceFileConstructor: function () { return SourceFileObject; },
|
||||
getSymbolConstructor: function () { return SymbolObject; },
|
||||
getTypeConstructor: function () { return TypeObject; },
|
||||
@@ -59689,7 +59562,7 @@ var ts;
|
||||
//
|
||||
/// <reference path='services.ts' />
|
||||
/* @internal */
|
||||
var debugObjectHost = new Function("return this")();
|
||||
var debugObjectHost = this;
|
||||
// We need to use 'null' to interface with the managed side.
|
||||
/* tslint:disable:no-null-keyword */
|
||||
/* tslint:disable:no-in-operator */
|
||||
@@ -59828,7 +59701,7 @@ var ts;
|
||||
return this.shimHost.getCurrentDirectory();
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
|
||||
return JSON.parse(this.shimHost.getDirectories(path));
|
||||
return this.shimHost.getDirectories(path);
|
||||
};
|
||||
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
|
||||
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
|
||||
|
||||
+5
-2
@@ -30,8 +30,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/browserify": "latest",
|
||||
"@types/convert-source-map": "latest",
|
||||
"@types/chai": "latest",
|
||||
"@types/convert-source-map": "latest",
|
||||
"@types/del": "latest",
|
||||
"@types/glob": "latest",
|
||||
"@types/gulp": "latest",
|
||||
@@ -69,16 +69,19 @@
|
||||
"mkdirp": "latest",
|
||||
"mocha": "latest",
|
||||
"mocha-fivemat-progress-reporter": "latest",
|
||||
"q": "latest",
|
||||
"run-sequence": "latest",
|
||||
"sorcery": "latest",
|
||||
"through2": "latest",
|
||||
"travis-fold": "latest",
|
||||
"ts-node": "latest",
|
||||
"tsd": "latest",
|
||||
"tslint": "next",
|
||||
"typescript": "next"
|
||||
},
|
||||
"scripts": {
|
||||
"pretest": "jake tests",
|
||||
"test": "jake runtests",
|
||||
"test": "jake runtests-parallel",
|
||||
"build": "npm run build:compiler && npm run build:tests",
|
||||
"build:compiler": "jake local",
|
||||
"build:tests": "jake tests",
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
};
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
/// <reference path="../src/harness/external/node.d.ts" />
|
||||
/// <reference types="node"/>
|
||||
|
||||
import fs = require('fs');
|
||||
import path = require('path');
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
var Linter = require("tslint");
|
||||
var fs = require("fs");
|
||||
|
||||
function getLinterOptions() {
|
||||
return {
|
||||
configuration: require("../tslint.json"),
|
||||
formatter: "prose",
|
||||
formattersDirectory: undefined,
|
||||
rulesDirectory: "built/local/tslint"
|
||||
};
|
||||
}
|
||||
|
||||
function lintFileContents(options, path, contents) {
|
||||
var ll = new Linter(path, contents, options);
|
||||
return ll.lint();
|
||||
}
|
||||
|
||||
function lintFileAsync(options, path, cb) {
|
||||
fs.readFile(path, "utf8", function (err, contents) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
var result = lintFileContents(options, path, contents);
|
||||
cb(undefined, result);
|
||||
});
|
||||
}
|
||||
|
||||
process.on("message", function (data) {
|
||||
switch (data.kind) {
|
||||
case "file":
|
||||
var target = data.name;
|
||||
var lintOptions = getLinterOptions();
|
||||
lintFileAsync(lintOptions, target, function (err, result) {
|
||||
if (err) {
|
||||
process.send({ kind: "error", error: err.toString() });
|
||||
return;
|
||||
}
|
||||
process.send({ kind: "result", failures: result.failureCount, output: result.output });
|
||||
});
|
||||
break;
|
||||
case "close":
|
||||
process.exit(0);
|
||||
break;
|
||||
}
|
||||
});
|
||||
@@ -69,7 +69,7 @@ function checkForUniqueCodes(messages: string[], diagnosticTable: InputDiagnosti
|
||||
}
|
||||
|
||||
function buildUniqueNameMap(names: string[]): ts.Map<string> {
|
||||
var nameMap: ts.Map<string> = {};
|
||||
var nameMap = ts.createMap<string>();
|
||||
|
||||
var uniqueNames = NameGenerator.ensureUniqueness(names, /* isCaseSensitive */ false, /* isFixed */ undefined);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as Lint from "tslint/lib/lint";
|
||||
import * as ts from "typescript";
|
||||
|
||||
|
||||
export class Rule extends Lint.Rules.AbstractRule {
|
||||
public static TRAILING_FAILURE_STRING = "Excess trailing whitespace found around type assertion.";
|
||||
|
||||
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
||||
return this.applyWithWalker(new TypeAssertionWhitespaceWalker(sourceFile, this.getOptions()));
|
||||
}
|
||||
}
|
||||
|
||||
class TypeAssertionWhitespaceWalker extends Lint.RuleWalker {
|
||||
public visitNode(node: ts.Node) {
|
||||
if (node.kind === ts.SyntaxKind.TypeAssertionExpression) {
|
||||
const refined = node as ts.TypeAssertion;
|
||||
const leftSideWhitespaceStart = refined.type.getEnd() + 1;
|
||||
const rightSideWhitespaceEnd = refined.expression.getStart();
|
||||
if (leftSideWhitespaceStart !== rightSideWhitespaceEnd) {
|
||||
this.addFailure(this.createFailure(leftSideWhitespaceStart, rightSideWhitespaceEnd, Rule.TRAILING_FAILURE_STRING));
|
||||
}
|
||||
}
|
||||
super.visitNode(node);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Lint from "tslint/lib/lint";
|
||||
import * as ts from "typescript";
|
||||
|
||||
|
||||
export class Rule extends Lint.Rules.AbstractRule {
|
||||
public static FAILURE_STRING_FACTORY = (identifier: string) => `Identifier '${identifier}' never appears on the LHS of an assignment - use const instead of let for its declaration.`;
|
||||
|
||||
@@ -10,44 +9,12 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
}
|
||||
}
|
||||
|
||||
function isBindingPattern(node: ts.Node): node is ts.BindingPattern {
|
||||
return !!node && (node.kind === ts.SyntaxKind.ArrayBindingPattern || node.kind === ts.SyntaxKind.ObjectBindingPattern);
|
||||
}
|
||||
|
||||
function walkUpBindingElementsAndPatterns(node: ts.Node): ts.Node {
|
||||
while (node && (node.kind === ts.SyntaxKind.BindingElement || isBindingPattern(node))) {
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function getCombinedNodeFlags(node: ts.Node): ts.NodeFlags {
|
||||
node = walkUpBindingElementsAndPatterns(node);
|
||||
|
||||
let flags = node.flags;
|
||||
if (node.kind === ts.SyntaxKind.VariableDeclaration) {
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
if (node && node.kind === ts.SyntaxKind.VariableDeclarationList) {
|
||||
flags |= node.flags;
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
if (node && node.kind === ts.SyntaxKind.VariableStatement) {
|
||||
flags |= node.flags;
|
||||
}
|
||||
|
||||
return flags;
|
||||
}
|
||||
|
||||
function isLet(node: ts.Node) {
|
||||
return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Let);
|
||||
return !!(ts.getCombinedNodeFlags(node) & ts.NodeFlags.Let);
|
||||
}
|
||||
|
||||
function isExported(node: ts.Node) {
|
||||
return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Export);
|
||||
return !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export);
|
||||
}
|
||||
|
||||
function isAssignmentOperator(token: ts.SyntaxKind): boolean {
|
||||
@@ -64,7 +31,7 @@ interface DeclarationUsages {
|
||||
}
|
||||
|
||||
class PreferConstWalker extends Lint.RuleWalker {
|
||||
private inScopeLetDeclarations: ts.Map<DeclarationUsages>[] = [];
|
||||
private inScopeLetDeclarations: ts.MapLike<DeclarationUsages>[] = [];
|
||||
private errors: Lint.RuleFailure[] = [];
|
||||
private markAssignment(identifier: ts.Identifier) {
|
||||
const name = identifier.text;
|
||||
@@ -126,11 +93,16 @@ class PreferConstWalker extends Lint.RuleWalker {
|
||||
|
||||
private visitBindingPatternIdentifiers(pattern: ts.BindingPattern) {
|
||||
for (const element of pattern.elements) {
|
||||
if (element.name.kind === ts.SyntaxKind.Identifier) {
|
||||
this.markAssignment(element.name as ts.Identifier);
|
||||
if (element.kind !== ts.SyntaxKind.BindingElement) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = (<ts.BindingElement>element).name;
|
||||
if (name.kind === ts.SyntaxKind.Identifier) {
|
||||
this.markAssignment(name as ts.Identifier);
|
||||
}
|
||||
else {
|
||||
this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern);
|
||||
this.visitBindingPatternIdentifiers(name as ts.BindingPattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,7 +144,7 @@ class PreferConstWalker extends Lint.RuleWalker {
|
||||
}
|
||||
|
||||
private visitAnyForStatement(node: ts.ForOfStatement | ts.ForInStatement) {
|
||||
const names: ts.Map<DeclarationUsages> = {};
|
||||
const names: ts.MapLike<DeclarationUsages> = {};
|
||||
if (isLet(node.initializer)) {
|
||||
if (node.initializer.kind === ts.SyntaxKind.VariableDeclarationList) {
|
||||
this.collectLetIdentifiers(node.initializer as ts.VariableDeclarationList, names);
|
||||
@@ -194,7 +166,7 @@ class PreferConstWalker extends Lint.RuleWalker {
|
||||
}
|
||||
|
||||
visitBlock(node: ts.Block) {
|
||||
const names: ts.Map<DeclarationUsages> = {};
|
||||
const names: ts.MapLike<DeclarationUsages> = {};
|
||||
for (const statement of node.statements) {
|
||||
if (statement.kind === ts.SyntaxKind.VariableStatement) {
|
||||
this.collectLetIdentifiers((statement as ts.VariableStatement).declarationList, names);
|
||||
@@ -205,7 +177,7 @@ class PreferConstWalker extends Lint.RuleWalker {
|
||||
this.popDeclarations();
|
||||
}
|
||||
|
||||
private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.Map<DeclarationUsages>) {
|
||||
private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.MapLike<DeclarationUsages>) {
|
||||
for (const node of list.declarations) {
|
||||
if (isLet(node) && !isExported(node)) {
|
||||
this.collectNameIdentifiers(node, node.name, ret);
|
||||
@@ -213,7 +185,7 @@ class PreferConstWalker extends Lint.RuleWalker {
|
||||
}
|
||||
}
|
||||
|
||||
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
|
||||
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
|
||||
if (node.kind === ts.SyntaxKind.Identifier) {
|
||||
table[(node as ts.Identifier).text] = { declaration, usages: 0 };
|
||||
}
|
||||
@@ -222,9 +194,11 @@ class PreferConstWalker extends Lint.RuleWalker {
|
||||
}
|
||||
}
|
||||
|
||||
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
|
||||
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
|
||||
for (const element of pattern.elements) {
|
||||
this.collectNameIdentifiers(value, element.name, table);
|
||||
if (element.kind === ts.SyntaxKind.BindingElement) {
|
||||
this.collectNameIdentifiers(value, (<ts.BindingElement>element).name, table);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+2
-1
@@ -10,7 +10,7 @@ declare module "gulp-insert" {
|
||||
export function append(text: string | Buffer): NodeJS.ReadWriteStream;
|
||||
export function prepend(text: string | Buffer): NodeJS.ReadWriteStream;
|
||||
export function wrap(text: string | Buffer, tail: string | Buffer): NodeJS.ReadWriteStream;
|
||||
export function transform(cb: (contents: string, file: {path: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file
|
||||
export function transform(cb: (contents: string, file: {path: string, relative: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file
|
||||
}
|
||||
|
||||
declare module "into-stream" {
|
||||
@@ -22,3 +22,4 @@ declare module "into-stream" {
|
||||
}
|
||||
|
||||
declare module "sorcery";
|
||||
declare module "travis-fold";
|
||||
|
||||
+884
-85
File diff suppressed because it is too large
Load Diff
+2133
-1280
File diff suppressed because it is too large
Load Diff
@@ -30,6 +30,7 @@ namespace ts {
|
||||
{
|
||||
name: "extendedDiagnostics",
|
||||
type: "boolean",
|
||||
experimental: true
|
||||
},
|
||||
{
|
||||
name: "emitBOM",
|
||||
@@ -61,10 +62,10 @@ namespace ts {
|
||||
},
|
||||
{
|
||||
name: "jsx",
|
||||
type: {
|
||||
type: createMap({
|
||||
"preserve": JsxEmit.Preserve,
|
||||
"react": JsxEmit.React
|
||||
},
|
||||
}),
|
||||
paramType: Diagnostics.KIND,
|
||||
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
|
||||
},
|
||||
@@ -91,7 +92,7 @@ namespace ts {
|
||||
{
|
||||
name: "module",
|
||||
shortName: "m",
|
||||
type: {
|
||||
type: createMap({
|
||||
"none": ModuleKind.None,
|
||||
"commonjs": ModuleKind.CommonJS,
|
||||
"amd": ModuleKind.AMD,
|
||||
@@ -99,16 +100,16 @@ namespace ts {
|
||||
"umd": ModuleKind.UMD,
|
||||
"es6": ModuleKind.ES6,
|
||||
"es2015": ModuleKind.ES2015,
|
||||
},
|
||||
}),
|
||||
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
|
||||
paramType: Diagnostics.KIND,
|
||||
},
|
||||
{
|
||||
name: "newLine",
|
||||
type: {
|
||||
type: createMap({
|
||||
"crlf": NewLineKind.CarriageReturnLineFeed,
|
||||
"lf": NewLineKind.LineFeed
|
||||
},
|
||||
}),
|
||||
description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
|
||||
paramType: Diagnostics.NEWLINE,
|
||||
},
|
||||
@@ -126,6 +127,10 @@ namespace ts {
|
||||
type: "boolean",
|
||||
description: Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
|
||||
},
|
||||
{
|
||||
name: "noErrorTruncation",
|
||||
type: "boolean"
|
||||
},
|
||||
{
|
||||
name: "noImplicitAny",
|
||||
type: "boolean",
|
||||
@@ -139,12 +144,12 @@ namespace ts {
|
||||
{
|
||||
name: "noUnusedLocals",
|
||||
type: "boolean",
|
||||
description: Diagnostics.Report_errors_on_unused_locals,
|
||||
description: Diagnostics.Report_errors_on_unused_locals,
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
type: "boolean",
|
||||
description: Diagnostics.Report_errors_on_unused_parameters,
|
||||
description: Diagnostics.Report_errors_on_unused_parameters,
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -250,12 +255,12 @@ namespace ts {
|
||||
{
|
||||
name: "target",
|
||||
shortName: "t",
|
||||
type: {
|
||||
type: createMap({
|
||||
"es3": ScriptTarget.ES3,
|
||||
"es5": ScriptTarget.ES5,
|
||||
"es6": ScriptTarget.ES6,
|
||||
"es2015": ScriptTarget.ES2015,
|
||||
},
|
||||
}),
|
||||
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
|
||||
paramType: Diagnostics.VERSION,
|
||||
},
|
||||
@@ -284,11 +289,12 @@ namespace ts {
|
||||
},
|
||||
{
|
||||
name: "moduleResolution",
|
||||
type: {
|
||||
type: createMap({
|
||||
"node": ModuleResolutionKind.NodeJs,
|
||||
"classic": ModuleResolutionKind.Classic,
|
||||
},
|
||||
}),
|
||||
description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
|
||||
paramType: Diagnostics.STRATEGY,
|
||||
},
|
||||
{
|
||||
name: "allowUnusedLabels",
|
||||
@@ -392,7 +398,7 @@ namespace ts {
|
||||
type: "list",
|
||||
element: {
|
||||
name: "lib",
|
||||
type: {
|
||||
type: createMap({
|
||||
// JavaScript only
|
||||
"es5": "lib.es5.d.ts",
|
||||
"es6": "lib.es2015.d.ts",
|
||||
@@ -417,7 +423,7 @@ namespace ts {
|
||||
"es2016.array.include": "lib.es2016.array.include.d.ts",
|
||||
"es2017.object": "lib.es2017.object.d.ts",
|
||||
"es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts"
|
||||
},
|
||||
}),
|
||||
},
|
||||
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
|
||||
},
|
||||
@@ -429,6 +435,11 @@ namespace ts {
|
||||
name: "strictNullChecks",
|
||||
type: "boolean",
|
||||
description: Diagnostics.Enable_strict_null_checks
|
||||
},
|
||||
{
|
||||
name: "importHelpers",
|
||||
type: "boolean",
|
||||
description: Diagnostics.Import_emit_helpers_from_tslib
|
||||
}
|
||||
];
|
||||
|
||||
@@ -462,6 +473,14 @@ namespace ts {
|
||||
shortOptionNames: Map<string>;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const defaultInitCompilerOptions: CompilerOptions = {
|
||||
module: ModuleKind.CommonJS,
|
||||
target: ScriptTarget.ES5,
|
||||
noImplicitAny: false,
|
||||
sourceMap: false,
|
||||
};
|
||||
|
||||
let optionNameMapCache: OptionNameMap;
|
||||
|
||||
/* @internal */
|
||||
@@ -470,8 +489,8 @@ namespace ts {
|
||||
return optionNameMapCache;
|
||||
}
|
||||
|
||||
const optionNameMap: Map<CommandLineOption> = {};
|
||||
const shortOptionNames: Map<string> = {};
|
||||
const optionNameMap = createMap<CommandLineOption>();
|
||||
const shortOptionNames = createMap<string>();
|
||||
forEach(optionDeclarations, option => {
|
||||
optionNameMap[option.name.toLowerCase()] = option;
|
||||
if (option.shortName) {
|
||||
@@ -486,10 +505,9 @@ namespace ts {
|
||||
/* @internal */
|
||||
export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic {
|
||||
const namesOfType: string[] = [];
|
||||
forEachKey(opt.type, key => {
|
||||
for (const key in opt.type) {
|
||||
namesOfType.push(` '${key}'`);
|
||||
});
|
||||
|
||||
}
|
||||
return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType);
|
||||
}
|
||||
|
||||
@@ -497,7 +515,7 @@ namespace ts {
|
||||
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
|
||||
const key = trimString((value || "")).toLowerCase();
|
||||
const map = opt.type;
|
||||
if (hasProperty(map, key)) {
|
||||
if (key in map) {
|
||||
return map[key];
|
||||
}
|
||||
else {
|
||||
@@ -551,11 +569,11 @@ namespace ts {
|
||||
s = s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase();
|
||||
|
||||
// Try to translate short option names to their full equivalents.
|
||||
if (hasProperty(shortOptionNames, s)) {
|
||||
if (s in shortOptionNames) {
|
||||
s = shortOptionNames[s];
|
||||
}
|
||||
|
||||
if (hasProperty(optionNameMap, s)) {
|
||||
if (s in optionNameMap) {
|
||||
const opt = optionNameMap[s];
|
||||
|
||||
if (opt.isTSConfigOnly) {
|
||||
@@ -668,6 +686,94 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate tsconfig configuration when running command line "--init"
|
||||
* @param options commandlineOptions to be generated into tsconfig.json
|
||||
* @param fileNames array of filenames to be generated into tsconfig.json
|
||||
*/
|
||||
/* @internal */
|
||||
export function generateTSConfig(options: CompilerOptions, fileNames: string[]): { compilerOptions: Map<CompilerOptionsValue> } {
|
||||
const compilerOptions = extend(options, defaultInitCompilerOptions);
|
||||
const configurations: any = {
|
||||
compilerOptions: serializeCompilerOptions(compilerOptions)
|
||||
};
|
||||
if (fileNames && fileNames.length) {
|
||||
// only set the files property if we have at least one file
|
||||
configurations.files = fileNames;
|
||||
}
|
||||
|
||||
return configurations;
|
||||
|
||||
function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map<string | number> | undefined {
|
||||
if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") {
|
||||
// this is of a type CommandLineOptionOfPrimitiveType
|
||||
return undefined;
|
||||
}
|
||||
else if (optionDefinition.type === "list") {
|
||||
return getCustomTypeMapOfCommandLineOption((<CommandLineOptionOfListType>optionDefinition).element);
|
||||
}
|
||||
else {
|
||||
return (<CommandLineOptionOfCustomType>optionDefinition).type;
|
||||
}
|
||||
}
|
||||
|
||||
function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: MapLike<string | number>): string | undefined {
|
||||
// There is a typeMap associated with this command-line option so use it to map value back to its name
|
||||
for (const key in customTypeMap) {
|
||||
if (customTypeMap[key] === value) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function serializeCompilerOptions(options: CompilerOptions): Map<CompilerOptionsValue> {
|
||||
const result = createMap<CompilerOptionsValue>();
|
||||
const optionsNameMap = getOptionNameMap().optionNameMap;
|
||||
|
||||
for (const name in options) {
|
||||
if (hasProperty(options, name)) {
|
||||
// tsconfig only options cannot be specified via command line,
|
||||
// so we can assume that only types that can appear here string | number | boolean
|
||||
switch (name) {
|
||||
case "init":
|
||||
case "watch":
|
||||
case "version":
|
||||
case "help":
|
||||
case "project":
|
||||
break;
|
||||
default:
|
||||
const value = options[name];
|
||||
let optionDefinition = optionsNameMap[name.toLowerCase()];
|
||||
if (optionDefinition) {
|
||||
const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition);
|
||||
if (!customTypeMap) {
|
||||
// There is no map associated with this compiler option then use the value as-is
|
||||
// This is the case if the value is expect to be string, number, boolean or list of string
|
||||
result[name] = value;
|
||||
}
|
||||
else {
|
||||
if (optionDefinition.type === "list") {
|
||||
const convertedValue: string[] = [];
|
||||
for (const element of value as (string | number)[]) {
|
||||
convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap));
|
||||
}
|
||||
result[name] = convertedValue;
|
||||
}
|
||||
else {
|
||||
// There is a typeMap associated with this command-line option so use it to map value back to its name
|
||||
result[name] = getNameOfCompilerOptionValue(value, customTypeMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the comments from a json like text.
|
||||
* Comments can be single line comments (starting with # or //) or multiline comments using / * * /
|
||||
@@ -693,9 +799,6 @@ namespace ts {
|
||||
return output;
|
||||
}
|
||||
|
||||
// Skip over any minified JavaScript files (ending in ".min.js")
|
||||
// Skip over dotted files and folders as well
|
||||
const ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/;
|
||||
/**
|
||||
* Parse the contents of a config file (tsconfig.json).
|
||||
* @param json The contents of the config file to parse
|
||||
@@ -756,14 +859,13 @@ namespace ts {
|
||||
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
|
||||
}
|
||||
else {
|
||||
// By default, exclude common package folders
|
||||
// By default, exclude common package folders and the outDir
|
||||
excludeSpecs = ["node_modules", "bower_components", "jspm_packages"];
|
||||
}
|
||||
|
||||
// Always exclude the output directory unless explicitly included
|
||||
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
|
||||
if (outDir) {
|
||||
excludeSpecs.push(outDir);
|
||||
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
|
||||
if (outDir) {
|
||||
excludeSpecs.push(outDir);
|
||||
}
|
||||
}
|
||||
|
||||
if (fileNames === undefined && includeSpecs === undefined) {
|
||||
@@ -789,7 +891,7 @@ namespace ts {
|
||||
function convertCompilerOptionsFromJsonWorker(jsonOptions: any,
|
||||
basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions {
|
||||
|
||||
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {};
|
||||
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
|
||||
convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors);
|
||||
return options;
|
||||
}
|
||||
@@ -814,7 +916,7 @@ namespace ts {
|
||||
const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name);
|
||||
|
||||
for (const id in jsonOptions) {
|
||||
if (hasProperty(optionNameMap, id)) {
|
||||
if (id in optionNameMap) {
|
||||
const opt = optionNameMap[id];
|
||||
defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
|
||||
}
|
||||
@@ -851,7 +953,7 @@ namespace ts {
|
||||
|
||||
function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
|
||||
const key = value.toLowerCase();
|
||||
if (hasProperty(opt.type, key)) {
|
||||
if (key in opt.type) {
|
||||
return opt.type[key];
|
||||
}
|
||||
else {
|
||||
@@ -961,12 +1063,12 @@ namespace ts {
|
||||
// Literal file names (provided via the "files" array in tsconfig.json) are stored in a
|
||||
// file map with a possibly case insensitive key. We use this map later when when including
|
||||
// wildcard paths.
|
||||
const literalFileMap: Map<string> = {};
|
||||
const literalFileMap = createMap<string>();
|
||||
|
||||
// Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
|
||||
// file map with a possibly case insensitive key. We use this map to store paths matched
|
||||
// via wildcard, and to handle extension priority.
|
||||
const wildcardFileMap: Map<string> = {};
|
||||
const wildcardFileMap = createMap<string>();
|
||||
|
||||
if (include) {
|
||||
include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false);
|
||||
@@ -1007,10 +1109,6 @@ namespace ts {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ignoreFileNamePattern.test(file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// We may have included a wildcard path with a lower priority
|
||||
// extension due to the user-defined order of entries in the
|
||||
// "include" array. If there is a lower priority extension in the
|
||||
@@ -1018,7 +1116,7 @@ namespace ts {
|
||||
removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
|
||||
|
||||
const key = keyMapper(file);
|
||||
if (!hasProperty(literalFileMap, key) && !hasProperty(wildcardFileMap, key)) {
|
||||
if (!(key in literalFileMap) && !(key in wildcardFileMap)) {
|
||||
wildcardFileMap[key] = file;
|
||||
}
|
||||
}
|
||||
@@ -1070,7 +1168,7 @@ namespace ts {
|
||||
// /a/b/a?z - Watch /a/b directly to catch any new file matching a?z
|
||||
const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude");
|
||||
const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
|
||||
const wildcardDirectories: Map<WatchDirectoryFlags> = {};
|
||||
const wildcardDirectories = createMap<WatchDirectoryFlags>();
|
||||
if (include !== undefined) {
|
||||
const recursiveKeys: string[] = [];
|
||||
for (const file of include) {
|
||||
@@ -1083,7 +1181,7 @@ namespace ts {
|
||||
if (match) {
|
||||
const key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase();
|
||||
const flags = watchRecursivePattern.test(name) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None;
|
||||
const existingFlags = getProperty(wildcardDirectories, key);
|
||||
const existingFlags = wildcardDirectories[key];
|
||||
if (existingFlags === undefined || existingFlags < flags) {
|
||||
wildcardDirectories[key] = flags;
|
||||
if (flags === WatchDirectoryFlags.Recursive) {
|
||||
@@ -1095,11 +1193,9 @@ namespace ts {
|
||||
|
||||
// Remove any subpaths under an existing recursively watched directory.
|
||||
for (const key in wildcardDirectories) {
|
||||
if (hasProperty(wildcardDirectories, key)) {
|
||||
for (const recursiveKey of recursiveKeys) {
|
||||
if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
|
||||
delete wildcardDirectories[key];
|
||||
}
|
||||
for (const recursiveKey of recursiveKeys) {
|
||||
if (key !== recursiveKey && containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
|
||||
delete wildcardDirectories[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1122,7 +1218,7 @@ namespace ts {
|
||||
for (let i = ExtensionPriority.Highest; i < adjustedExtensionPriority; i++) {
|
||||
const higherPriorityExtension = extensions[i];
|
||||
const higherPriorityPath = keyMapper(changeExtension(file, higherPriorityExtension));
|
||||
if (hasProperty(literalFiles, higherPriorityPath) || hasProperty(wildcardFiles, higherPriorityPath)) {
|
||||
if (higherPriorityPath in literalFiles || higherPriorityPath in wildcardFiles) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
/// <reference path="sourcemap.ts" />
|
||||
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
export interface CommentWriter {
|
||||
reset(): void;
|
||||
setSourceFile(sourceFile: SourceFile): void;
|
||||
emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void;
|
||||
emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void;
|
||||
emitTrailingCommentsOfPosition(pos: number): void;
|
||||
}
|
||||
|
||||
export function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter {
|
||||
const compilerOptions = host.getCompilerOptions();
|
||||
const extendedDiagnostics = compilerOptions.extendedDiagnostics;
|
||||
const newLine = host.getNewLine();
|
||||
const { emitPos } = sourceMap;
|
||||
|
||||
let containerPos = -1;
|
||||
let containerEnd = -1;
|
||||
let declarationListContainerEnd = -1;
|
||||
let currentSourceFile: SourceFile;
|
||||
let currentText: string;
|
||||
let currentLineMap: number[];
|
||||
let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[];
|
||||
let hasWrittenComment = false;
|
||||
let disabled: boolean = compilerOptions.removeComments;
|
||||
|
||||
return {
|
||||
reset,
|
||||
setSourceFile,
|
||||
emitNodeWithComments,
|
||||
emitBodyWithDetachedComments,
|
||||
emitTrailingCommentsOfPosition,
|
||||
};
|
||||
|
||||
function emitNodeWithComments(node: Node, emitCallback: (node: Node) => void) {
|
||||
if (disabled) {
|
||||
emitCallback(node);
|
||||
return;
|
||||
}
|
||||
|
||||
if (node) {
|
||||
const { pos, end } = node.commentRange || node;
|
||||
const emitFlags = node.emitFlags;
|
||||
if ((pos < 0 && end < 0) || (pos === end)) {
|
||||
// Both pos and end are synthesized, so just emit the node without comments.
|
||||
if (emitFlags & NodeEmitFlags.NoNestedComments) {
|
||||
disableCommentsAndEmit(node, emitCallback);
|
||||
}
|
||||
else {
|
||||
emitCallback(node);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("preEmitNodeWithComment");
|
||||
}
|
||||
|
||||
const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement;
|
||||
const skipLeadingComments = pos < 0 || (emitFlags & NodeEmitFlags.NoLeadingComments) !== 0;
|
||||
const skipTrailingComments = end < 0 || (emitFlags & NodeEmitFlags.NoTrailingComments) !== 0;
|
||||
|
||||
// Emit leading comments if the position is not synthesized and the node
|
||||
// has not opted out from emitting leading comments.
|
||||
if (!skipLeadingComments) {
|
||||
emitLeadingComments(pos, isEmittedNode);
|
||||
}
|
||||
|
||||
// Save current container state on the stack.
|
||||
const savedContainerPos = containerPos;
|
||||
const savedContainerEnd = containerEnd;
|
||||
const savedDeclarationListContainerEnd = declarationListContainerEnd;
|
||||
|
||||
if (!skipLeadingComments) {
|
||||
containerPos = pos;
|
||||
}
|
||||
|
||||
if (!skipTrailingComments) {
|
||||
containerEnd = end;
|
||||
|
||||
// To avoid invalid comment emit in a down-level binding pattern, we
|
||||
// keep track of the last declaration list container's end
|
||||
if (node.kind === SyntaxKind.VariableDeclarationList) {
|
||||
declarationListContainerEnd = end;
|
||||
}
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.measure("commentTime", "preEmitNodeWithComment");
|
||||
}
|
||||
|
||||
if (emitFlags & NodeEmitFlags.NoNestedComments) {
|
||||
disableCommentsAndEmit(node, emitCallback);
|
||||
}
|
||||
else {
|
||||
emitCallback(node);
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("beginEmitNodeWithComment");
|
||||
}
|
||||
|
||||
// Restore previous container state.
|
||||
containerPos = savedContainerPos;
|
||||
containerEnd = savedContainerEnd;
|
||||
declarationListContainerEnd = savedDeclarationListContainerEnd;
|
||||
|
||||
// Emit trailing comments if the position is not synthesized and the node
|
||||
// has not opted out from emitting leading comments and is an emitted node.
|
||||
if (!skipTrailingComments && isEmittedNode) {
|
||||
emitTrailingComments(end);
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.measure("commentTime", "beginEmitNodeWithComment");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void) {
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("preEmitBodyWithDetachedComments");
|
||||
}
|
||||
|
||||
const { pos, end } = detachedRange;
|
||||
const emitFlags = node.emitFlags;
|
||||
const skipLeadingComments = pos < 0 || (emitFlags & NodeEmitFlags.NoLeadingComments) !== 0;
|
||||
const skipTrailingComments = disabled || end < 0 || (emitFlags & NodeEmitFlags.NoTrailingComments) !== 0;
|
||||
|
||||
if (!skipLeadingComments) {
|
||||
emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.measure("commentTime", "preEmitBodyWithDetachedComments");
|
||||
}
|
||||
|
||||
if (emitFlags & NodeEmitFlags.NoNestedComments) {
|
||||
disableCommentsAndEmit(node, emitCallback);
|
||||
}
|
||||
else {
|
||||
emitCallback(node);
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("beginEmitBodyWithDetachedCommetns");
|
||||
}
|
||||
|
||||
if (!skipTrailingComments) {
|
||||
emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns");
|
||||
}
|
||||
}
|
||||
|
||||
function emitLeadingComments(pos: number, isEmittedNode: boolean) {
|
||||
hasWrittenComment = false;
|
||||
|
||||
if (isEmittedNode) {
|
||||
forEachLeadingCommentToEmit(pos, emitLeadingComment);
|
||||
}
|
||||
else if (pos === 0) {
|
||||
// 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 node will not be emitted
|
||||
forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
|
||||
}
|
||||
}
|
||||
|
||||
function emitTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
|
||||
if (isTripleSlashComment(commentPos, commentEnd)) {
|
||||
emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
|
||||
}
|
||||
}
|
||||
|
||||
function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
|
||||
if (!hasWrittenComment) {
|
||||
emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos);
|
||||
hasWrittenComment = true;
|
||||
}
|
||||
|
||||
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
|
||||
emitPos(commentPos);
|
||||
writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
|
||||
emitPos(commentEnd);
|
||||
|
||||
if (hasTrailingNewLine) {
|
||||
writer.writeLine();
|
||||
}
|
||||
else {
|
||||
writer.write(" ");
|
||||
}
|
||||
}
|
||||
|
||||
function emitTrailingComments(pos: number) {
|
||||
forEachTrailingCommentToEmit(pos, emitTrailingComment);
|
||||
}
|
||||
|
||||
function emitTrailingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) {
|
||||
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
|
||||
if (!writer.isAtStartOfLine()) {
|
||||
writer.write(" ");
|
||||
}
|
||||
|
||||
emitPos(commentPos);
|
||||
writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
|
||||
emitPos(commentEnd);
|
||||
|
||||
if (hasTrailingNewLine) {
|
||||
writer.writeLine();
|
||||
}
|
||||
}
|
||||
|
||||
function emitTrailingCommentsOfPosition(pos: number) {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("beforeEmitTrailingCommentsOfPosition");
|
||||
}
|
||||
|
||||
forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition);
|
||||
|
||||
if (extendedDiagnostics) {
|
||||
performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition");
|
||||
}
|
||||
}
|
||||
|
||||
function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) {
|
||||
// trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
|
||||
|
||||
emitPos(commentPos);
|
||||
writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
|
||||
emitPos(commentEnd);
|
||||
|
||||
if (hasTrailingNewLine) {
|
||||
writer.writeLine();
|
||||
}
|
||||
else {
|
||||
writer.write(" ");
|
||||
}
|
||||
}
|
||||
|
||||
function forEachLeadingCommentToEmit(pos: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) {
|
||||
// Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
|
||||
if (containerPos === -1 || pos !== containerPos) {
|
||||
if (hasDetachedComments(pos)) {
|
||||
forEachLeadingCommentWithoutDetachedComments(cb);
|
||||
}
|
||||
else {
|
||||
forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function forEachTrailingCommentToEmit(end: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) => void) {
|
||||
// Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
|
||||
if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) {
|
||||
forEachTrailingCommentRange(currentText, end, cb);
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
currentSourceFile = undefined;
|
||||
currentText = undefined;
|
||||
currentLineMap = undefined;
|
||||
detachedCommentsInfo = undefined;
|
||||
}
|
||||
|
||||
function setSourceFile(sourceFile: SourceFile) {
|
||||
currentSourceFile = sourceFile;
|
||||
currentText = currentSourceFile.text;
|
||||
currentLineMap = getLineStarts(currentSourceFile);
|
||||
detachedCommentsInfo = undefined;
|
||||
}
|
||||
|
||||
function disableCommentsAndEmit(node: Node, emitCallback: (node: Node) => void): void {
|
||||
if (disabled) {
|
||||
emitCallback(node);
|
||||
}
|
||||
else {
|
||||
disabled = true;
|
||||
emitCallback(node);
|
||||
disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function hasDetachedComments(pos: number) {
|
||||
return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos;
|
||||
}
|
||||
|
||||
function forEachLeadingCommentWithoutDetachedComments(cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) {
|
||||
// get the leading comments from detachedPos
|
||||
const pos = lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos;
|
||||
if (detachedCommentsInfo.length - 1) {
|
||||
detachedCommentsInfo.pop();
|
||||
}
|
||||
else {
|
||||
detachedCommentsInfo = undefined;
|
||||
}
|
||||
|
||||
forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos);
|
||||
}
|
||||
|
||||
function emitDetachedCommentsAndUpdateCommentsInfo(range: TextRange) {
|
||||
const currentDetachedCommentInfo = emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled);
|
||||
if (currentDetachedCommentInfo) {
|
||||
if (detachedCommentsInfo) {
|
||||
detachedCommentsInfo.push(currentDetachedCommentInfo);
|
||||
}
|
||||
else {
|
||||
detachedCommentsInfo = [currentDetachedCommentInfo];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function writeComment(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) {
|
||||
emitPos(commentPos);
|
||||
writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
|
||||
emitPos(commentEnd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given comment is a triple-slash
|
||||
*
|
||||
* @return true if the comment is a triple-slash comment else false
|
||||
**/
|
||||
function isTripleSlashComment(commentPos: number, commentEnd: number) {
|
||||
// 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(commentPos + 1) === CharacterCodes.slash &&
|
||||
commentPos + 2 < commentEnd &&
|
||||
currentText.charCodeAt(commentPos + 2) === CharacterCodes.slash) {
|
||||
const textSubStr = currentText.substring(commentPos, commentEnd);
|
||||
return textSubStr.match(fullTripleSlashReferencePathRegEx) ||
|
||||
textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ?
|
||||
true : false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+605
-145
@@ -19,8 +19,28 @@ namespace ts {
|
||||
True = -1
|
||||
}
|
||||
|
||||
const createObject = Object.create;
|
||||
|
||||
export function createMap<T>(template?: MapLike<T>): Map<T> {
|
||||
const map: Map<T> = createObject(null); // tslint:disable-line:no-null-keyword
|
||||
|
||||
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
|
||||
// This disables creation of hidden classes, which are expensive when an object is
|
||||
// constantly changing shape.
|
||||
map["__"] = undefined;
|
||||
delete map["__"];
|
||||
|
||||
// Copies keys/values from template. Note that for..in will not throw if
|
||||
// template is undefined, and instead will just exit the loop.
|
||||
for (const key in template) if (hasOwnProperty.call(template, key)) {
|
||||
map[key] = template[key];
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
export function createFileMap<T>(keyMapper?: (key: string) => string): FileMap<T> {
|
||||
let files: Map<T> = {};
|
||||
let files = createMap<T>();
|
||||
return {
|
||||
get,
|
||||
set,
|
||||
@@ -46,7 +66,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function contains(path: Path) {
|
||||
return hasProperty(files, toKey(path));
|
||||
return toKey(path) in files;
|
||||
}
|
||||
|
||||
function remove(path: Path) {
|
||||
@@ -55,7 +75,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function clear() {
|
||||
files = {};
|
||||
files = createMap<T>();
|
||||
}
|
||||
|
||||
function toKey(path: Path): string {
|
||||
@@ -81,7 +101,7 @@ namespace ts {
|
||||
* returns a truthy value, then returns that value.
|
||||
* If no such value is found, the callback is applied to each element of array and undefined is returned.
|
||||
*/
|
||||
export function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U {
|
||||
export function forEach<T, U>(array: T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined {
|
||||
if (array) {
|
||||
for (let i = 0, len = array.length; i < len; i++) {
|
||||
const result = callback(array[i], i);
|
||||
@@ -93,10 +113,52 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function contains<T>(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean {
|
||||
/**
|
||||
* Iterates through `array` by index and performs the callback on each element of array until the callback
|
||||
* returns a falsey value, then returns false.
|
||||
* If no such value is found, the callback is applied to each element of array and `true` is returned.
|
||||
*/
|
||||
export function every<T>(array: T[], callback: (element: T, index: number) => boolean): boolean {
|
||||
if (array) {
|
||||
for (let i = 0, len = array.length; i < len; i++) {
|
||||
if (!callback(array[i], i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */
|
||||
export function find<T>(array: T[], predicate: (element: T, index: number) => boolean): T | undefined {
|
||||
for (let i = 0, len = array.length; i < len; i++) {
|
||||
const value = array[i];
|
||||
if (predicate(value, i)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first truthy result of `callback`, or else fails.
|
||||
* This is like `forEach`, but never returns undefined.
|
||||
*/
|
||||
export function findMap<T, U>(array: T[], callback: (element: T, index: number) => U | undefined): U {
|
||||
for (let i = 0, len = array.length; i < len; i++) {
|
||||
const result = callback(array[i], i);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Debug.fail();
|
||||
}
|
||||
|
||||
export function contains<T>(array: T[], value: T): boolean {
|
||||
if (array) {
|
||||
for (const v of array) {
|
||||
if (areEqual ? areEqual(v, value) : v === value) {
|
||||
if (v === value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -124,11 +186,12 @@ namespace ts {
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function countWhere<T>(array: T[], predicate: (x: T) => boolean): number {
|
||||
export function countWhere<T>(array: T[], predicate: (x: T, i: number) => boolean): number {
|
||||
let count = 0;
|
||||
if (array) {
|
||||
for (const v of array) {
|
||||
if (predicate(v)) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const v = array[i];
|
||||
if (predicate(v, i)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
@@ -136,17 +199,46 @@ namespace ts {
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters an array by a predicate function. Returns the same array instance if the predicate is
|
||||
* true for all elements, otherwise returns a new array instance containing the filtered subset.
|
||||
*/
|
||||
export function filter<T, U extends T>(array: T[], f: (x: T) => x is U): U[];
|
||||
export function filter<T>(array: T[], f: (x: T) => boolean): T[]
|
||||
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
|
||||
let result: T[];
|
||||
if (array) {
|
||||
result = [];
|
||||
for (const item of array) {
|
||||
if (f(item)) {
|
||||
result.push(item);
|
||||
const len = array.length;
|
||||
let i = 0;
|
||||
while (i < len && f(array[i])) i++;
|
||||
if (i < len) {
|
||||
const result = array.slice(0, i);
|
||||
i++;
|
||||
while (i < len) {
|
||||
const item = array[i];
|
||||
if (f(item)) {
|
||||
result.push(item);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return array;
|
||||
}
|
||||
|
||||
export function removeWhere<T>(array: T[], f: (x: T) => boolean): boolean {
|
||||
let outIndex = 0;
|
||||
for (const item of array) {
|
||||
if (!f(item)) {
|
||||
array[outIndex] = item;
|
||||
outIndex++;
|
||||
}
|
||||
}
|
||||
if (outIndex !== array.length) {
|
||||
array.length = outIndex;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function filterMutate<T>(array: T[], f: (x: T) => boolean): void {
|
||||
@@ -160,37 +252,174 @@ namespace ts {
|
||||
array.length = outIndex;
|
||||
}
|
||||
|
||||
export function map<T, U>(array: T[], f: (x: T) => U): U[] {
|
||||
export function map<T, U>(array: T[], f: (x: T, i: number) => U): U[] {
|
||||
let result: U[];
|
||||
if (array) {
|
||||
result = [];
|
||||
for (const v of array) {
|
||||
result.push(f(v));
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const v = array[i];
|
||||
result.push(f(v, i));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens an array containing a mix of array or non-array elements.
|
||||
*
|
||||
* @param array The array to flatten.
|
||||
*/
|
||||
export function flatten<T>(array: (T | T[])[]): T[] {
|
||||
let result: T[];
|
||||
if (array) {
|
||||
result = [];
|
||||
for (const v of array) {
|
||||
if (v) {
|
||||
if (isArray(v)) {
|
||||
addRange(result, v);
|
||||
}
|
||||
else {
|
||||
result.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps an array. If the mapped value is an array, it is spread into the result.
|
||||
*
|
||||
* @param array The array to map.
|
||||
* @param mapfn The callback used to map the result into one or more values.
|
||||
*/
|
||||
export function flatMap<T, U>(array: T[], mapfn: (x: T, i: number) => U | U[]): U[] {
|
||||
let result: U[];
|
||||
if (array) {
|
||||
result = [];
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const v = mapfn(array[i], i);
|
||||
if (v) {
|
||||
if (isArray(v)) {
|
||||
addRange(result, v);
|
||||
}
|
||||
else {
|
||||
result.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the first matching span of elements and returns a tuple of the first span
|
||||
* and the remaining elements.
|
||||
*/
|
||||
export function span<T>(array: T[], f: (x: T, i: number) => boolean): [T[], T[]] {
|
||||
if (array) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (!f(array[i], i)) {
|
||||
return [array.slice(0, i), array.slice(i)];
|
||||
}
|
||||
}
|
||||
return [array.slice(0), []];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps contiguous spans of values with the same key.
|
||||
*
|
||||
* @param array The array to map.
|
||||
* @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, start: number, end: number) => U): U[] {
|
||||
let result: U[];
|
||||
if (array) {
|
||||
result = [];
|
||||
const len = array.length;
|
||||
let previousKey: K;
|
||||
let key: K;
|
||||
let start = 0;
|
||||
let pos = 0;
|
||||
while (start < len) {
|
||||
while (pos < len) {
|
||||
const value = array[pos];
|
||||
key = keyfn(value, pos);
|
||||
if (pos === 0) {
|
||||
previousKey = key;
|
||||
}
|
||||
else if (key !== previousKey) {
|
||||
break;
|
||||
}
|
||||
|
||||
pos++;
|
||||
}
|
||||
|
||||
if (start < pos) {
|
||||
const v = mapfn(array.slice(start, pos), previousKey, start, pos);
|
||||
if (v) {
|
||||
result.push(v);
|
||||
}
|
||||
|
||||
start = pos;
|
||||
}
|
||||
|
||||
previousKey = key;
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function concatenate<T>(array1: T[], array2: T[]): T[] {
|
||||
if (!array2 || !array2.length) return array1;
|
||||
if (!array1 || !array1.length) return array2;
|
||||
|
||||
return array1.concat(array2);
|
||||
return [...array1, ...array2];
|
||||
}
|
||||
|
||||
export function deduplicate<T>(array: T[], areEqual?: (a: T, b: T) => boolean): T[] {
|
||||
let result: T[];
|
||||
if (array) {
|
||||
result = [];
|
||||
for (const item of array) {
|
||||
if (!contains(result, item, areEqual)) {
|
||||
result.push(item);
|
||||
loop: for (const item of array) {
|
||||
for (const res of result) {
|
||||
if (areEqual ? areEqual(res, item) : res === item) {
|
||||
continue loop;
|
||||
}
|
||||
}
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compacts an array, removing any falsey elements.
|
||||
*/
|
||||
export function compact<T>(array: T[]): T[] {
|
||||
let result: T[];
|
||||
if (array) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const v = array[i];
|
||||
if (result || !v) {
|
||||
if (!result) {
|
||||
result = array.slice(0, i);
|
||||
}
|
||||
if (v) {
|
||||
result.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result || array;
|
||||
}
|
||||
|
||||
export function sum(array: any[], prop: string): number {
|
||||
let result = 0;
|
||||
for (const v of array) {
|
||||
@@ -202,7 +431,9 @@ namespace ts {
|
||||
export function addRange<T>(to: T[], from: T[]): void {
|
||||
if (to && from) {
|
||||
for (const v of from) {
|
||||
to.push(v);
|
||||
if (v !== undefined) {
|
||||
to.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,15 +448,31 @@ namespace ts {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function firstOrUndefined<T>(array: T[]): T {
|
||||
return array && array.length > 0
|
||||
? array[0]
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function singleOrUndefined<T>(array: T[]): T {
|
||||
return array && array.length === 1
|
||||
? array[0]
|
||||
: 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.
|
||||
*/
|
||||
export function lastOrUndefined<T>(array: T[]): T {
|
||||
if (array.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return array[array.length - 1];
|
||||
return array && array.length > 0
|
||||
? array[array.length - 1]
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -257,14 +504,15 @@ namespace ts {
|
||||
return ~low;
|
||||
}
|
||||
|
||||
export function reduceLeft<T>(array: T[], f: (a: T, x: T) => T): T;
|
||||
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
|
||||
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
|
||||
if (array) {
|
||||
const count = array.length;
|
||||
if (count > 0) {
|
||||
let pos = 0;
|
||||
let result: T | U;
|
||||
export function reduceLeft<T, U>(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
|
||||
export function reduceLeft<T>(array: T[], f: (memo: T, value: T, i: number) => T): T;
|
||||
export function reduceLeft<T>(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T {
|
||||
if (array && array.length > 0) {
|
||||
const size = array.length;
|
||||
if (size > 0) {
|
||||
let pos = start === undefined || start < 0 ? 0 : start;
|
||||
const end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
|
||||
let result: T;
|
||||
if (arguments.length <= 2) {
|
||||
result = array[pos];
|
||||
pos++;
|
||||
@@ -272,23 +520,25 @@ namespace ts {
|
||||
else {
|
||||
result = initial;
|
||||
}
|
||||
while (pos < count) {
|
||||
result = f(<U>result, array[pos]);
|
||||
while (pos <= end) {
|
||||
result = f(result, array[pos], pos);
|
||||
pos++;
|
||||
}
|
||||
return <U>result;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return initial;
|
||||
}
|
||||
|
||||
export function reduceRight<T>(array: T[], f: (a: T, x: T) => T): T;
|
||||
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
|
||||
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
|
||||
export function reduceRight<T, U>(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
|
||||
export function reduceRight<T>(array: T[], f: (memo: T, value: T, i: number) => T): T;
|
||||
export function reduceRight<T>(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T {
|
||||
if (array) {
|
||||
let pos = array.length - 1;
|
||||
if (pos >= 0) {
|
||||
let result: T | U;
|
||||
const size = array.length;
|
||||
if (size > 0) {
|
||||
let pos = start === undefined || start > size - 1 ? size - 1 : start;
|
||||
const end = count === undefined || pos - count < 0 ? 0 : pos - count;
|
||||
let result: T;
|
||||
if (arguments.length <= 2) {
|
||||
result = array[pos];
|
||||
pos--;
|
||||
@@ -296,11 +546,11 @@ namespace ts {
|
||||
else {
|
||||
result = initial;
|
||||
}
|
||||
while (pos >= 0) {
|
||||
result = f(<U>result, array[pos]);
|
||||
while (pos >= end) {
|
||||
result = f(result, array[pos], pos);
|
||||
pos--;
|
||||
}
|
||||
return <U>result;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return initial;
|
||||
@@ -308,78 +558,142 @@ namespace ts {
|
||||
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
|
||||
export function hasProperty<T>(map: Map<T>, key: string): boolean {
|
||||
/**
|
||||
* Indicates whether a map-like contains an own property with the specified key.
|
||||
*
|
||||
* NOTE: This is intended for use only with MapLike<T> objects. For Map<T> objects, use
|
||||
* the 'in' operator.
|
||||
*
|
||||
* @param map A map-like.
|
||||
* @param key A property key.
|
||||
*/
|
||||
export function hasProperty<T>(map: MapLike<T>, key: string): boolean {
|
||||
return hasOwnProperty.call(map, key);
|
||||
}
|
||||
|
||||
export function getKeys<T>(map: Map<T>): string[] {
|
||||
/**
|
||||
* Gets the value of an owned property in a map-like.
|
||||
*
|
||||
* NOTE: This is intended for use only with MapLike<T> objects. For Map<T> objects, use
|
||||
* an indexer.
|
||||
*
|
||||
* @param map A map-like.
|
||||
* @param key A property key.
|
||||
*/
|
||||
export function getProperty<T>(map: MapLike<T>, key: string): T | undefined {
|
||||
return hasOwnProperty.call(map, key) ? map[key] : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the owned, enumerable property keys of a map-like.
|
||||
*
|
||||
* NOTE: This is intended for use with MapLike<T> objects. For Map<T> objects, use
|
||||
* Object.keys instead as it offers better performance.
|
||||
*
|
||||
* @param map A map-like.
|
||||
*/
|
||||
export function getOwnKeys<T>(map: MapLike<T>): string[] {
|
||||
const keys: string[] = [];
|
||||
for (const key in map) {
|
||||
for (const key in map) if (hasOwnProperty.call(map, key)) {
|
||||
keys.push(key);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export function getProperty<T>(map: Map<T>, key: string): T {
|
||||
return hasOwnProperty.call(map, key) ? map[key] : undefined;
|
||||
/**
|
||||
* Enumerates the properties of a Map<T>, invoking a callback and returning the first truthy result.
|
||||
*
|
||||
* @param map A map for which properties should be enumerated.
|
||||
* @param callback A callback to invoke for each property.
|
||||
*/
|
||||
export function forEachProperty<T, U>(map: Map<T>, callback: (value: T, key: string) => U): U {
|
||||
let result: U;
|
||||
for (const key in map) {
|
||||
if (result = callback(map[key], key)) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function isEmpty<T>(map: Map<T>) {
|
||||
for (const id in map) {
|
||||
if (hasProperty(map, id)) {
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Returns true if a Map<T> has some matching property.
|
||||
*
|
||||
* @param map A map whose properties should be tested.
|
||||
* @param predicate An optional callback used to test each property.
|
||||
*/
|
||||
export function someProperties<T>(map: Map<T>, predicate?: (value: T, key: string) => boolean) {
|
||||
for (const key in map) {
|
||||
if (!predicate || predicate(map[key], key)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a shallow copy of the properties from a source Map<T> to a target MapLike<T>
|
||||
*
|
||||
* @param source A map from which properties should be copied.
|
||||
* @param target A map to which properties should be copied.
|
||||
*/
|
||||
export function copyProperties<T>(source: Map<T>, target: MapLike<T>): void {
|
||||
for (const key in source) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce the properties of a map.
|
||||
*
|
||||
* NOTE: This is intended for use with Map<T> objects. For MapLike<T> objects, use
|
||||
* reduceOwnProperties instead as it offers better runtime safety.
|
||||
*
|
||||
* @param map The map to reduce
|
||||
* @param callback An aggregation function that is called for each entry in the map
|
||||
* @param initial The initial value for the reduction.
|
||||
*/
|
||||
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
|
||||
let result = initial;
|
||||
for (const key in map) {
|
||||
result = callback(result, map[key], String(key));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce the properties defined on a map-like (but not from its prototype chain).
|
||||
*
|
||||
* NOTE: This is intended for use with MapLike<T> objects. For Map<T> objects, use
|
||||
* reduceProperties instead as it offers better performance.
|
||||
*
|
||||
* @param map The map-like to reduce
|
||||
* @param callback An aggregation function that is called for each entry in the map
|
||||
* @param initial The initial value for the reduction.
|
||||
*/
|
||||
export function reduceOwnProperties<T, U>(map: MapLike<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
|
||||
let result = initial;
|
||||
for (const key in map) if (hasOwnProperty.call(map, key)) {
|
||||
result = callback(result, map[key], String(key));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a shallow equality comparison of the contents of two map-likes.
|
||||
*
|
||||
* @param left A map-like whose properties should be compared.
|
||||
* @param right A map-like whose properties should be compared.
|
||||
*/
|
||||
export function equalOwnProperties<T>(left: MapLike<T>, right: MapLike<T>, equalityComparer?: (left: T, right: T) => boolean) {
|
||||
if (left === right) return true;
|
||||
if (!left || !right) return false;
|
||||
for (const key in left) if (hasOwnProperty.call(left, key)) {
|
||||
if (!hasOwnProperty.call(right, key) === undefined) return false;
|
||||
if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false;
|
||||
}
|
||||
for (const key in right) if (hasOwnProperty.call(right, key)) {
|
||||
if (!hasOwnProperty.call(left, key)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function clone<T>(object: T): T {
|
||||
const result: any = {};
|
||||
for (const id in object) {
|
||||
result[id] = (<any>object)[id];
|
||||
}
|
||||
return <T>result;
|
||||
}
|
||||
|
||||
export function extend<T1 extends Map<{}>, T2 extends Map<{}>>(first: T1 , second: T2): T1 & T2 {
|
||||
const result: T1 & T2 = <any>{};
|
||||
for (const id in first) {
|
||||
(result as any)[id] = first[id];
|
||||
}
|
||||
for (const id in second) {
|
||||
if (!hasProperty(result, id)) {
|
||||
(result as any)[id] = second[id];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U {
|
||||
let result: U;
|
||||
for (const id in map) {
|
||||
if (result = callback(map[id])) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U {
|
||||
let result: U;
|
||||
for (const id in map) {
|
||||
if (result = callback(id)) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function lookUp<T>(map: Map<T>, key: string): T {
|
||||
return hasProperty(map, key) ? map[key] : undefined;
|
||||
}
|
||||
|
||||
export function copyMap<T>(source: Map<T>, target: Map<T>): void {
|
||||
for (const p in source) {
|
||||
target[p] = source[p];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a map from the elements of an array.
|
||||
*
|
||||
@@ -390,34 +704,80 @@ namespace ts {
|
||||
* the same key with the given 'makeKey' function, then the element with the higher
|
||||
* index in the array will be the one associated with the produced key.
|
||||
*/
|
||||
export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T> {
|
||||
const result: Map<T> = {};
|
||||
export function arrayToMap<T>(array: T[], makeKey: (value: T) => string): Map<T>;
|
||||
export function arrayToMap<T, U>(array: T[], makeKey: (value: T) => string, makeValue: (value: T) => U): Map<U>;
|
||||
export function arrayToMap<T, U>(array: T[], makeKey: (value: T) => string, makeValue?: (value: T) => U): Map<T | U> {
|
||||
const result = createMap<T | U>();
|
||||
for (const value of array) {
|
||||
result[makeKey(value)] = makeValue ? makeValue(value) : value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
forEach(array, value => {
|
||||
result[makeKey(value)] = value;
|
||||
});
|
||||
export function isEmpty<T>(map: Map<T>) {
|
||||
for (const id in map) {
|
||||
if (hasProperty(map, id)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function cloneMap<T>(map: Map<T>) {
|
||||
const clone = createMap<T>();
|
||||
copyProperties(map, clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
export function clone<T>(object: T): T {
|
||||
const result: any = {};
|
||||
for (const id in object) {
|
||||
if (hasOwnProperty.call(object, id)) {
|
||||
result[id] = (<any>object)[id];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function extend<T1, T2>(first: T1 , second: T2): T1 & T2 {
|
||||
const result: T1 & T2 = <any>{};
|
||||
for (const id in second) if (hasOwnProperty.call(second, id)) {
|
||||
(result as any)[id] = (second as any)[id];
|
||||
}
|
||||
for (const id in first) if (hasOwnProperty.call(first, id)) {
|
||||
(result as any)[id] = (first as any)[id];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce the properties of a map.
|
||||
*
|
||||
* @param map The map to reduce
|
||||
* @param callback An aggregation function that is called for each entry in the map
|
||||
* @param initial The initial value for the reduction.
|
||||
* Adds the value to an array of values associated with the key, and returns the array.
|
||||
* Creates the array if it does not already exist.
|
||||
*/
|
||||
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
|
||||
let result = initial;
|
||||
if (map) {
|
||||
for (const key in map) {
|
||||
if (hasProperty(map, key)) {
|
||||
result = callback(result, map[key], String(key));
|
||||
}
|
||||
export function multiMapAdd<V>(map: Map<V[]>, key: string, value: V): V[] {
|
||||
const values = map[key];
|
||||
if (values) {
|
||||
values.push(value);
|
||||
return values;
|
||||
}
|
||||
else {
|
||||
return map[key] = [value];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a value from an array of values associated with the key.
|
||||
* Does not preserve the order of those values.
|
||||
* Does nothing if `key` is not in `map`, or `value` is not in `map[key]`.
|
||||
*/
|
||||
export function multiMapRemove<V>(map: Map<V[]>, key: string, value: V): void {
|
||||
const values = map[key];
|
||||
if (values) {
|
||||
unorderedRemoveItem(values, value);
|
||||
if (!values.length) {
|
||||
delete map[key];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,9 +807,7 @@ namespace ts {
|
||||
export let localizedDiagnosticMessages: Map<string> = undefined;
|
||||
|
||||
export function getLocaleSpecificMessage(message: DiagnosticMessage) {
|
||||
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key]
|
||||
? localizedDiagnosticMessages[message.key]
|
||||
: message.message;
|
||||
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message;
|
||||
}
|
||||
|
||||
export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic;
|
||||
@@ -932,11 +1290,29 @@ namespace ts {
|
||||
const reservedCharacterPattern = /[^\w\s\/]/g;
|
||||
const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question];
|
||||
|
||||
/**
|
||||
* Matches any single directory segment unless it is the last segment and a .min.js file
|
||||
* Breakdown:
|
||||
* [^./] # matches everything up to the first . character (excluding directory seperators)
|
||||
* (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
|
||||
*/
|
||||
const singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*";
|
||||
const singleAsteriskRegexFragmentOther = "[^/]*";
|
||||
|
||||
export function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude") {
|
||||
if (specs === undefined || specs.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther;
|
||||
const singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther;
|
||||
|
||||
/**
|
||||
* Regex for the ** wildcard. Matches any number of subdirectories. When used for including
|
||||
* files or directories, does not match subdirectories that start with a . character
|
||||
*/
|
||||
const doubleAsteriskRegexFragment = usage === "exclude" ? "(/.+?)?" : "(/[^/.][^/]*)*?";
|
||||
|
||||
let pattern = "";
|
||||
let hasWrittenSubpattern = false;
|
||||
spec: for (const spec of specs) {
|
||||
@@ -957,13 +1333,13 @@ namespace ts {
|
||||
components[0] = removeTrailingDirectorySeparator(components[0]);
|
||||
|
||||
let optionalCount = 0;
|
||||
for (const component of components) {
|
||||
for (let component of components) {
|
||||
if (component === "**") {
|
||||
if (hasRecursiveDirectoryWildcard) {
|
||||
continue spec;
|
||||
}
|
||||
|
||||
subpattern += "(/.+?)?";
|
||||
subpattern += doubleAsteriskRegexFragment;
|
||||
hasRecursiveDirectoryWildcard = true;
|
||||
hasWrittenComponent = true;
|
||||
}
|
||||
@@ -977,6 +1353,20 @@ namespace ts {
|
||||
subpattern += directorySeparator;
|
||||
}
|
||||
|
||||
if (usage !== "exclude") {
|
||||
// The * and ? wildcards should not match directories or files that start with . if they
|
||||
// appear first in a component. Dotted directories and files can be included explicitly
|
||||
// like so: **/.*/.*
|
||||
if (component.charCodeAt(0) === CharacterCodes.asterisk) {
|
||||
subpattern += "([^./]" + singleAsteriskRegexFragment + ")?";
|
||||
component = component.substr(1);
|
||||
}
|
||||
else if (component.charCodeAt(0) === CharacterCodes.question) {
|
||||
subpattern += "[^./]";
|
||||
component = component.substr(1);
|
||||
}
|
||||
}
|
||||
|
||||
subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
|
||||
hasWrittenComponent = true;
|
||||
}
|
||||
@@ -1002,8 +1392,16 @@ namespace ts {
|
||||
return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$");
|
||||
}
|
||||
|
||||
function replaceWildcardCharacter(match: string) {
|
||||
return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match;
|
||||
function replaceWildCardCharacterFiles(match: string) {
|
||||
return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles);
|
||||
}
|
||||
|
||||
function replaceWildCardCharacterOther(match: string) {
|
||||
return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther);
|
||||
}
|
||||
|
||||
function replaceWildcardCharacter(match: string, singleAsteriskRegexFragment: string) {
|
||||
return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
|
||||
}
|
||||
|
||||
export interface FileSystemEntries {
|
||||
@@ -1145,6 +1543,8 @@ namespace ts {
|
||||
* List of supported extensions in order of file resolution precedence.
|
||||
*/
|
||||
export const supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"];
|
||||
/** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
|
||||
export const supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"];
|
||||
export const supportedJavascriptExtensions = [".js", ".jsx"];
|
||||
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
|
||||
|
||||
@@ -1227,8 +1627,12 @@ namespace ts {
|
||||
return path;
|
||||
}
|
||||
|
||||
export function tryRemoveExtension(path: string, extension: string): string {
|
||||
return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined;
|
||||
export function tryRemoveExtension(path: string, extension: string): string | undefined {
|
||||
return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
|
||||
}
|
||||
|
||||
export function removeExtension(path: string, extension: string): string {
|
||||
return path.substring(0, path.length - extension.length);
|
||||
}
|
||||
|
||||
export function isJsxOrTsxExtension(ext: string): boolean {
|
||||
@@ -1263,11 +1667,16 @@ namespace ts {
|
||||
}
|
||||
|
||||
function Node(this: Node, kind: SyntaxKind, pos: number, end: number) {
|
||||
this.id = 0;
|
||||
this.kind = kind;
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = NodeFlags.None;
|
||||
this.modifierFlagsCache = ModifierFlags.None;
|
||||
this.transformFlags = TransformFlags.None;
|
||||
this.parent = undefined;
|
||||
this.original = undefined;
|
||||
this.transformId = 0;
|
||||
}
|
||||
|
||||
export let objectAllocator: ObjectAllocator = {
|
||||
@@ -1288,10 +1697,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 {
|
||||
@@ -1308,22 +1720,70 @@ 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[]) {
|
||||
const copiedList: T[] = [];
|
||||
for (const e of list) {
|
||||
if (e !== item) {
|
||||
copiedList.push(e);
|
||||
export function getEnvironmentVariable(name: string, host?: CompilerHost) {
|
||||
if (host && host.getEnvironmentVariable) {
|
||||
return host.getEnvironmentVariable(name);
|
||||
}
|
||||
|
||||
if (sys && sys.getEnvironmentVariable) {
|
||||
return sys.getEnvironmentVariable(name);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/** Remove an item from an array, moving everything to its right one space left. */
|
||||
export function orderedRemoveItemAt<T>(array: T[], index: number): void {
|
||||
// This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
|
||||
for (let i = index; i < array.length - 1; i++) {
|
||||
array[i] = array[i + 1];
|
||||
}
|
||||
array.pop();
|
||||
}
|
||||
|
||||
export function unorderedRemoveItemAt<T>(array: T[], index: number): void {
|
||||
// Fill in the "hole" left at `index`.
|
||||
array[index] = array[array.length - 1];
|
||||
array.pop();
|
||||
}
|
||||
|
||||
/** Remove the *first* occurrence of `item` from the array. */
|
||||
export function unorderedRemoveItem<T>(array: T[], item: T): void {
|
||||
unorderedRemoveFirstItemWhere(array, element => element === item);
|
||||
}
|
||||
|
||||
/** Remove the *first* element satisfying `predicate`. */
|
||||
function unorderedRemoveFirstItemWhere<T>(array: T[], predicate: (element: T) => boolean): void {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (predicate(array[i])) {
|
||||
unorderedRemoveItemAt(array, i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return copiedList;
|
||||
}
|
||||
|
||||
export function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string {
|
||||
return useCaseSensitivefileNames
|
||||
export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string {
|
||||
return useCaseSensitiveFileNames
|
||||
? ((fileName) => fileName)
|
||||
: ((fileName) => fileName.toLowerCase());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -157,9 +157,7 @@ namespace ts {
|
||||
|
||||
if (usedTypeDirectiveReferences) {
|
||||
for (const directive in usedTypeDirectiveReferences) {
|
||||
if (hasProperty(usedTypeDirectiveReferences, directive)) {
|
||||
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
|
||||
}
|
||||
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,10 +267,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (!usedTypeDirectiveReferences) {
|
||||
usedTypeDirectiveReferences = {};
|
||||
usedTypeDirectiveReferences = createMap<string>();
|
||||
}
|
||||
for (const directive of typeReferenceDirectives) {
|
||||
if (!hasProperty(usedTypeDirectiveReferences, directive)) {
|
||||
if (!(directive in usedTypeDirectiveReferences)) {
|
||||
usedTypeDirectiveReferences[directive] = directive;
|
||||
}
|
||||
}
|
||||
@@ -376,7 +374,7 @@ namespace ts {
|
||||
const jsDocComments = getJsDocCommentsFromText(declaration, currentText);
|
||||
emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
|
||||
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
|
||||
emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange);
|
||||
emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeCommentRange);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,7 +395,7 @@ namespace ts {
|
||||
case SyntaxKind.NullKeyword:
|
||||
case SyntaxKind.NeverKeyword:
|
||||
case SyntaxKind.ThisType:
|
||||
case SyntaxKind.StringLiteralType:
|
||||
case SyntaxKind.LiteralType:
|
||||
return writeTextOfNode(currentText, type);
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>type);
|
||||
@@ -441,7 +439,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function emitEntityName(entityName: EntityName | PropertyAccessExpression) {
|
||||
function emitEntityName(entityName: EntityNameOrEntityNameExpression) {
|
||||
const visibilityResult = resolver.isEntityNameVisible(entityName,
|
||||
// Aliases can be written asynchronously so use correct enclosing declaration
|
||||
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
|
||||
@@ -452,9 +450,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
|
||||
if (isSupportedExpressionWithTypeArguments(node)) {
|
||||
if (isEntityNameExpression(node.expression)) {
|
||||
Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression);
|
||||
emitEntityName(<Identifier | PropertyAccessExpression>node.expression);
|
||||
emitEntityName(node.expression);
|
||||
if (node.typeArguments) {
|
||||
write("<");
|
||||
emitCommaList(node.typeArguments, emitType);
|
||||
@@ -537,14 +535,14 @@ namespace ts {
|
||||
// do not need to keep track of created temp names.
|
||||
function getExportDefaultTempVariableName(): string {
|
||||
const baseName = "_default";
|
||||
if (!hasProperty(currentIdentifiers, baseName)) {
|
||||
if (!(baseName in currentIdentifiers)) {
|
||||
return baseName;
|
||||
}
|
||||
let count = 0;
|
||||
while (true) {
|
||||
count++;
|
||||
const name = baseName + "_" + count;
|
||||
if (!hasProperty(currentIdentifiers, name)) {
|
||||
if (!(name in currentIdentifiers)) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -657,12 +655,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) {
|
||||
@@ -671,21 +670,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 ");
|
||||
}
|
||||
}
|
||||
@@ -694,7 +693,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 ");
|
||||
@@ -733,7 +732,7 @@ namespace ts {
|
||||
|
||||
function writeImportDeclaration(node: ImportDeclaration) {
|
||||
emitJsDocComments(node);
|
||||
if (node.flags & NodeFlags.Export) {
|
||||
if (hasModifier(node, ModifierFlags.Export)) {
|
||||
write("export ");
|
||||
}
|
||||
write("import ");
|
||||
@@ -928,7 +927,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[]) {
|
||||
@@ -978,7 +977,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) {
|
||||
@@ -1019,7 +1018,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function emitTypeOfTypeReference(node: ExpressionWithTypeArguments) {
|
||||
if (isSupportedExpressionWithTypeArguments(node)) {
|
||||
if (isEntityNameExpression(node.expression)) {
|
||||
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
|
||||
}
|
||||
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
|
||||
@@ -1057,7 +1056,7 @@ namespace ts {
|
||||
function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) {
|
||||
if (constructorDeclaration) {
|
||||
forEach(constructorDeclaration.parameters, param => {
|
||||
if (param.flags & NodeFlags.ParameterPropertyModifier) {
|
||||
if (hasModifier(param, ModifierFlags.ParameterPropertyModifier)) {
|
||||
emitPropertyDeclaration(param);
|
||||
}
|
||||
});
|
||||
@@ -1066,7 +1065,7 @@ namespace ts {
|
||||
|
||||
emitJsDocComments(node);
|
||||
emitModuleElementDeclarationFlags(node);
|
||||
if (node.flags & NodeFlags.Abstract) {
|
||||
if (hasModifier(node, ModifierFlags.Abstract)) {
|
||||
write("abstract ");
|
||||
}
|
||||
|
||||
@@ -1116,7 +1115,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
emitJsDocComments(node);
|
||||
emitClassMemberDeclarationFlags(node.flags);
|
||||
emitClassMemberDeclarationFlags(getModifierFlags(node));
|
||||
emitVariableDeclaration(<VariableDeclaration>node);
|
||||
write(";");
|
||||
writeLine();
|
||||
@@ -1134,14 +1133,16 @@ namespace ts {
|
||||
// it if it's not a well known symbol. In that case, the text of the name will be exactly
|
||||
// what we want, namely the name expression enclosed in brackets.
|
||||
writeTextOfNode(currentText, node.name);
|
||||
// If optional property emit ?
|
||||
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.Parameter) && hasQuestionToken(node)) {
|
||||
// If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor
|
||||
// we don't want to emit property declaration with "?"
|
||||
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature ||
|
||||
(node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) {
|
||||
write("?");
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1158,7 +1159,7 @@ 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) {
|
||||
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 :
|
||||
@@ -1269,9 +1270,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) {
|
||||
@@ -1302,7 +1303,7 @@ namespace ts {
|
||||
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) {
|
||||
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;
|
||||
@@ -1320,7 +1321,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
else {
|
||||
if (accessorWithTypeAnnotation.flags & NodeFlags.Static) {
|
||||
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 :
|
||||
@@ -1356,7 +1357,7 @@ namespace ts {
|
||||
emitModuleElementDeclarationFlags(node);
|
||||
}
|
||||
else if (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.Constructor) {
|
||||
emitClassMemberDeclarationFlags(node.flags);
|
||||
emitClassMemberDeclarationFlags(getModifierFlags(node));
|
||||
}
|
||||
if (node.kind === SyntaxKind.FunctionDeclaration) {
|
||||
write("function ");
|
||||
@@ -1387,7 +1388,7 @@ namespace ts {
|
||||
|
||||
if (node.kind === SyntaxKind.IndexSignature) {
|
||||
// Index signature can have readonly modifier
|
||||
emitClassMemberDeclarationFlags(node.flags);
|
||||
emitClassMemberDeclarationFlags(getModifierFlags(node));
|
||||
write("[");
|
||||
}
|
||||
else {
|
||||
@@ -1428,7 +1429,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);
|
||||
}
|
||||
|
||||
@@ -1468,7 +1469,7 @@ namespace ts {
|
||||
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
case SyntaxKind.MethodSignature:
|
||||
if (node.flags & NodeFlags.Static) {
|
||||
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 :
|
||||
@@ -1534,7 +1535,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -1570,7 +1571,7 @@ namespace ts {
|
||||
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
case SyntaxKind.MethodSignature:
|
||||
if (node.parent.flags & NodeFlags.Static) {
|
||||
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 :
|
||||
|
||||
@@ -827,10 +827,6 @@
|
||||
"category": "Error",
|
||||
"code": 1308
|
||||
},
|
||||
"Async functions are only available when targeting ECMAScript 2015 or higher.": {
|
||||
"category": "Error",
|
||||
"code": 1311
|
||||
},
|
||||
"'=' can only be used in an object literal property inside a destructuring assignment.": {
|
||||
"category": "Error",
|
||||
"code": 1312
|
||||
@@ -1067,10 +1063,6 @@
|
||||
"category": "Error",
|
||||
"code": 2353
|
||||
},
|
||||
"No best common type exists among return expressions.": {
|
||||
"category": "Error",
|
||||
"code": 2354
|
||||
},
|
||||
"A function whose declared type is neither 'void' nor 'any' must return a value.": {
|
||||
"category": "Error",
|
||||
"code": 2355
|
||||
@@ -1635,10 +1627,6 @@
|
||||
"category": "Error",
|
||||
"code": 2503
|
||||
},
|
||||
"No best common type exists among yield expressions.": {
|
||||
"category": "Error",
|
||||
"code": 2504
|
||||
},
|
||||
"A generator cannot have a 'void' type annotation.": {
|
||||
"category": "Error",
|
||||
"code": 2505
|
||||
@@ -1703,7 +1691,7 @@
|
||||
"category": "Error",
|
||||
"code": 2521
|
||||
},
|
||||
"The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression.": {
|
||||
"The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method.": {
|
||||
"category": "Error",
|
||||
"code": 2522
|
||||
},
|
||||
@@ -1755,6 +1743,10 @@
|
||||
"category": "Error",
|
||||
"code": 2534
|
||||
},
|
||||
"Enum type '{0}' has members with initializers that are not literals.": {
|
||||
"category": "Error",
|
||||
"code": 2535
|
||||
},
|
||||
"JSX element attributes type '{0}' may not be a union type.": {
|
||||
"category": "Error",
|
||||
"code": 2600
|
||||
@@ -1943,6 +1935,18 @@
|
||||
"category": "Error",
|
||||
"code": 2689
|
||||
},
|
||||
"A class must be declared after its base class.": {
|
||||
"category": "Error",
|
||||
"code": 2690
|
||||
},
|
||||
"An import path cannot end with a '{0}' extension. Consider importing '{1}' instead.": {
|
||||
"category": "Error",
|
||||
"code": 2691
|
||||
},
|
||||
"'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible.": {
|
||||
"category": "Error",
|
||||
"code": 2692
|
||||
},
|
||||
"Import declaration '{0}' is using private name '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 4000
|
||||
@@ -2223,7 +2227,7 @@
|
||||
"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.": {
|
||||
"Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict.": {
|
||||
"category": "Message",
|
||||
"code": 4090
|
||||
},
|
||||
@@ -2336,6 +2340,10 @@
|
||||
"category": "Error",
|
||||
"code": 5065
|
||||
},
|
||||
"Substitutions for pattern '{0}' shouldn't be an empty array.": {
|
||||
"category": "Error",
|
||||
"code": 5066
|
||||
},
|
||||
"Concatenate and emit output to single file.": {
|
||||
"category": "Message",
|
||||
"code": 6001
|
||||
@@ -2456,6 +2464,10 @@
|
||||
"category": "Message",
|
||||
"code": 6038
|
||||
},
|
||||
"STRATEGY": {
|
||||
"category": "Message",
|
||||
"code": 6039
|
||||
},
|
||||
"Compilation complete. Watching for file changes.": {
|
||||
"category": "Message",
|
||||
"code": 6042
|
||||
@@ -2800,11 +2812,11 @@
|
||||
"category": "Error",
|
||||
"code": 6133
|
||||
},
|
||||
"Report errors on unused locals.": {
|
||||
"Report errors on unused locals.": {
|
||||
"category": "Message",
|
||||
"code": 6134
|
||||
},
|
||||
"Report errors on unused parameters.": {
|
||||
"Report errors on unused parameters.": {
|
||||
"category": "Message",
|
||||
"code": 6135
|
||||
},
|
||||
@@ -2816,6 +2828,14 @@
|
||||
"category": "Message",
|
||||
"code": 6137
|
||||
},
|
||||
"Property '{0}' is declared but never used.": {
|
||||
"category": "Error",
|
||||
"code": 6138
|
||||
},
|
||||
"Import emit helpers from 'tslib'.": {
|
||||
"category": "Message",
|
||||
"code": 6139
|
||||
},
|
||||
"Variable '{0}' implicitly has an '{1}' type.": {
|
||||
"category": "Error",
|
||||
"code": 7005
|
||||
@@ -2848,10 +2868,6 @@
|
||||
"category": "Error",
|
||||
"code": 7015
|
||||
},
|
||||
"Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation.": {
|
||||
"category": "Error",
|
||||
"code": 7016
|
||||
},
|
||||
"Index signature of object type implicitly has an 'any' type.": {
|
||||
"category": "Error",
|
||||
"code": 7017
|
||||
@@ -2908,6 +2924,14 @@
|
||||
"category": "Error",
|
||||
"code": 7031
|
||||
},
|
||||
"Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation.": {
|
||||
"category": "Error",
|
||||
"code": 7032
|
||||
},
|
||||
"Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation.": {
|
||||
"category": "Error",
|
||||
"code": 7033
|
||||
},
|
||||
"You cannot rename this element.": {
|
||||
"category": "Error",
|
||||
"code": 8000
|
||||
|
||||
+2840
-8283
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+511
-448
File diff suppressed because it is too large
Load Diff
+52
-66
@@ -2,75 +2,61 @@
|
||||
namespace ts {
|
||||
declare const performance: { now?(): number } | undefined;
|
||||
/** Gets a timestamp with (at least) ms resolution */
|
||||
export const timestamp = typeof performance !== "undefined" && performance.now ? performance.now : Date.now ? Date.now : () => +(new Date());
|
||||
export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now() : Date.now ? Date.now : () => +(new Date());
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
/** Performance measurements for the compiler. */
|
||||
namespace ts.performance {
|
||||
/** Performance measurements for the compiler. */
|
||||
declare const onProfilerEvent: { (markName: string): void; profiler: boolean; };
|
||||
let profilerEvent: (markName: string) => void;
|
||||
let counters: Map<number>;
|
||||
|
||||
const profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true
|
||||
? onProfilerEvent
|
||||
: (markName: string) => { };
|
||||
|
||||
let enabled = false;
|
||||
let profilerStart = 0;
|
||||
let counts: Map<number>;
|
||||
let marks: Map<number>;
|
||||
let measures: Map<number>;
|
||||
|
||||
/**
|
||||
* Emit a performance event if ts-profiler is connected. This is primarily used
|
||||
* to generate heap snapshots.
|
||||
* Marks a performance event.
|
||||
*
|
||||
* @param eventName A name for the event.
|
||||
* @param markName The name of the mark.
|
||||
*/
|
||||
export function emit(eventName: string) {
|
||||
if (profilerEvent) {
|
||||
profilerEvent(eventName);
|
||||
export function mark(markName: string) {
|
||||
if (enabled) {
|
||||
marks[markName] = timestamp();
|
||||
counts[markName] = (counts[markName] || 0) + 1;
|
||||
profilerEvent(markName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments a counter with the specified name.
|
||||
*
|
||||
* @param counterName The name of the counter.
|
||||
*/
|
||||
export function increment(counterName: string) {
|
||||
if (counters) {
|
||||
counters[counterName] = (getProperty(counters, counterName) || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the counter with the specified name.
|
||||
*
|
||||
* @param counterName The name of the counter.
|
||||
*/
|
||||
export function getCount(counterName: string) {
|
||||
return counters && getProperty(counters, counterName) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the start of a performance measurement.
|
||||
*/
|
||||
export function mark() {
|
||||
return measures ? timestamp() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a performance measurement with the specified name.
|
||||
*
|
||||
* @param measureName The name of the performance measurement.
|
||||
* @param marker The timestamp of the starting mark.
|
||||
* @param startMarkName The name of the starting mark. If not supplied, the point at which the
|
||||
* profiler was enabled is used.
|
||||
* @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
|
||||
* used.
|
||||
*/
|
||||
export function measure(measureName: string, marker: number) {
|
||||
if (measures) {
|
||||
measures[measureName] = (getProperty(measures, measureName) || 0) + (timestamp() - marker);
|
||||
export function measure(measureName: string, startMarkName?: string, endMarkName?: string) {
|
||||
if (enabled) {
|
||||
const end = endMarkName && marks[endMarkName] || timestamp();
|
||||
const start = startMarkName && marks[startMarkName] || profilerStart;
|
||||
measures[measureName] = (measures[measureName] || 0) + (end - start);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over each measure, performing some action
|
||||
*
|
||||
* @param cb The action to perform for each measure
|
||||
* Gets the number of times a marker was encountered.
|
||||
*
|
||||
* @param markName The name of the mark.
|
||||
*/
|
||||
export function forEachMeasure(cb: (measureName: string, duration: number) => void) {
|
||||
return forEachKey(measures, key => cb(key, measures[key]));
|
||||
export function getCount(markName: string) {
|
||||
return counts && counts[markName] || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,31 +65,31 @@ namespace ts.performance {
|
||||
* @param measureName The name of the measure whose durations should be accumulated.
|
||||
*/
|
||||
export function getDuration(measureName: string) {
|
||||
return measures && getProperty(measures, measureName) || 0;
|
||||
return measures && measures[measureName] || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over each measure, performing some action
|
||||
*
|
||||
* @param cb The action to perform for each measure
|
||||
*/
|
||||
export function forEachMeasure(cb: (measureName: string, duration: number) => void) {
|
||||
for (const key in measures) {
|
||||
cb(key, measures[key]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Enables (and resets) performance measurements for the compiler. */
|
||||
export function enable() {
|
||||
counters = { };
|
||||
measures = {
|
||||
"I/O Read": 0,
|
||||
"I/O Write": 0,
|
||||
"Program": 0,
|
||||
"Parse": 0,
|
||||
"Bind": 0,
|
||||
"Check": 0,
|
||||
"Emit": 0,
|
||||
};
|
||||
|
||||
profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true
|
||||
? onProfilerEvent
|
||||
: undefined;
|
||||
counts = createMap<number>();
|
||||
marks = createMap<number>();
|
||||
measures = createMap<number>();
|
||||
enabled = true;
|
||||
profilerStart = timestamp();
|
||||
}
|
||||
|
||||
/** Disables (and clears) performance measurements for the compiler. */
|
||||
/** Disables performance measurements for the compiler. */
|
||||
export function disable() {
|
||||
counters = undefined;
|
||||
measures = undefined;
|
||||
profilerEvent = undefined;
|
||||
enabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+179
-142
@@ -8,11 +8,9 @@ namespace ts {
|
||||
|
||||
const emptyArray: any[] = [];
|
||||
|
||||
const defaultTypeRoots = ["node_modules/@types"];
|
||||
|
||||
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
|
||||
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string {
|
||||
while (true) {
|
||||
const fileName = combinePaths(searchPath, "tsconfig.json");
|
||||
const fileName = combinePaths(searchPath, configName);
|
||||
if (fileExists(fileName)) {
|
||||
return fileName;
|
||||
}
|
||||
@@ -119,49 +117,31 @@ namespace ts {
|
||||
}
|
||||
|
||||
function tryReadTypesSection(packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string {
|
||||
let jsonContent: { typings?: string, types?: string, main?: string };
|
||||
try {
|
||||
const jsonText = state.host.readFile(packageJsonPath);
|
||||
jsonContent = jsonText ? <{ typings?: string, types?: string, main?: string }>JSON.parse(jsonText) : {};
|
||||
}
|
||||
catch (e) {
|
||||
// gracefully handle if readFile fails or returns not JSON
|
||||
jsonContent = {};
|
||||
const jsonContent = readJson(packageJsonPath, state.host);
|
||||
|
||||
function tryReadFromField(fieldName: string) {
|
||||
if (hasProperty(jsonContent, fieldName)) {
|
||||
const typesFile = (<any>jsonContent)[fieldName];
|
||||
if (typeof typesFile === "string") {
|
||||
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
|
||||
}
|
||||
return typesFilePath;
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let typesFile: string;
|
||||
let fieldName: string;
|
||||
// first try to read content of 'typings' section (backward compatibility)
|
||||
if (jsonContent.typings) {
|
||||
if (typeof jsonContent.typings === "string") {
|
||||
fieldName = "typings";
|
||||
typesFile = jsonContent.typings;
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings);
|
||||
}
|
||||
}
|
||||
}
|
||||
// then read 'types'
|
||||
if (!typesFile && jsonContent.types) {
|
||||
if (typeof jsonContent.types === "string") {
|
||||
fieldName = "types";
|
||||
typesFile = jsonContent.types;
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typesFile) {
|
||||
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
|
||||
}
|
||||
const typesFilePath = tryReadFromField("typings") || tryReadFromField("types");
|
||||
if (typesFilePath) {
|
||||
return typesFilePath;
|
||||
}
|
||||
|
||||
// Use the main module for inferring types if no types package specified and the allowJs is set
|
||||
if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") {
|
||||
if (state.traceEnabled) {
|
||||
@@ -173,9 +153,20 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readJson(path: string, host: ModuleResolutionHost): { typings?: string, types?: string, main?: string } {
|
||||
try {
|
||||
const jsonText = host.readFile(path);
|
||||
return jsonText ? JSON.parse(jsonText) : {};
|
||||
}
|
||||
catch (e) {
|
||||
// gracefully handle if readFile fails or returns not JSON
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
const typeReferenceExtensions = [".d.ts"];
|
||||
|
||||
function getEffectiveTypeRoots(options: CompilerOptions, host: ModuleResolutionHost) {
|
||||
export function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean, getCurrentDirectory?: () => string }): string[] | undefined {
|
||||
if (options.typeRoots) {
|
||||
return options.typeRoots;
|
||||
}
|
||||
@@ -188,12 +179,38 @@ namespace ts {
|
||||
currentDirectory = host.getCurrentDirectory();
|
||||
}
|
||||
|
||||
if (!currentDirectory) {
|
||||
return undefined;
|
||||
}
|
||||
return map(defaultTypeRoots, d => combinePaths(currentDirectory, d));
|
||||
return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path to every node_modules/@types directory from some ancestor directory.
|
||||
* Returns undefined if there are none.
|
||||
*/
|
||||
function getDefaultTypeRoots(currentDirectory: string, host: { directoryExists?: (directoryName: string) => boolean }): string[] | undefined {
|
||||
if (!host.directoryExists) {
|
||||
return [combinePaths(currentDirectory, nodeModulesAtTypes)];
|
||||
// And if it doesn't exist, tough.
|
||||
}
|
||||
|
||||
let typeRoots: string[];
|
||||
|
||||
while (true) {
|
||||
const atTypes = combinePaths(currentDirectory, nodeModulesAtTypes);
|
||||
if (host.directoryExists(atTypes)) {
|
||||
(typeRoots || (typeRoots = [])).push(atTypes);
|
||||
}
|
||||
|
||||
const parent = getDirectoryPath(currentDirectory);
|
||||
if (parent === currentDirectory) {
|
||||
break;
|
||||
}
|
||||
currentDirectory = parent;
|
||||
}
|
||||
|
||||
return typeRoots;
|
||||
}
|
||||
const nodeModulesAtTypes = combinePaths("node_modules", "@types");
|
||||
|
||||
/**
|
||||
* @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
|
||||
@@ -508,7 +525,7 @@ namespace ts {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
|
||||
}
|
||||
matchedPattern = matchPatternOrExact(getKeys(state.compilerOptions.paths), moduleName);
|
||||
matchedPattern = matchPatternOrExact(getOwnKeys(state.compilerOptions.paths), moduleName);
|
||||
}
|
||||
|
||||
if (matchedPattern) {
|
||||
@@ -668,24 +685,27 @@ namespace ts {
|
||||
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
|
||||
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
|
||||
*/
|
||||
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
|
||||
// First try to keep/add an extension: importing "./foo.ts" can be matched by a file "./foo.ts", and "./foo" by "./foo.d.ts"
|
||||
const resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
|
||||
if (resolvedByAddingOrKeepingExtension) {
|
||||
return resolvedByAddingOrKeepingExtension;
|
||||
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
|
||||
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
|
||||
const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
|
||||
if (resolvedByAddingExtension) {
|
||||
return resolvedByAddingExtension;
|
||||
}
|
||||
// Then try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one, e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
|
||||
|
||||
// If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
|
||||
// e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
|
||||
if (hasJavaScriptFileExtension(candidate)) {
|
||||
const extensionless = removeFileExtension(candidate);
|
||||
if (state.traceEnabled) {
|
||||
const extension = candidate.substring(extensionless.length);
|
||||
trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
|
||||
}
|
||||
return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
|
||||
return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
|
||||
}
|
||||
}
|
||||
|
||||
function loadModuleFromFileWorker(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
|
||||
/** Try to return an existing file that adds one of the `extensions` to `candidate`. */
|
||||
function tryAddingExtensions(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
|
||||
if (!onlyRecordFailures) {
|
||||
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
|
||||
const directory = getDirectoryPath(candidate);
|
||||
@@ -693,31 +713,29 @@ namespace ts {
|
||||
onlyRecordFailures = !directoryProbablyExists(directory, state.host);
|
||||
}
|
||||
}
|
||||
return forEach(extensions, tryLoad);
|
||||
return forEach(extensions, ext =>
|
||||
!(state.skipTsx && isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state));
|
||||
}
|
||||
|
||||
function tryLoad(ext: string): string {
|
||||
if (state.skipTsx && isJsxOrTsxExtension(ext)) {
|
||||
return undefined;
|
||||
/** Return the file if it exists. */
|
||||
function tryFile(fileName: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
|
||||
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
|
||||
}
|
||||
const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
|
||||
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
|
||||
}
|
||||
failedLookupLocation.push(fileName);
|
||||
return undefined;
|
||||
return fileName;
|
||||
}
|
||||
else {
|
||||
if (state.traceEnabled) {
|
||||
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
|
||||
}
|
||||
failedLookupLocation.push(fileName);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
|
||||
const packageJsonPath = combinePaths(candidate, "package.json");
|
||||
const packageJsonPath = pathToPackageJson(candidate);
|
||||
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
|
||||
if (directoryExists && state.host.fileExists(packageJsonPath)) {
|
||||
if (state.traceEnabled) {
|
||||
@@ -725,7 +743,10 @@ namespace ts {
|
||||
}
|
||||
const typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
|
||||
if (typesFile) {
|
||||
const result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typesFile), state.host), state);
|
||||
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(typesFile), state.host);
|
||||
// A package.json "typings" may specify an exact filename, or may choose to omit an extension.
|
||||
const result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures, state) ||
|
||||
tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures, state);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
@@ -747,6 +768,10 @@ namespace ts {
|
||||
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
|
||||
}
|
||||
|
||||
function pathToPackageJson(directory: string): string {
|
||||
return combinePaths(directory, "package.json");
|
||||
}
|
||||
|
||||
function loadModuleFromNodeModulesFolder(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
|
||||
const nodeModulesFolder = combinePaths(directory, "node_modules");
|
||||
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
|
||||
@@ -831,14 +856,6 @@ namespace ts {
|
||||
: { resolvedModule: undefined, failedLookupLocations };
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const defaultInitCompilerOptions: CompilerOptions = {
|
||||
module: ModuleKind.CommonJS,
|
||||
target: ScriptTarget.ES5,
|
||||
noImplicitAny: false,
|
||||
sourceMap: false,
|
||||
};
|
||||
|
||||
interface OutputFingerprint {
|
||||
hash: string;
|
||||
byteOrderMark: boolean;
|
||||
@@ -846,7 +863,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
|
||||
const existingDirectories: Map<boolean> = {};
|
||||
const existingDirectories = createMap<boolean>();
|
||||
|
||||
function getCanonicalFileName(fileName: string): string {
|
||||
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
|
||||
@@ -860,9 +877,10 @@ namespace ts {
|
||||
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
|
||||
let text: string;
|
||||
try {
|
||||
const start = performance.mark();
|
||||
performance.mark("beforeIORead");
|
||||
text = sys.readFile(fileName, options.charset);
|
||||
performance.measure("I/O Read", start);
|
||||
performance.mark("afterIORead");
|
||||
performance.measure("I/O Read", "beforeIORead", "afterIORead");
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
@@ -877,7 +895,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function directoryExists(directoryPath: string): boolean {
|
||||
if (hasProperty(existingDirectories, directoryPath)) {
|
||||
if (directoryPath in existingDirectories) {
|
||||
return true;
|
||||
}
|
||||
if (sys.directoryExists(directoryPath)) {
|
||||
@@ -899,13 +917,13 @@ namespace ts {
|
||||
|
||||
function writeFileIfUpdated(fileName: string, data: string, writeByteOrderMark: boolean): void {
|
||||
if (!outputFingerprints) {
|
||||
outputFingerprints = {};
|
||||
outputFingerprints = createMap<OutputFingerprint>();
|
||||
}
|
||||
|
||||
const hash = sys.createHash(data);
|
||||
const mtimeBefore = sys.getModifiedTime(fileName);
|
||||
|
||||
if (mtimeBefore && hasProperty(outputFingerprints, fileName)) {
|
||||
if (mtimeBefore && fileName in outputFingerprints) {
|
||||
const fingerprint = outputFingerprints[fileName];
|
||||
|
||||
// If output has not been changed, and the file has no external modification
|
||||
@@ -929,7 +947,7 @@ namespace ts {
|
||||
|
||||
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
|
||||
try {
|
||||
const start = performance.mark();
|
||||
performance.mark("beforeIOWrite");
|
||||
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
|
||||
|
||||
if (isWatchSet(options) && sys.createHash && sys.getModifiedTime) {
|
||||
@@ -939,7 +957,8 @@ namespace ts {
|
||||
sys.writeFile(fileName, data, writeByteOrderMark);
|
||||
}
|
||||
|
||||
performance.measure("I/O Write", start);
|
||||
performance.mark("afterIOWrite");
|
||||
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
@@ -968,6 +987,7 @@ namespace ts {
|
||||
readFile: fileName => sys.readFile(fileName),
|
||||
trace: (s: string) => sys.write(s + newLine),
|
||||
directoryExists: directoryName => sys.directoryExists(directoryName),
|
||||
getEnvironmentVariable: name => getEnvironmentVariable(name, /*host*/ undefined),
|
||||
getDirectories: (path: string) => sys.getDirectories(path),
|
||||
realpath
|
||||
};
|
||||
@@ -1040,47 +1060,47 @@ namespace ts {
|
||||
return [];
|
||||
}
|
||||
const resolutions: T[] = [];
|
||||
const cache: Map<T> = {};
|
||||
const cache = createMap<T>();
|
||||
for (const name of names) {
|
||||
let result: T;
|
||||
if (hasProperty(cache, name)) {
|
||||
result = cache[name];
|
||||
}
|
||||
else {
|
||||
result = loader(name, containingFile);
|
||||
cache[name] = result;
|
||||
}
|
||||
const result = name in cache
|
||||
? cache[name]
|
||||
: cache[name] = loader(name, containingFile);
|
||||
resolutions.push(result);
|
||||
}
|
||||
return resolutions;
|
||||
}
|
||||
|
||||
function getInferredTypesRoot(options: CompilerOptions, rootFiles: string[], host: CompilerHost) {
|
||||
return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), f => host.getCanonicalFileName(f));
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a set of options and a set of root files, returns the set of type directive names
|
||||
* Given a set of options, returns the set of type directive names
|
||||
* that should be included for this program automatically.
|
||||
* This list could either come from the config file,
|
||||
* or from enumerating the types root + initial secondary types lookup location.
|
||||
* More type directives might appear in the program later as a result of loading actual source files;
|
||||
* this list is only the set of defaults that are implicitly included.
|
||||
*/
|
||||
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[] {
|
||||
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[] {
|
||||
// Use explicit type list from tsconfig.json
|
||||
if (options.types) {
|
||||
return options.types;
|
||||
}
|
||||
|
||||
// Walk the primary type lookup locations
|
||||
let result: string[] = [];
|
||||
const result: string[] = [];
|
||||
if (host.directoryExists && host.getDirectories) {
|
||||
const typeRoots = getEffectiveTypeRoots(options, host);
|
||||
if (typeRoots) {
|
||||
for (const root of typeRoots) {
|
||||
if (host.directoryExists(root)) {
|
||||
result = result.concat(host.getDirectories(root));
|
||||
for (const typeDirectivePath of host.getDirectories(root)) {
|
||||
const normalized = normalizePath(typeDirectivePath);
|
||||
const packageJsonPath = pathToPackageJson(combinePaths(root, normalized));
|
||||
// tslint:disable-next-line:no-null-keyword
|
||||
const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null;
|
||||
if (!isNotNeededPackage) {
|
||||
// Return just the type directive names
|
||||
result.push(getBaseFileName(normalized));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1096,7 +1116,7 @@ namespace ts {
|
||||
let noDiagnosticsTypeChecker: TypeChecker;
|
||||
let classifiableNames: Map<string>;
|
||||
|
||||
let resolvedTypeReferenceDirectives: Map<ResolvedTypeReferenceDirective> = {};
|
||||
let resolvedTypeReferenceDirectives = createMap<ResolvedTypeReferenceDirective>();
|
||||
let fileProcessingDiagnostics = createDiagnosticCollection();
|
||||
|
||||
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
|
||||
@@ -1106,17 +1126,17 @@ namespace ts {
|
||||
// - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
|
||||
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
|
||||
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
|
||||
const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
|
||||
const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
|
||||
let currentNodeModulesDepth = 0;
|
||||
|
||||
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
|
||||
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
|
||||
const modulesWithElidedImports: Map<boolean> = {};
|
||||
const modulesWithElidedImports = createMap<boolean>();
|
||||
|
||||
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
|
||||
const sourceFilesFoundSearchingNodeModules: Map<boolean> = {};
|
||||
const sourceFilesFoundSearchingNodeModules = createMap<boolean>();
|
||||
|
||||
const start = performance.mark();
|
||||
performance.mark("beforeProgram");
|
||||
|
||||
host = host || createCompilerHost(options);
|
||||
|
||||
@@ -1155,11 +1175,11 @@ namespace ts {
|
||||
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
|
||||
|
||||
// load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
|
||||
const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, rootNames, host);
|
||||
const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, host);
|
||||
|
||||
if (typeReferences) {
|
||||
const inferredRoot = getInferredTypesRoot(options, rootNames, host);
|
||||
const containingFilename = combinePaths(inferredRoot, "__inferred type names__.ts");
|
||||
// This containingFilename needs to match with the one used in managed-side
|
||||
const containingFilename = combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts");
|
||||
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
|
||||
for (let i = 0; i < typeReferences.length; i++) {
|
||||
processTypeReferenceDirective(typeReferences[i], resolutions[i]);
|
||||
@@ -1214,8 +1234,8 @@ namespace ts {
|
||||
};
|
||||
|
||||
verifyCompilerOptions();
|
||||
|
||||
performance.measure("Program", start);
|
||||
performance.mark("afterProgram");
|
||||
performance.measure("Program", "beforeProgram", "afterProgram");
|
||||
|
||||
return program;
|
||||
|
||||
@@ -1242,10 +1262,10 @@ namespace ts {
|
||||
if (!classifiableNames) {
|
||||
// Initialize a checker so that all our files are bound.
|
||||
getTypeChecker();
|
||||
classifiableNames = {};
|
||||
classifiableNames = createMap<string>();
|
||||
|
||||
for (const sourceFile of files) {
|
||||
copyMap(sourceFile.classifiableNames, classifiableNames);
|
||||
copyProperties(sourceFile.classifiableNames, classifiableNames);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1273,7 +1293,7 @@ namespace ts {
|
||||
(oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) ||
|
||||
!arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) ||
|
||||
!arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) ||
|
||||
!mapIsEqualTo(oldOptions.paths, options.paths)) {
|
||||
!equalOwnProperties(oldOptions.paths, options.paths)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1395,7 +1415,7 @@ namespace ts {
|
||||
getSourceFile: program.getSourceFile,
|
||||
getSourceFileByPath: program.getSourceFileByPath,
|
||||
getSourceFiles: program.getSourceFiles,
|
||||
isSourceFileFromExternalLibrary: (file: SourceFile) => !!lookUp(sourceFilesFoundSearchingNodeModules, file.path),
|
||||
isSourceFileFromExternalLibrary: (file: SourceFile) => !!sourceFilesFoundSearchingNodeModules[file.path],
|
||||
writeFile: writeFileCallback || (
|
||||
(fileName, data, writeByteOrderMark, onError, sourceFiles) => host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles)),
|
||||
isEmitBlocked,
|
||||
@@ -1458,14 +1478,15 @@ namespace ts {
|
||||
// checked is to not pass the file to getEmitResolver.
|
||||
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
|
||||
|
||||
const start = performance.mark();
|
||||
performance.mark("beforeEmit");
|
||||
|
||||
const emitResult = emitFiles(
|
||||
emitResolver,
|
||||
getEmitHost(writeFileCallback),
|
||||
sourceFile);
|
||||
|
||||
performance.measure("Emit", start);
|
||||
performance.mark("afterEmit");
|
||||
performance.measure("Emit", "beforeEmit", "afterEmit");
|
||||
return emitResult;
|
||||
}
|
||||
|
||||
@@ -1710,7 +1731,7 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
|
||||
function checkModifiers(modifiers: ModifiersArray): boolean {
|
||||
function checkModifiers(modifiers: NodeArray<Modifier>): boolean {
|
||||
if (modifiers) {
|
||||
for (const modifier of modifiers) {
|
||||
switch (modifier.kind) {
|
||||
@@ -1794,6 +1815,17 @@ namespace ts {
|
||||
let imports: LiteralExpression[];
|
||||
let moduleAugmentations: LiteralExpression[];
|
||||
|
||||
// If we are importing helpers, we need to add a synthetic reference to resolve the
|
||||
// helpers library.
|
||||
if (options.importHelpers
|
||||
&& (options.isolatedModules || isExternalModuleFile)
|
||||
&& !file.isDeclarationFile) {
|
||||
const externalHelpersModuleReference = <StringLiteral>createNode(SyntaxKind.StringLiteral);
|
||||
externalHelpersModuleReference.text = externalHelpersModuleNameText;
|
||||
externalHelpersModuleReference.parent = file;
|
||||
imports = [externalHelpersModuleReference];
|
||||
}
|
||||
|
||||
for (const node of file.statements) {
|
||||
collectModuleReferences(node, /*inAmbientModule*/ false);
|
||||
if (isJavaScriptFile) {
|
||||
@@ -1827,7 +1859,7 @@ namespace ts {
|
||||
}
|
||||
break;
|
||||
case SyntaxKind.ModuleDeclaration:
|
||||
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
|
||||
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || isDeclarationFile(file))) {
|
||||
const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name;
|
||||
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
|
||||
// This will happen in two cases:
|
||||
@@ -1932,7 +1964,7 @@ namespace ts {
|
||||
|
||||
// If the file was previously found via a node_modules search, but is now being processed as a root file,
|
||||
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
|
||||
if (file && lookUp(sourceFilesFoundSearchingNodeModules, file.path) && currentNodeModulesDepth == 0) {
|
||||
if (file && sourceFilesFoundSearchingNodeModules[file.path] && currentNodeModulesDepth == 0) {
|
||||
sourceFilesFoundSearchingNodeModules[file.path] = false;
|
||||
if (!options.noResolve) {
|
||||
processReferencedFiles(file, getDirectoryPath(fileName), isDefaultLib);
|
||||
@@ -1943,7 +1975,7 @@ namespace ts {
|
||||
processImportedModules(file, getDirectoryPath(fileName));
|
||||
}
|
||||
// See if we need to reprocess the imports due to prior skipped imports
|
||||
else if (file && lookUp(modulesWithElidedImports, file.path)) {
|
||||
else if (file && modulesWithElidedImports[file.path]) {
|
||||
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
|
||||
modulesWithElidedImports[file.path] = false;
|
||||
processImportedModules(file, getDirectoryPath(fileName));
|
||||
@@ -2010,15 +2042,17 @@ namespace ts {
|
||||
}
|
||||
|
||||
function processTypeReferenceDirectives(file: SourceFile) {
|
||||
const typeDirectives = map(file.typeReferenceDirectives, l => l.fileName);
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const typeDirectives = map(file.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase());
|
||||
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
|
||||
|
||||
for (let i = 0; i < typeDirectives.length; i++) {
|
||||
const ref = file.typeReferenceDirectives[i];
|
||||
const resolvedTypeReferenceDirective = resolutions[i];
|
||||
// store resolved type directive on the file
|
||||
setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective);
|
||||
processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
|
||||
const fileName = ref.fileName.toLocaleLowerCase();
|
||||
setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
|
||||
processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2043,7 +2077,7 @@ namespace ts {
|
||||
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
|
||||
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
|
||||
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd,
|
||||
Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict,
|
||||
Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict,
|
||||
typeReferenceDirective,
|
||||
resolvedTypeReferenceDirective.resolvedFileName,
|
||||
previousResolution.resolvedFileName
|
||||
@@ -2083,7 +2117,7 @@ namespace ts {
|
||||
function processImportedModules(file: SourceFile, basePath: string) {
|
||||
collectExternalModuleReferences(file);
|
||||
if (file.imports.length || file.moduleAugmentations.length) {
|
||||
file.resolvedModules = {};
|
||||
file.resolvedModules = createMap<ResolvedModule>();
|
||||
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
|
||||
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
|
||||
for (let i = 0; i < moduleNames.length; i++) {
|
||||
@@ -2200,6 +2234,9 @@ namespace ts {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
|
||||
}
|
||||
if (isArray(options.paths[key])) {
|
||||
if (options.paths[key].length === 0) {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key));
|
||||
}
|
||||
for (const subst of options.paths[key]) {
|
||||
const typeOfSubst = typeof subst;
|
||||
if (typeOfSubst === "string") {
|
||||
@@ -2252,7 +2289,7 @@ namespace ts {
|
||||
const languageVersion = options.target || ScriptTarget.ES3;
|
||||
const outFile = options.outFile || options.out;
|
||||
|
||||
const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
|
||||
const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
|
||||
if (options.isolatedModules) {
|
||||
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
|
||||
@@ -2264,10 +2301,10 @@ namespace ts {
|
||||
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
|
||||
}
|
||||
}
|
||||
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
|
||||
else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
|
||||
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
|
||||
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
|
||||
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
|
||||
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
|
||||
programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
|
||||
}
|
||||
|
||||
// Cannot specify module gen that isn't amd or system with --out
|
||||
@@ -2275,9 +2312,9 @@ namespace ts {
|
||||
if (options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
|
||||
}
|
||||
else if (options.module === undefined && firstExternalModuleSourceFile) {
|
||||
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
|
||||
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
|
||||
else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
|
||||
const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
|
||||
programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2305,7 +2342,7 @@ namespace ts {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
|
||||
}
|
||||
|
||||
if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) {
|
||||
if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
|
||||
}
|
||||
|
||||
|
||||
+105
-37
@@ -27,6 +27,7 @@ namespace ts {
|
||||
reScanSlashToken(): SyntaxKind;
|
||||
reScanTemplateToken(): SyntaxKind;
|
||||
scanJsxIdentifier(): SyntaxKind;
|
||||
scanJsxAttributeValue(): SyntaxKind;
|
||||
reScanJsxToken(): SyntaxKind;
|
||||
scanJsxToken(): SyntaxKind;
|
||||
scanJSDocToken(): SyntaxKind;
|
||||
@@ -55,7 +56,7 @@ namespace ts {
|
||||
tryScan<T>(callback: () => T): T;
|
||||
}
|
||||
|
||||
const textToToken: Map<SyntaxKind> = {
|
||||
const textToToken = createMap({
|
||||
"abstract": SyntaxKind.AbstractKeyword,
|
||||
"any": SyntaxKind.AnyKeyword,
|
||||
"as": SyntaxKind.AsKeyword,
|
||||
@@ -179,7 +180,7 @@ namespace ts {
|
||||
"|=": SyntaxKind.BarEqualsToken,
|
||||
"^=": SyntaxKind.CaretEqualsToken,
|
||||
"@": SyntaxKind.AtToken,
|
||||
};
|
||||
});
|
||||
|
||||
/*
|
||||
As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
|
||||
@@ -274,9 +275,7 @@ namespace ts {
|
||||
function makeReverseMap(source: Map<number>): string[] {
|
||||
const result: string[] = [];
|
||||
for (const name in source) {
|
||||
if (source.hasOwnProperty(name)) {
|
||||
result[source[name]] = name;
|
||||
}
|
||||
result[source[name]] = name;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -441,9 +440,7 @@ namespace ts {
|
||||
|
||||
/* @internal */
|
||||
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments = false): number {
|
||||
// Using ! with a greater than test is a fast way of testing the following conditions:
|
||||
// pos === undefined || pos === null || isNaN(pos) || pos < 0;
|
||||
if (!(pos >= 0)) {
|
||||
if (positionIsSynthesized(pos)) {
|
||||
return pos;
|
||||
}
|
||||
|
||||
@@ -592,20 +589,34 @@ namespace ts {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract comments from text prefixing the token closest following `pos`.
|
||||
* The return value is an array containing a TextRange for each comment.
|
||||
* Single-line comment ranges include the beginning '//' characters but not the ending line break.
|
||||
* Multi - line comment ranges include the beginning '/* and ending '<asterisk>/' characters.
|
||||
* The return value is undefined if no comments were found.
|
||||
* @param trailing
|
||||
* If false, whitespace is skipped until the first line break and comments between that location
|
||||
* and the next token are returned.
|
||||
* If true, comments occurring between the given position and the next line break are returned.
|
||||
* Invokes a callback for each comment range following the provided position.
|
||||
*
|
||||
* Single-line comment ranges include the leading double-slash characters but not the ending
|
||||
* line break. Multi-line comment ranges include the leading slash-asterisk and trailing
|
||||
* asterisk-slash characters.
|
||||
*
|
||||
* @param reduce If true, accumulates the result of calling the callback in a fashion similar
|
||||
* to reduceLeft. If false, iteration stops when the callback returns a truthy value.
|
||||
* @param text The source text to scan.
|
||||
* @param pos The position at which to start scanning.
|
||||
* @param trailing If false, whitespace is skipped until the first line break and comments
|
||||
* between that location and the next token are returned. If true, comments occurring
|
||||
* between the given position and the next line break are returned.
|
||||
* @param cb The callback to execute as each comment range is encountered.
|
||||
* @param state A state value to pass to each iteration of the callback.
|
||||
* @param initial An initial value to pass when accumulating results (when "reduce" is true).
|
||||
* @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
|
||||
* return value of the callback.
|
||||
*/
|
||||
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
|
||||
let result: CommentRange[];
|
||||
function iterateCommentRanges<T, U>(reduce: boolean, text: string, pos: number, trailing: boolean, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial?: U): U {
|
||||
let pendingPos: number;
|
||||
let pendingEnd: number;
|
||||
let pendingKind: SyntaxKind;
|
||||
let pendingHasTrailingNewLine: boolean;
|
||||
let hasPendingCommentRange = false;
|
||||
let collecting = trailing || pos === 0;
|
||||
while (pos < text.length) {
|
||||
let accumulator = initial;
|
||||
scan: while (pos >= 0 && pos < text.length) {
|
||||
const ch = text.charCodeAt(pos);
|
||||
switch (ch) {
|
||||
case CharacterCodes.carriageReturn:
|
||||
@@ -615,12 +626,14 @@ namespace ts {
|
||||
case CharacterCodes.lineFeed:
|
||||
pos++;
|
||||
if (trailing) {
|
||||
return result;
|
||||
break scan;
|
||||
}
|
||||
|
||||
collecting = true;
|
||||
if (result && result.length) {
|
||||
lastOrUndefined(result).hasTrailingNewLine = true;
|
||||
if (hasPendingCommentRange) {
|
||||
pendingHasTrailingNewLine = true;
|
||||
}
|
||||
|
||||
continue;
|
||||
case CharacterCodes.tab:
|
||||
case CharacterCodes.verticalTab:
|
||||
@@ -653,38 +666,78 @@ namespace ts {
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
|
||||
if (collecting) {
|
||||
if (!result) {
|
||||
result = [];
|
||||
if (hasPendingCommentRange) {
|
||||
accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
|
||||
if (!reduce && accumulator) {
|
||||
// If we are not reducing and we have a truthy result, return it.
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
hasPendingCommentRange = false;
|
||||
}
|
||||
|
||||
result.push({ pos: startPos, end: pos, hasTrailingNewLine, kind });
|
||||
pendingPos = startPos;
|
||||
pendingEnd = pos;
|
||||
pendingKind = kind;
|
||||
pendingHasTrailingNewLine = hasTrailingNewLine;
|
||||
hasPendingCommentRange = true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
break scan;
|
||||
default:
|
||||
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch))) {
|
||||
if (result && result.length && isLineBreak(ch)) {
|
||||
lastOrUndefined(result).hasTrailingNewLine = true;
|
||||
if (hasPendingCommentRange && isLineBreak(ch)) {
|
||||
pendingHasTrailingNewLine = true;
|
||||
}
|
||||
pos++;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
break scan;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return result;
|
||||
if (hasPendingCommentRange) {
|
||||
accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
|
||||
}
|
||||
|
||||
return accumulator;
|
||||
}
|
||||
|
||||
export function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) {
|
||||
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
|
||||
}
|
||||
|
||||
export function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) {
|
||||
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
|
||||
}
|
||||
|
||||
export function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U) {
|
||||
return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
|
||||
}
|
||||
|
||||
export function reduceEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U) {
|
||||
return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
|
||||
}
|
||||
|
||||
function appendCommentRange(pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: any, comments: CommentRange[]) {
|
||||
if (!comments) {
|
||||
comments = [];
|
||||
}
|
||||
|
||||
comments.push({ pos, end, hasTrailingNewLine, kind });
|
||||
return comments;
|
||||
}
|
||||
|
||||
export function getLeadingCommentRanges(text: string, pos: number): CommentRange[] {
|
||||
return getCommentRanges(text, pos, /*trailing*/ false);
|
||||
return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined);
|
||||
}
|
||||
|
||||
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
|
||||
return getCommentRanges(text, pos, /*trailing*/ true);
|
||||
return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined);
|
||||
}
|
||||
|
||||
/** Optionally, get the shebang */
|
||||
@@ -707,7 +760,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function isIdentifier(name: string, languageVersion: ScriptTarget): boolean {
|
||||
export function isIdentifierText(name: string, languageVersion: ScriptTarget): boolean {
|
||||
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
|
||||
return false;
|
||||
}
|
||||
@@ -765,6 +818,7 @@ namespace ts {
|
||||
reScanSlashToken,
|
||||
reScanTemplateToken,
|
||||
scanJsxIdentifier,
|
||||
scanJsxAttributeValue,
|
||||
reScanJsxToken,
|
||||
scanJsxToken,
|
||||
scanJSDocToken,
|
||||
@@ -859,7 +913,7 @@ namespace ts {
|
||||
return value;
|
||||
}
|
||||
|
||||
function scanString(): string {
|
||||
function scanString(allowEscapes = true): string {
|
||||
const quote = text.charCodeAt(pos);
|
||||
pos++;
|
||||
let result = "";
|
||||
@@ -877,7 +931,7 @@ namespace ts {
|
||||
pos++;
|
||||
break;
|
||||
}
|
||||
if (ch === CharacterCodes.backslash) {
|
||||
if (ch === CharacterCodes.backslash && allowEscapes) {
|
||||
result += text.substring(start, pos);
|
||||
result += scanEscapeSequence();
|
||||
start = pos;
|
||||
@@ -1685,6 +1739,20 @@ namespace ts {
|
||||
return token;
|
||||
}
|
||||
|
||||
function scanJsxAttributeValue(): SyntaxKind {
|
||||
startPos = pos;
|
||||
|
||||
switch (text.charCodeAt(pos)) {
|
||||
case CharacterCodes.doubleQuote:
|
||||
case CharacterCodes.singleQuote:
|
||||
tokenValue = scanString(/*allowEscapes*/ false);
|
||||
return token = SyntaxKind.StringLiteral;
|
||||
default:
|
||||
// If this scans anything other than `{`, it's a parse error.
|
||||
return scan();
|
||||
}
|
||||
}
|
||||
|
||||
function scanJSDocToken(): SyntaxKind {
|
||||
if (pos >= end) {
|
||||
return token = SyntaxKind.EndOfFileToken;
|
||||
|
||||
+505
-42
@@ -3,19 +3,211 @@
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
export interface SourceMapWriter {
|
||||
getSourceMapData(): SourceMapData;
|
||||
setSourceFile(sourceFile: SourceFile): void;
|
||||
emitPos(pos: number): void;
|
||||
emitStart(range: TextRange): void;
|
||||
emitEnd(range: TextRange, stopOverridingSpan?: boolean): void;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
|
||||
const compilerOptions = host.getCompilerOptions();
|
||||
if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
|
||||
if (compilerOptions.extendedDiagnostics) {
|
||||
return createSourceMapWriterWithExtendedDiagnostics(host, writer);
|
||||
}
|
||||
|
||||
return createSourceMapWriterWorker(host, writer);
|
||||
}
|
||||
else {
|
||||
return getNullSourceMapWriter();
|
||||
}
|
||||
}
|
||||
|
||||
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) => TextRange): number { return -1; },
|
||||
emitTokenEnd(token: SyntaxKind, end: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => 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,
|
||||
@@ -25,28 +217,11 @@ 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 { },
|
||||
};
|
||||
}
|
||||
|
||||
return nullSourceMapWriter;
|
||||
}
|
||||
|
||||
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
|
||||
function createSourceMapWriterWorker(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
|
||||
const compilerOptions = host.getCompilerOptions();
|
||||
const extendedDiagnostics = compilerOptions.extendedDiagnostics;
|
||||
let currentSourceFile: SourceFile;
|
||||
let currentSourceText: string;
|
||||
let sourceMapDir: string; // The directory in which sourcemap will be
|
||||
let stopOverridingSpan = false;
|
||||
let modifyLastSourcePos = false;
|
||||
@@ -62,25 +237,45 @@ namespace ts {
|
||||
// Source map data
|
||||
let sourceMapData: SourceMapData;
|
||||
|
||||
// This keeps track of the number of times `disable` has been called without a
|
||||
// corresponding call to `enable`. As long as this value is non-zero, mappings will not
|
||||
// be recorded.
|
||||
// This is primarily used to provide a better experience when debugging binding
|
||||
// patterns and destructuring assignments for simple expressions.
|
||||
let disableDepth: number;
|
||||
|
||||
return {
|
||||
initialize,
|
||||
reset,
|
||||
getSourceMapData: () => sourceMapData,
|
||||
setSourceFile,
|
||||
emitPos,
|
||||
emitStart,
|
||||
emitEnd,
|
||||
emitTokenStart,
|
||||
emitTokenEnd,
|
||||
changeEmitSourcePos,
|
||||
stopOverridingSpan: () => stopOverridingSpan = true,
|
||||
getText,
|
||||
getSourceMappingURL,
|
||||
initialize,
|
||||
reset,
|
||||
};
|
||||
|
||||
/**
|
||||
* 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
|
||||
sourceMapSourceIndex = -1;
|
||||
@@ -139,6 +334,9 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the SourceMapWriter to an empty state.
|
||||
*/
|
||||
function reset() {
|
||||
currentSourceFile = undefined;
|
||||
sourceMapDir = undefined;
|
||||
@@ -147,6 +345,23 @@ namespace ts {
|
||||
lastEncodedSourceMapSpan = undefined;
|
||||
lastEncodedNameIndex = undefined;
|
||||
sourceMapData = undefined;
|
||||
disableDepth = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-enables the recording of mappings.
|
||||
*/
|
||||
function enable() {
|
||||
if (disableDepth > 0) {
|
||||
disableDepth--;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables the recording of mappings.
|
||||
*/
|
||||
function disable() {
|
||||
disableDepth++;
|
||||
}
|
||||
|
||||
function updateLastEncodedAndRecordedSpans() {
|
||||
@@ -235,12 +450,22 @@ 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 (pos === -1) {
|
||||
if (positionIsSynthesized(pos) || disableDepth > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const start = performance.mark();
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("beforeSourcemap");
|
||||
}
|
||||
|
||||
const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
|
||||
|
||||
@@ -282,30 +507,207 @@ namespace ts {
|
||||
|
||||
updateLastEncodedAndRecordedSpans();
|
||||
|
||||
performance.measure("Source Map", start);
|
||||
if (extendedDiagnostics) {
|
||||
performance.mark("afterSourcemap");
|
||||
performance.measure("Source Map", "beforeSourcemap", "afterSourcemap");
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
/**
|
||||
* 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) {
|
||||
emitPos(range.end);
|
||||
stopOverridingSpan = stopOverridingEnd;
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
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 = currentSourceFile.text;
|
||||
|
||||
// Add the file to tsFilePaths
|
||||
// If sourceroot option: Use the relative path corresponding to the common directory path
|
||||
@@ -324,14 +726,17 @@ namespace ts {
|
||||
sourceMapData.sourceMapSources.push(source);
|
||||
|
||||
// The one that can be used from program to get the actual source file
|
||||
sourceMapData.inputSourceFileNames.push(sourceFile.fileName);
|
||||
sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName);
|
||||
|
||||
if (compilerOptions.inlineSources) {
|
||||
sourceMapData.sourceMapSourcesContent.push(sourceFile.text);
|
||||
sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the text for the source map.
|
||||
*/
|
||||
function getText() {
|
||||
encodeLastRecordedSourceMapSpan();
|
||||
|
||||
@@ -346,6 +751,9 @@ namespace ts {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the SourceMappingURL for the source map.
|
||||
*/
|
||||
function getSourceMappingURL() {
|
||||
if (compilerOptions.inlineSourceMap) {
|
||||
// Encode the sourceMap into the sourceMap url
|
||||
@@ -358,6 +766,61 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function createSourceMapWriterWithExtendedDiagnostics(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
|
||||
const {
|
||||
initialize,
|
||||
reset,
|
||||
getSourceMapData,
|
||||
setSourceFile,
|
||||
emitPos,
|
||||
emitStart,
|
||||
emitEnd,
|
||||
emitTokenStart,
|
||||
emitTokenEnd,
|
||||
changeEmitSourcePos,
|
||||
stopOverridingSpan,
|
||||
getText,
|
||||
getSourceMappingURL,
|
||||
} = createSourceMapWriterWorker(host, writer);
|
||||
return {
|
||||
initialize,
|
||||
reset,
|
||||
getSourceMapData,
|
||||
setSourceFile,
|
||||
emitPos(pos: number): void {
|
||||
performance.mark("sourcemapStart");
|
||||
emitPos(pos);
|
||||
performance.measure("sourceMapTime", "sourcemapStart");
|
||||
},
|
||||
emitStart(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void {
|
||||
performance.mark("emitSourcemap:emitStart");
|
||||
emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback);
|
||||
performance.measure("sourceMapTime", "emitSourcemap:emitStart");
|
||||
},
|
||||
emitEnd(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void {
|
||||
performance.mark("emitSourcemap:emitEnd");
|
||||
emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback);
|
||||
performance.measure("sourceMapTime", "emitSourcemap:emitEnd");
|
||||
},
|
||||
emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
|
||||
performance.mark("emitSourcemap:emitTokenStart");
|
||||
tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback);
|
||||
performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart");
|
||||
return tokenStartPos;
|
||||
},
|
||||
emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
|
||||
performance.mark("emitSourcemap:emitTokenEnd");
|
||||
tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback);
|
||||
performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd");
|
||||
return tokenEndPos;
|
||||
},
|
||||
changeEmitSourcePos,
|
||||
stopOverridingSpan,
|
||||
getText,
|
||||
getSourceMappingURL,
|
||||
};
|
||||
}
|
||||
|
||||
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
function base64FormatEncode(inValue: number) {
|
||||
|
||||
+29
-25
@@ -32,6 +32,8 @@ namespace ts {
|
||||
getMemoryUsage?(): number;
|
||||
exit(exitCode?: number): void;
|
||||
realpath?(path: string): string;
|
||||
/*@internal*/ getEnvironmentVariable(name: string): string;
|
||||
/*@internal*/ tryEnableSourceMapsForHost?(): void;
|
||||
}
|
||||
|
||||
export interface FileWatcher {
|
||||
@@ -78,6 +80,7 @@ namespace ts {
|
||||
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
|
||||
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
|
||||
realpath(path: string): string;
|
||||
getEnvironmentVariable?(name: string): string;
|
||||
};
|
||||
|
||||
export var sys: System = (function() {
|
||||
@@ -212,6 +215,9 @@ namespace ts {
|
||||
return shell.CurrentDirectory;
|
||||
},
|
||||
getDirectories,
|
||||
getEnvironmentVariable(name: string) {
|
||||
return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings(`%${name}%`);
|
||||
},
|
||||
readDirectory,
|
||||
exit(exitCode?: number): void {
|
||||
try {
|
||||
@@ -233,15 +239,15 @@ namespace ts {
|
||||
const useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"];
|
||||
|
||||
function createWatchedFileSet() {
|
||||
const dirWatchers: Map<DirectoryWatcher> = {};
|
||||
const dirWatchers = createMap<DirectoryWatcher>();
|
||||
// One file can have multiple watchers
|
||||
const fileWatcherCallbacks: Map<FileWatcherCallback[]> = {};
|
||||
const fileWatcherCallbacks = createMap<FileWatcherCallback[]>();
|
||||
return { addFile, removeFile };
|
||||
|
||||
function reduceDirWatcherRefCountForFile(fileName: string) {
|
||||
const dirName = getDirectoryPath(fileName);
|
||||
if (hasProperty(dirWatchers, dirName)) {
|
||||
const watcher = dirWatchers[dirName];
|
||||
const watcher = dirWatchers[dirName];
|
||||
if (watcher) {
|
||||
watcher.referenceCount -= 1;
|
||||
if (watcher.referenceCount <= 0) {
|
||||
watcher.close();
|
||||
@@ -251,13 +257,12 @@ namespace ts {
|
||||
}
|
||||
|
||||
function addDirWatcher(dirPath: string): void {
|
||||
if (hasProperty(dirWatchers, dirPath)) {
|
||||
const watcher = dirWatchers[dirPath];
|
||||
let watcher = dirWatchers[dirPath];
|
||||
if (watcher) {
|
||||
watcher.referenceCount += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const watcher: DirectoryWatcher = _fs.watch(
|
||||
watcher = _fs.watch(
|
||||
dirPath,
|
||||
{ persistent: true },
|
||||
(eventName: string, relativeFileName: string) => fileEventHandler(eventName, relativeFileName, dirPath)
|
||||
@@ -268,12 +273,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
|
||||
if (hasProperty(fileWatcherCallbacks, filePath)) {
|
||||
fileWatcherCallbacks[filePath].push(callback);
|
||||
}
|
||||
else {
|
||||
fileWatcherCallbacks[filePath] = [callback];
|
||||
}
|
||||
multiMapAdd(fileWatcherCallbacks, filePath, callback);
|
||||
}
|
||||
|
||||
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
|
||||
@@ -289,15 +289,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
|
||||
if (hasProperty(fileWatcherCallbacks, filePath)) {
|
||||
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks[filePath]);
|
||||
if (newCallbacks.length === 0) {
|
||||
delete fileWatcherCallbacks[filePath];
|
||||
}
|
||||
else {
|
||||
fileWatcherCallbacks[filePath] = newCallbacks;
|
||||
}
|
||||
}
|
||||
multiMapRemove(fileWatcherCallbacks, filePath, callback);
|
||||
}
|
||||
|
||||
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: string) {
|
||||
@@ -306,7 +298,7 @@ namespace ts {
|
||||
? undefined
|
||||
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
|
||||
// Some applications save a working file via rename operations
|
||||
if ((eventName === "change" || eventName === "rename") && hasProperty(fileWatcherCallbacks, fileName)) {
|
||||
if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks[fileName]) {
|
||||
for (const fileCallback of fileWatcherCallbacks[fileName]) {
|
||||
fileCallback(fileName);
|
||||
}
|
||||
@@ -437,7 +429,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getDirectories(path: string): string[] {
|
||||
return filter<string>(_fs.readdirSync(path), p => fileSystemEntryExists(combinePaths(path, p), FileSystemEntryKind.Directory));
|
||||
return filter<string>(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory));
|
||||
}
|
||||
|
||||
const nodeSystem: System = {
|
||||
@@ -513,6 +505,9 @@ namespace ts {
|
||||
return process.cwd();
|
||||
},
|
||||
getDirectories,
|
||||
getEnvironmentVariable(name: string) {
|
||||
return process.env[name] || "";
|
||||
},
|
||||
readDirectory,
|
||||
getModifiedTime(path) {
|
||||
try {
|
||||
@@ -548,6 +543,14 @@ namespace ts {
|
||||
},
|
||||
realpath(path: string): string {
|
||||
return _fs.realpathSync(path);
|
||||
},
|
||||
tryEnableSourceMapsForHost() {
|
||||
try {
|
||||
require("source-map-support").install();
|
||||
}
|
||||
catch (e) {
|
||||
// Could not enable source maps.
|
||||
}
|
||||
}
|
||||
};
|
||||
return nodeSystem;
|
||||
@@ -579,6 +582,7 @@ namespace ts {
|
||||
getExecutingFilePath: () => ChakraHost.executingFile,
|
||||
getCurrentDirectory: () => ChakraHost.currentDirectory,
|
||||
getDirectories: ChakraHost.getDirectories,
|
||||
getEnvironmentVariable: ChakraHost.getEnvironmentVariable || ((name: string) => ""),
|
||||
readDirectory: (path: string, extensions?: string[], excludes?: string[], includes?: string[]) => {
|
||||
const pattern = getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory);
|
||||
return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern);
|
||||
|
||||
@@ -0,0 +1,632 @@
|
||||
/// <reference path="visitor.ts" />
|
||||
/// <reference path="transformers/ts.ts" />
|
||||
/// <reference path="transformers/jsx.ts" />
|
||||
/// <reference path="transformers/es7.ts" />
|
||||
/// <reference path="transformers/es6.ts" />
|
||||
/// <reference path="transformers/generators.ts" />
|
||||
/// <reference path="transformers/module/module.ts" />
|
||||
/// <reference path="transformers/module/system.ts" />
|
||||
/// <reference path="transformers/module/es6.ts" />
|
||||
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
const moduleTransformerMap = createMap<Transformer>({
|
||||
[ModuleKind.ES6]: transformES6Module,
|
||||
[ModuleKind.System]: transformSystemModule,
|
||||
[ModuleKind.AMD]: transformModule,
|
||||
[ModuleKind.CommonJS]: transformModule,
|
||||
[ModuleKind.UMD]: transformModule,
|
||||
[ModuleKind.None]: transformModule,
|
||||
});
|
||||
|
||||
const enum SyntaxKindFeatureFlags {
|
||||
Substitution = 1 << 0,
|
||||
EmitNotifications = 1 << 1,
|
||||
}
|
||||
|
||||
export interface TransformationResult {
|
||||
/**
|
||||
* Gets the transformed source files.
|
||||
*/
|
||||
getSourceFiles(): SourceFile[];
|
||||
|
||||
/**
|
||||
* Gets the TextRange to use for source maps for a token of a node.
|
||||
*/
|
||||
getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange;
|
||||
|
||||
/**
|
||||
* Determines whether expression substitutions are enabled for the provided node.
|
||||
*/
|
||||
isSubstitutionEnabled(node: Node): boolean;
|
||||
|
||||
/**
|
||||
* Determines whether before/after emit notifications should be raised in the pretty
|
||||
* printer when it emits a node.
|
||||
*/
|
||||
isEmitNotificationEnabled(node: Node): boolean;
|
||||
|
||||
/**
|
||||
* Hook used by transformers to substitute expressions just before they
|
||||
* are emitted by the pretty printer.
|
||||
*
|
||||
* @param node The node to substitute.
|
||||
* @param isExpression A value indicating whether the node is in an expression context.
|
||||
*/
|
||||
onSubstituteNode(node: Node, isExpression: boolean): Node;
|
||||
|
||||
/**
|
||||
* Hook used to allow transformers to capture state before or after
|
||||
* the printer emits a node.
|
||||
*
|
||||
* @param node The node to emit.
|
||||
* @param emitCallback A callback used to emit the node.
|
||||
*/
|
||||
onEmitNode(node: Node, emitCallback: (node: Node) => void): void;
|
||||
|
||||
/**
|
||||
* Reset transient transformation properties on parse tree nodes.
|
||||
*/
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
|
||||
*/
|
||||
enableSubstitution(kind: SyntaxKind): void;
|
||||
|
||||
/**
|
||||
* Determines whether expression substitutions are enabled for the provided node.
|
||||
*/
|
||||
isSubstitutionEnabled(node: Node): boolean;
|
||||
|
||||
/**
|
||||
* Hook used by transformers to substitute expressions just before they
|
||||
* are emitted by the pretty printer.
|
||||
*/
|
||||
onSubstituteNode?: (node: Node, isExpression: boolean) => Node;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
isEmitNotificationEnabled(node: Node): boolean;
|
||||
|
||||
/**
|
||||
* Hook used to allow transformers to capture state before or after
|
||||
* the printer emits a node.
|
||||
*/
|
||||
onEmitNode?: (node: Node, emit: (node: Node) => void) => void;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile;
|
||||
|
||||
export function getTransformers(compilerOptions: CompilerOptions) {
|
||||
const jsx = compilerOptions.jsx;
|
||||
const languageVersion = getEmitScriptTarget(compilerOptions);
|
||||
const moduleKind = getEmitModuleKind(compilerOptions);
|
||||
const transformers: Transformer[] = [];
|
||||
|
||||
transformers.push(transformTypeScript);
|
||||
transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ModuleKind.None]);
|
||||
|
||||
if (jsx === JsxEmit.React) {
|
||||
transformers.push(transformJsx);
|
||||
}
|
||||
|
||||
transformers.push(transformES7);
|
||||
|
||||
if (languageVersion < ScriptTarget.ES6) {
|
||||
transformers.push(transformES6);
|
||||
transformers.push(transformGenerators);
|
||||
}
|
||||
|
||||
return transformers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks a monotonically increasing transformation id used to associate a node with a specific
|
||||
* transformation. This ensures transient properties related to transformations can be safely
|
||||
* stored on source tree nodes that may be reused across multiple transformations (such as
|
||||
* with compile-on-save).
|
||||
*/
|
||||
let nextTransformId = 1;
|
||||
|
||||
/**
|
||||
* Transforms an array of SourceFiles by passing them through each transformer.
|
||||
*
|
||||
* @param resolver The emit resolver provided by the checker.
|
||||
* @param host The emit host.
|
||||
* @param sourceFiles An array of source files
|
||||
* @param transforms An array of Transformers.
|
||||
*/
|
||||
export function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]): TransformationResult {
|
||||
const transformId = nextTransformId;
|
||||
nextTransformId++;
|
||||
|
||||
const tokenSourceMapRanges = createMap<TextRange>();
|
||||
const lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = [];
|
||||
const lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = [];
|
||||
const enabledSyntaxKindFeatures = new Array<SyntaxKindFeatureFlags>(SyntaxKind.Count);
|
||||
const parseTreeNodesWithAnnotations: Node[] = [];
|
||||
|
||||
let lastTokenSourceMapRangeNode: Node;
|
||||
let lastTokenSourceMapRangeToken: SyntaxKind;
|
||||
let lastTokenSourceMapRange: TextRange;
|
||||
let lexicalEnvironmentStackOffset = 0;
|
||||
let hoistedVariableDeclarations: VariableDeclaration[];
|
||||
let hoistedFunctionDeclarations: FunctionDeclaration[];
|
||||
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,
|
||||
onSubstituteNode,
|
||||
enableSubstitution,
|
||||
isSubstitutionEnabled,
|
||||
onEmitNode,
|
||||
enableEmitNotification,
|
||||
isEmitNotificationEnabled
|
||||
};
|
||||
|
||||
// Chain together and initialize each transformer.
|
||||
const transformation = chain(...transformers)(context);
|
||||
|
||||
// Transform each source file.
|
||||
const transformed = map(sourceFiles, transformSourceFile);
|
||||
|
||||
// Disable modification of the lexical environment.
|
||||
lexicalEnvironmentDisabled = true;
|
||||
|
||||
return {
|
||||
getSourceFiles: () => transformed,
|
||||
getTokenSourceMapRange,
|
||||
isSubstitutionEnabled,
|
||||
isEmitNotificationEnabled,
|
||||
onSubstituteNode: context.onSubstituteNode,
|
||||
onEmitNode: context.onEmitNode,
|
||||
dispose() {
|
||||
// During transformation we may need to annotate a parse tree node with transient
|
||||
// transformation properties. As parse tree nodes live longer than transformation
|
||||
// nodes, we need to make sure we reclaim any memory allocated for custom ranges
|
||||
// from these nodes to ensure we do not hold onto entire subtrees just for position
|
||||
// information. We also need to reset these nodes to a pre-transformation state
|
||||
// for incremental parsing scenarios so that we do not impact later emit.
|
||||
for (const node of parseTreeNodesWithAnnotations) {
|
||||
if (node.transformId === transformId) {
|
||||
node.transformId = 0;
|
||||
node.emitFlags = 0;
|
||||
node.commentRange = undefined;
|
||||
node.sourceMapRange = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
parseTreeNodesWithAnnotations.length = 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Transforms a source file.
|
||||
*
|
||||
* @param sourceFile The source file to transform.
|
||||
*/
|
||||
function transformSourceFile(sourceFile: SourceFile) {
|
||||
if (isDeclarationFile(sourceFile)) {
|
||||
return sourceFile;
|
||||
}
|
||||
|
||||
return transformation(sourceFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
|
||||
*/
|
||||
function enableSubstitution(kind: SyntaxKind) {
|
||||
enabledSyntaxKindFeatures[kind] |= SyntaxKindFeatureFlags.Substitution;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
emit(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates a node with the current transformation, initializing
|
||||
* various transient transformation properties.
|
||||
*
|
||||
* @param node The node.
|
||||
*/
|
||||
function beforeSetAnnotation(node: Node) {
|
||||
if ((node.flags & NodeFlags.Synthesized) === 0 && node.transformId !== transformId) {
|
||||
// To avoid holding onto transformation artifacts, we keep track of any
|
||||
// parse tree node we are annotating. This allows us to clean them up after
|
||||
// all transformations have completed.
|
||||
parseTreeNodesWithAnnotations.push(node);
|
||||
node.transformId = transformId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets flags that control emit behavior of a node.
|
||||
*
|
||||
* If the node does not have its own NodeEmitFlags set, the node emit flags of its
|
||||
* original pointer are used.
|
||||
*
|
||||
* @param node The node.
|
||||
*/
|
||||
function getNodeEmitFlags(node: Node) {
|
||||
return node.emitFlags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets flags that control emit behavior of a node.
|
||||
*
|
||||
* @param node The node.
|
||||
* @param emitFlags The NodeEmitFlags for the node.
|
||||
*/
|
||||
function setNodeEmitFlags<T extends Node>(node: T, emitFlags: NodeEmitFlags) {
|
||||
beforeSetAnnotation(node);
|
||||
node.emitFlags = emitFlags;
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a custom text range to use when emitting source maps.
|
||||
*
|
||||
* If a node does not have its own custom source map text range, the custom source map
|
||||
* text range of its original pointer is used.
|
||||
*
|
||||
* @param node The node.
|
||||
*/
|
||||
function getSourceMapRange(node: Node) {
|
||||
return node.sourceMapRange || node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a custom text range to use when emitting source maps.
|
||||
*
|
||||
* @param node The node.
|
||||
* @param range The text range.
|
||||
*/
|
||||
function setSourceMapRange<T extends Node>(node: T, range: TextRange) {
|
||||
beforeSetAnnotation(node);
|
||||
node.sourceMapRange = range;
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the TextRange to use for source maps for a token of a node.
|
||||
*
|
||||
* If a node does not have its own custom source map text range for a token, the custom
|
||||
* source map text range for the token of its original pointer is used.
|
||||
*
|
||||
* @param node The node.
|
||||
* @param token The token.
|
||||
*/
|
||||
function getTokenSourceMapRange(node: Node, token: SyntaxKind) {
|
||||
// As a performance optimization, use the cached value of the most recent node.
|
||||
// This helps for cases where this function is called repeatedly for the same node.
|
||||
if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) {
|
||||
return lastTokenSourceMapRange;
|
||||
}
|
||||
|
||||
// Get the custom token source map range for a node or from one of its original nodes.
|
||||
// Custom token ranges are not stored on the node to avoid the GC burden.
|
||||
let range: TextRange;
|
||||
let current = node;
|
||||
while (current) {
|
||||
range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined;
|
||||
if (range !== undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
current = current.original;
|
||||
}
|
||||
|
||||
// Cache the most recently requested value.
|
||||
lastTokenSourceMapRangeNode = node;
|
||||
lastTokenSourceMapRangeToken = token;
|
||||
lastTokenSourceMapRange = range;
|
||||
return range;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the TextRange to use for source maps for a token of a node.
|
||||
*
|
||||
* @param node The node.
|
||||
* @param token The token.
|
||||
* @param range The text range.
|
||||
*/
|
||||
function setTokenSourceMapRange<T extends Node>(node: T, token: SyntaxKind, range: TextRange) {
|
||||
// Cache the most recently requested value.
|
||||
lastTokenSourceMapRangeNode = node;
|
||||
lastTokenSourceMapRangeToken = token;
|
||||
lastTokenSourceMapRange = range;
|
||||
tokenSourceMapRanges[getNodeId(node) + "-" + token] = range;
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a custom text range to use when emitting comments.
|
||||
*
|
||||
* If a node does not have its own custom source map text range, the custom source map
|
||||
* text range of its original pointer is used.
|
||||
*
|
||||
* @param node The node.
|
||||
*/
|
||||
function getCommentRange(node: Node) {
|
||||
return node.commentRange || node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a custom text range to use when emitting comments.
|
||||
*/
|
||||
function setCommentRange<T extends Node>(node: T, range: TextRange) {
|
||||
beforeSetAnnotation(node);
|
||||
node.commentRange = range;
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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];
|
||||
}
|
||||
else {
|
||||
hoistedVariableDeclarations.push(decl);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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];
|
||||
}
|
||||
else {
|
||||
hoistedFunctionDeclarations.push(func);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a new lexical environment. Any existing hoisted variable or function declarations
|
||||
* 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
|
||||
// transformation.
|
||||
lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations;
|
||||
lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations;
|
||||
lexicalEnvironmentStackOffset++;
|
||||
hoistedVariableDeclarations = undefined;
|
||||
hoistedFunctionDeclarations = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a lexical environment. The previous set of hoisted declarations are restored and
|
||||
* 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) {
|
||||
statements = [...hoistedFunctionDeclarations];
|
||||
}
|
||||
|
||||
if (hoistedVariableDeclarations) {
|
||||
const statement = createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList(hoistedVariableDeclarations)
|
||||
);
|
||||
|
||||
if (!statements) {
|
||||
statements = [statement];
|
||||
}
|
||||
else {
|
||||
statements.push(statement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore the previous lexical environment.
|
||||
lexicalEnvironmentStackOffset--;
|
||||
hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
|
||||
hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
|
||||
return statements;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High-order function, creates a function that executes a function composition.
|
||||
* For example, `chain(a, b)` is the equivalent of `x => ((a', b') => y => b'(a'(y)))(a(x), b(x))`
|
||||
*
|
||||
* @param args The functions to chain.
|
||||
*/
|
||||
function chain<T, U>(...args: ((t: T) => (u: U) => U)[]): (t: T) => (u: U) => U;
|
||||
function chain<T, U>(a: (t: T) => (u: U) => U, b: (t: T) => (u: U) => U, c: (t: T) => (u: U) => U, d: (t: T) => (u: U) => U, e: (t: T) => (u: U) => U): (t: T) => (u: U) => U {
|
||||
if (e) {
|
||||
const args: ((t: T) => (u: U) => U)[] = [];
|
||||
for (let i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
return t => compose(...map(args, f => f(t)));
|
||||
}
|
||||
else if (d) {
|
||||
return t => compose(a(t), b(t), c(t), d(t));
|
||||
}
|
||||
else if (c) {
|
||||
return t => compose(a(t), b(t), c(t));
|
||||
}
|
||||
else if (b) {
|
||||
return t => compose(a(t), b(t));
|
||||
}
|
||||
else if (a) {
|
||||
return t => compose(a(t));
|
||||
}
|
||||
else {
|
||||
return t => u => u;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* High-order function, composes functions. Note that functions are composed inside-out;
|
||||
* for example, `compose(a, b)` is the equivalent of `x => b(a(x))`.
|
||||
*
|
||||
* @param args The functions to compose.
|
||||
*/
|
||||
function compose<T>(...args: ((t: T) => T)[]): (t: T) => T;
|
||||
function compose<T>(a: (t: T) => T, b: (t: T) => T, c: (t: T) => T, d: (t: T) => T, e: (t: T) => T): (t: T) => T {
|
||||
if (e) {
|
||||
const args: ((t: T) => T)[] = [];
|
||||
for (let i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
return t => reduceLeft<(t: T) => T, T>(args, (u, f) => f(u), t);
|
||||
}
|
||||
else if (d) {
|
||||
return t => d(c(b(a(t))));
|
||||
}
|
||||
else if (c) {
|
||||
return t => c(b(a(t)));
|
||||
}
|
||||
else if (b) {
|
||||
return t => b(a(t));
|
||||
}
|
||||
else if (a) {
|
||||
return t => a(t);
|
||||
}
|
||||
else {
|
||||
return t => t;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
/// <reference path="../factory.ts" />
|
||||
/// <reference path="../visitor.ts" />
|
||||
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
/**
|
||||
* Flattens a destructuring assignment expression.
|
||||
*
|
||||
* @param root The destructuring assignment expression.
|
||||
* @param needsValue Indicates whether the value from the right-hand-side of the
|
||||
* destructuring assignment is needed as part of a larger expression.
|
||||
* @param recordTempVariable A callback used to record new temporary variables.
|
||||
* @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) => VisitResult<Node>): Expression {
|
||||
|
||||
if (isEmptyObjectLiteralOrArrayLiteral(node.left)) {
|
||||
const right = node.right;
|
||||
if (isDestructuringAssignment(right)) {
|
||||
return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor);
|
||||
}
|
||||
else {
|
||||
return node.right;
|
||||
}
|
||||
}
|
||||
|
||||
let location: TextRange = node;
|
||||
let value = node.right;
|
||||
const expressions: Expression[] = [];
|
||||
if (needsValue) {
|
||||
// If the right-hand value of the destructuring assignment needs to be preserved (as
|
||||
// is the case when the destructuring assignmen) is part of a larger expression),
|
||||
// then we need to cache the right-hand value.
|
||||
//
|
||||
// The source map location for the assignment should point to the entire binary
|
||||
// expression.
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor);
|
||||
}
|
||||
else if (nodeIsSynthesized(node)) {
|
||||
// Generally, the source map location for a destructuring assignment is the root
|
||||
// expression.
|
||||
//
|
||||
// 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 = value;
|
||||
}
|
||||
|
||||
flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
|
||||
if (needsValue) {
|
||||
expressions.push(value);
|
||||
}
|
||||
|
||||
const expression = inlineExpressions(expressions);
|
||||
aggregateTransformFlags(expression);
|
||||
return expression;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
|
||||
const expression = createAssignment(name, value, location);
|
||||
|
||||
// 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);
|
||||
emitAssignment(name, value, location);
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens binding patterns in a parameter declaration.
|
||||
*
|
||||
* @param node The ParameterDeclaration to flatten.
|
||||
* @param value The rhs value for the binding pattern.
|
||||
* @param visitor An optional visitor to use to visit expressions.
|
||||
*/
|
||||
export function flattenParameterDestructuring(
|
||||
context: TransformationContext,
|
||||
node: ParameterDeclaration,
|
||||
value: Expression,
|
||||
visitor?: (node: Node) => VisitResult<Node>) {
|
||||
const declarations: VariableDeclaration[] = [];
|
||||
|
||||
flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
|
||||
return declarations;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
|
||||
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
|
||||
|
||||
// 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(/*recordTempVariable*/ undefined);
|
||||
emitAssignment(name, value, location);
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens binding patterns in a variable declaration.
|
||||
*
|
||||
* @param node The VariableDeclaration to flatten.
|
||||
* @param value An optional rhs value for the binding pattern.
|
||||
* @param visitor An optional visitor to use to visit expressions.
|
||||
*/
|
||||
export function flattenVariableDestructuring(
|
||||
context: TransformationContext,
|
||||
node: VariableDeclaration,
|
||||
value?: Expression,
|
||||
visitor?: (node: Node) => VisitResult<Node>) {
|
||||
const declarations: VariableDeclaration[] = [];
|
||||
|
||||
flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
|
||||
return declarations;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
|
||||
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
|
||||
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(/*recordTempVariable*/ undefined);
|
||||
emitAssignment(name, value, location, /*original*/ undefined);
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens binding patterns in a variable declaration and transforms them into an expression.
|
||||
*
|
||||
* @param node The VariableDeclaration to flatten.
|
||||
* @param recordTempVariable A callback used to record new temporary variables.
|
||||
* @param nameSubstitution An optional callback used to substitute binding names.
|
||||
* @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) => VisitResult<Node>) {
|
||||
|
||||
const pendingAssignments: Expression[] = [];
|
||||
|
||||
flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
|
||||
const expression = inlineExpressions(pendingAssignments);
|
||||
aggregateTransformFlags(expression);
|
||||
return expression;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
|
||||
const left = nameSubstitution && nameSubstitution(name) || name;
|
||||
emitPendingAssignment(left, value, location, original);
|
||||
}
|
||||
|
||||
function emitTempVariableAssignment(value: Expression, location: TextRange) {
|
||||
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);
|
||||
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) => VisitResult<Node>) {
|
||||
if (value && visitor) {
|
||||
value = visitNode(value, visitor, isExpression);
|
||||
}
|
||||
|
||||
if (isBinaryExpression(root)) {
|
||||
emitDestructuringAssignment(root.left, value, location);
|
||||
}
|
||||
else {
|
||||
emitBindingElement(root, value);
|
||||
}
|
||||
|
||||
function emitDestructuringAssignment(bindingTarget: Expression | ShorthandPropertyAssignment, value: Expression, location: TextRange) {
|
||||
// When emitting target = value use source map node to highlight, including any temporary assignments needed for this
|
||||
let target: Expression;
|
||||
if (isShorthandPropertyAssignment(bindingTarget)) {
|
||||
const initializer = visitor
|
||||
? visitNode(bindingTarget.objectAssignmentInitializer, visitor, isExpression)
|
||||
: bindingTarget.objectAssignmentInitializer;
|
||||
|
||||
if (initializer) {
|
||||
value = createDefaultValueCheck(value, initializer, location);
|
||||
}
|
||||
|
||||
target = bindingTarget.name;
|
||||
}
|
||||
else if (isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === SyntaxKind.EqualsToken) {
|
||||
const initializer = visitor
|
||||
? visitNode(bindingTarget.right, visitor, isExpression)
|
||||
: bindingTarget.right;
|
||||
|
||||
value = createDefaultValueCheck(value, initializer, location);
|
||||
target = bindingTarget.left;
|
||||
}
|
||||
else {
|
||||
target = bindingTarget;
|
||||
}
|
||||
|
||||
if (target.kind === SyntaxKind.ObjectLiteralExpression) {
|
||||
emitObjectLiteralAssignment(<ObjectLiteralExpression>target, value, location);
|
||||
}
|
||||
else if (target.kind === SyntaxKind.ArrayLiteralExpression) {
|
||||
emitArrayLiteralAssignment(<ArrayLiteralExpression>target, value, location);
|
||||
}
|
||||
else {
|
||||
const name = getMutableClone(<Identifier>target);
|
||||
context.setSourceMapRange(name, target);
|
||||
context.setCommentRange(name, target);
|
||||
emitAssignment(name, value, location, /*original*/ undefined);
|
||||
}
|
||||
}
|
||||
|
||||
function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression, location: TextRange) {
|
||||
const properties = target.properties;
|
||||
if (properties.length !== 1) {
|
||||
// For anything but a single element destructuring we need to generate a temporary
|
||||
// to ensure value is evaluated exactly once.
|
||||
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
|
||||
}
|
||||
|
||||
for (const p of properties) {
|
||||
if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) {
|
||||
const propName = <Identifier | LiteralExpression>(<PropertyAssignment>p).name;
|
||||
const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? <ShorthandPropertyAssignment>p : (<PropertyAssignment>p).initializer || propName;
|
||||
// Assignment for target = value.propName should highligh whole property, hence use p as source map node
|
||||
emitDestructuringAssignment(target, createDestructuringPropertyAccess(value, propName), p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) {
|
||||
const elements = target.elements;
|
||||
const numElements = elements.length;
|
||||
if (numElements !== 1) {
|
||||
// For anything but a single element destructuring we need to generate a temporary
|
||||
// to ensure value is evaluated exactly once.
|
||||
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
|
||||
}
|
||||
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const e = elements[i];
|
||||
if (e.kind !== SyntaxKind.OmittedExpression) {
|
||||
// Assignment for target = value.propName should highligh whole property, hence use e as source map node
|
||||
if (e.kind !== SyntaxKind.SpreadElementExpression) {
|
||||
emitDestructuringAssignment(e, createElementAccess(value, createLiteral(i)), e);
|
||||
}
|
||||
else if (i === numElements - 1) {
|
||||
emitDestructuringAssignment((<SpreadElementExpression>e).expression, createArraySlice(value, i), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitBindingElement(target: BindingElement, value: Expression) {
|
||||
// Any temporary assignments needed to emit target = value should point to target
|
||||
const initializer = visitor ? visitNode(target.initializer, visitor, isExpression) : target.initializer;
|
||||
if (initializer) {
|
||||
// Combine value and initializer
|
||||
value = value ? createDefaultValueCheck(value, initializer, target) : initializer;
|
||||
}
|
||||
else if (!value) {
|
||||
// Use 'void 0' in absence of value and initializer
|
||||
value = createVoidZero();
|
||||
}
|
||||
|
||||
const name = target.name;
|
||||
if (isBindingPattern(name)) {
|
||||
const elements = name.elements;
|
||||
const numElements = elements.length;
|
||||
if (numElements !== 1) {
|
||||
// For anything other than a single-element destructuring we need to generate a temporary
|
||||
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
|
||||
// we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
|
||||
// so in that case, we'll intentionally create that temporary.
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment);
|
||||
}
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const element = elements[i];
|
||||
if (isOmittedExpression(element)) {
|
||||
continue;
|
||||
}
|
||||
else if (name.kind === SyntaxKind.ObjectBindingPattern) {
|
||||
// Rewrite element to a declaration with an initializer that fetches property
|
||||
const propName = element.propertyName || <Identifier>element.name;
|
||||
emitBindingElement(element, createDestructuringPropertyAccess(value, propName));
|
||||
}
|
||||
else {
|
||||
if (!element.dotDotDotToken) {
|
||||
// Rewrite element to a declaration that accesses array element at index i
|
||||
emitBindingElement(element, createElementAccess(value, i));
|
||||
}
|
||||
else if (i === numElements - 1) {
|
||||
emitBindingElement(element, createArraySlice(value, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
emitAssignment(name, value, target, target);
|
||||
}
|
||||
}
|
||||
|
||||
function createDefaultValueCheck(value: Expression, defaultValue: Expression, location: TextRange): Expression {
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
|
||||
return createConditional(
|
||||
createStrictEquality(value, createVoidZero()),
|
||||
createToken(SyntaxKind.QuestionToken),
|
||||
defaultValue,
|
||||
createToken(SyntaxKind.ColonToken),
|
||||
value
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates either a PropertyAccessExpression or an ElementAccessExpression for the
|
||||
* right-hand side of a transformed destructuring assignment.
|
||||
*
|
||||
* @param expression The right-hand expression that is the source of the property.
|
||||
* @param propertyName The destructuring property name.
|
||||
*/
|
||||
function createDestructuringPropertyAccess(expression: Expression, propertyName: PropertyName): LeftHandSideExpression {
|
||||
if (isComputedPropertyName(propertyName)) {
|
||||
return createElementAccess(
|
||||
expression,
|
||||
ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)
|
||||
);
|
||||
}
|
||||
else if (isLiteralExpression(propertyName)) {
|
||||
const clone = getSynthesizedClone(propertyName);
|
||||
clone.text = unescapeIdentifier(clone.text);
|
||||
return createElementAccess(expression, clone);
|
||||
}
|
||||
else {
|
||||
if (isGeneratedIdentifier(propertyName)) {
|
||||
const clone = getSynthesizedClone(propertyName);
|
||||
clone.text = unescapeIdentifier(clone.text);
|
||||
return createPropertyAccess(expression, clone);
|
||||
}
|
||||
else {
|
||||
return createPropertyAccess(expression, createIdentifier(unescapeIdentifier(propertyName.text)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that there exists a declared identifier whose value holds the given expression.
|
||||
* This function is useful to ensure that the expression's value can be read from in subsequent expressions.
|
||||
* Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
|
||||
*
|
||||
* @param value the expression whose value needs to be bound.
|
||||
* @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
|
||||
* 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,
|
||||
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
@@ -0,0 +1,97 @@
|
||||
/// <reference path="../factory.ts" />
|
||||
/// <reference path="../visitor.ts" />
|
||||
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
export function transformES7(context: TransformationContext) {
|
||||
const { hoistVariableDeclaration } = context;
|
||||
|
||||
return transformSourceFile;
|
||||
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
function visitor(node: Node): VisitResult<Node> {
|
||||
if (node.transformFlags & TransformFlags.ES7) {
|
||||
return visitorWorker(node);
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.ContainsES7) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
function visitorWorker(node: Node): VisitResult<Node> {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.BinaryExpression:
|
||||
return visitBinaryExpression(<BinaryExpression>node);
|
||||
|
||||
default:
|
||||
Debug.failBadSyntaxKind(node);
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
}
|
||||
|
||||
function visitBinaryExpression(node: BinaryExpression): Expression {
|
||||
// We are here because ES7 adds support for the exponentiation operator.
|
||||
const left = visitNode(node.left, visitor, isExpression);
|
||||
const right = visitNode(node.right, visitor, isExpression);
|
||||
if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) {
|
||||
let target: Expression;
|
||||
let value: Expression;
|
||||
if (isElementAccessExpression(left)) {
|
||||
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
|
||||
const expressionTemp = createTempVariable(hoistVariableDeclaration);
|
||||
|
||||
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
|
||||
|
||||
target = createElementAccess(
|
||||
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
|
||||
createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
|
||||
/*location*/ left
|
||||
);
|
||||
|
||||
value = createElementAccess(
|
||||
expressionTemp,
|
||||
argumentExpressionTemp,
|
||||
/*location*/ left
|
||||
);
|
||||
}
|
||||
else if (isPropertyAccessExpression(left)) {
|
||||
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
|
||||
const expressionTemp = createTempVariable(hoistVariableDeclaration);
|
||||
|
||||
target = createPropertyAccess(
|
||||
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
|
||||
left.name,
|
||||
/*location*/ left
|
||||
);
|
||||
|
||||
value = createPropertyAccess(
|
||||
expressionTemp,
|
||||
left.name,
|
||||
/*location*/ left
|
||||
);
|
||||
}
|
||||
else {
|
||||
// Transforms `a **= b` into `a = Math.pow(a, b)`
|
||||
target = left;
|
||||
value = left;
|
||||
}
|
||||
|
||||
return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node);
|
||||
}
|
||||
else if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskToken) {
|
||||
// Transforms `a ** b` into `Math.pow(a, b)`
|
||||
return createMathPow(left, right, /*location*/ node);
|
||||
}
|
||||
else {
|
||||
Debug.failBadSyntaxKind(node);
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,531 @@
|
||||
/// <reference path="../factory.ts" />
|
||||
/// <reference path="../visitor.ts" />
|
||||
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
const entities: Map<number> = createEntitiesMap();
|
||||
|
||||
export function transformJsx(context: TransformationContext) {
|
||||
const compilerOptions = context.getCompilerOptions();
|
||||
let currentSourceFile: SourceFile;
|
||||
return transformSourceFile;
|
||||
|
||||
/**
|
||||
* Transform JSX-specific syntax in a SourceFile.
|
||||
*
|
||||
* @param node A SourceFile node.
|
||||
*/
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
currentSourceFile = node;
|
||||
node = visitEachChild(node, visitor, context);
|
||||
currentSourceFile = undefined;
|
||||
return node;
|
||||
}
|
||||
|
||||
function visitor(node: Node): VisitResult<Node> {
|
||||
if (node.transformFlags & TransformFlags.Jsx) {
|
||||
return visitorWorker(node);
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.ContainsJsx) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
function visitorWorker(node: Node): VisitResult<Node> {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.JsxElement:
|
||||
return visitJsxElement(<JsxElement>node, /*isChild*/ false);
|
||||
|
||||
case SyntaxKind.JsxSelfClosingElement:
|
||||
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ false);
|
||||
|
||||
case SyntaxKind.JsxExpression:
|
||||
return visitJsxExpression(<JsxExpression>node);
|
||||
|
||||
default:
|
||||
Debug.failBadSyntaxKind(node);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function transformJsxChildToExpression(node: JsxChild): Expression {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.JsxText:
|
||||
return visitJsxText(<JsxText>node);
|
||||
|
||||
case SyntaxKind.JsxExpression:
|
||||
return visitJsxExpression(<JsxExpression>node);
|
||||
|
||||
case SyntaxKind.JsxElement:
|
||||
return visitJsxElement(<JsxElement>node, /*isChild*/ true);
|
||||
|
||||
case SyntaxKind.JsxSelfClosingElement:
|
||||
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ true);
|
||||
|
||||
default:
|
||||
Debug.failBadSyntaxKind(node);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function visitJsxElement(node: JsxElement, isChild: boolean) {
|
||||
return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
|
||||
}
|
||||
|
||||
function visitJsxSelfClosingElement(node: JsxSelfClosingElement, isChild: boolean) {
|
||||
return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
|
||||
}
|
||||
|
||||
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: JsxChild[], isChild: boolean, location: TextRange) {
|
||||
const tagName = getTagName(node);
|
||||
let objectProperties: Expression;
|
||||
const attrs = node.attributes;
|
||||
if (attrs.length === 0) {
|
||||
// When there are no attributes, React wants "null"
|
||||
objectProperties = createNull();
|
||||
}
|
||||
else {
|
||||
// Map spans of JsxAttribute nodes into object literals and spans
|
||||
// of JsxSpreadAttribute nodes into expressions.
|
||||
const segments = flatten(
|
||||
spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread
|
||||
? map(attrs, transformJsxSpreadAttributeToExpression)
|
||||
: createObjectLiteral(map(attrs, transformJsxAttributeToObjectLiteralElement))
|
||||
)
|
||||
);
|
||||
|
||||
if (isJsxSpreadAttribute(attrs[0])) {
|
||||
// We must always emit at least one object literal before a spread
|
||||
// argument.
|
||||
segments.unshift(createObjectLiteral());
|
||||
}
|
||||
|
||||
// Either emit one big object literal (no spread attribs), or
|
||||
// a call to the __assign helper.
|
||||
objectProperties = singleOrUndefined(segments)
|
||||
|| createAssignHelper(currentSourceFile.externalHelpersModuleName, segments);
|
||||
}
|
||||
|
||||
const element = createReactCreateElement(
|
||||
compilerOptions.reactNamespace,
|
||||
tagName,
|
||||
objectProperties,
|
||||
filter(map(children, transformJsxChildToExpression), isDefined),
|
||||
node,
|
||||
location
|
||||
);
|
||||
|
||||
if (isChild) {
|
||||
startOnNewLine(element);
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
function transformJsxSpreadAttributeToExpression(node: JsxSpreadAttribute) {
|
||||
return visitNode(node.expression, visitor, isExpression);
|
||||
}
|
||||
|
||||
function transformJsxAttributeToObjectLiteralElement(node: JsxAttribute) {
|
||||
const name = getAttributeName(node);
|
||||
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) {
|
||||
const decoded = tryDecodeEntities((<StringLiteral>node).text);
|
||||
return decoded ? createLiteral(decoded, /*location*/ node) : 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[];
|
||||
let firstNonWhitespace = 0;
|
||||
let lastNonWhitespace = -1;
|
||||
|
||||
// JSX trims whitespace at the end and beginning of lines, except that the
|
||||
// start/end of a tag is considered a start/end of a line only if that line is
|
||||
// on the same line as the closing tag. See examples in
|
||||
// tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const c = text.charCodeAt(i);
|
||||
if (isLineBreak(c)) {
|
||||
if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
|
||||
const part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
|
||||
if (!parts) {
|
||||
parts = [];
|
||||
}
|
||||
|
||||
// We do not escape the string here as that is handled by the printer
|
||||
// when it emits the literal. We do, however, need to decode JSX entities.
|
||||
parts.push(createLiteral(decodeEntities(part)));
|
||||
}
|
||||
|
||||
firstNonWhitespace = -1;
|
||||
}
|
||||
else if (!isWhiteSpace(c)) {
|
||||
lastNonWhitespace = i;
|
||||
if (firstNonWhitespace === -1) {
|
||||
firstNonWhitespace = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (firstNonWhitespace !== -1) {
|
||||
const part = text.substr(firstNonWhitespace);
|
||||
if (!parts) {
|
||||
parts = [];
|
||||
}
|
||||
|
||||
// We do not escape the string here as that is handled by the printer
|
||||
// when it emits the literal. We do, however, need to decode JSX entities.
|
||||
parts.push(createLiteral(decodeEntities(part)));
|
||||
}
|
||||
|
||||
if (parts) {
|
||||
return reduceLeft(parts, aggregateJsxTextParts);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregates two expressions by interpolating them with a whitespace literal.
|
||||
*/
|
||||
function aggregateJsxTextParts(left: Expression, right: Expression) {
|
||||
return createAdd(createAdd(left, createLiteral(" ")), right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace entities like " ", "{", and "�" with the characters they encode.
|
||||
* See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
|
||||
*/
|
||||
function decodeEntities(text: string): string {
|
||||
return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, (match, _all, _number, _digits, decimal, hex, word) => {
|
||||
if (decimal) {
|
||||
return String.fromCharCode(parseInt(decimal, 10));
|
||||
}
|
||||
else if (hex) {
|
||||
return String.fromCharCode(parseInt(hex, 16));
|
||||
}
|
||||
else {
|
||||
const ch = entities[word];
|
||||
// If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
|
||||
return ch ? String.fromCharCode(ch) : match;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
|
||||
function tryDecodeEntities(text: string): string | undefined {
|
||||
const decoded = decodeEntities(text);
|
||||
return decoded === text ? undefined : decoded;
|
||||
}
|
||||
|
||||
function getTagName(node: JsxElement | JsxOpeningLikeElement): Expression {
|
||||
if (node.kind === SyntaxKind.JsxElement) {
|
||||
return getTagName((<JsxElement>node).openingElement);
|
||||
}
|
||||
else {
|
||||
const name = (<JsxOpeningLikeElement>node).tagName;
|
||||
if (isIdentifier(name) && isIntrinsicJsxName(name.text)) {
|
||||
return createLiteral(name.text);
|
||||
}
|
||||
else {
|
||||
return createExpressionFromEntityName(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit an attribute name, which is quoted if it needs to be quoted. Because
|
||||
* these emit into an object literal property name, we don't need to be worried
|
||||
* about keywords, just non-identifier characters
|
||||
*/
|
||||
function getAttributeName(node: JsxAttribute): StringLiteral | Identifier {
|
||||
const name = node.name;
|
||||
if (/^[A-Za-z_]\w*$/.test(name.text)) {
|
||||
return name;
|
||||
}
|
||||
else {
|
||||
return createLiteral(name.text);
|
||||
}
|
||||
}
|
||||
|
||||
function visitJsxExpression(node: JsxExpression) {
|
||||
return visitNode(node.expression, visitor, isExpression);
|
||||
}
|
||||
}
|
||||
|
||||
function createEntitiesMap(): Map<number> {
|
||||
return createMap<number>({
|
||||
"quot": 0x0022,
|
||||
"amp": 0x0026,
|
||||
"apos": 0x0027,
|
||||
"lt": 0x003C,
|
||||
"gt": 0x003E,
|
||||
"nbsp": 0x00A0,
|
||||
"iexcl": 0x00A1,
|
||||
"cent": 0x00A2,
|
||||
"pound": 0x00A3,
|
||||
"curren": 0x00A4,
|
||||
"yen": 0x00A5,
|
||||
"brvbar": 0x00A6,
|
||||
"sect": 0x00A7,
|
||||
"uml": 0x00A8,
|
||||
"copy": 0x00A9,
|
||||
"ordf": 0x00AA,
|
||||
"laquo": 0x00AB,
|
||||
"not": 0x00AC,
|
||||
"shy": 0x00AD,
|
||||
"reg": 0x00AE,
|
||||
"macr": 0x00AF,
|
||||
"deg": 0x00B0,
|
||||
"plusmn": 0x00B1,
|
||||
"sup2": 0x00B2,
|
||||
"sup3": 0x00B3,
|
||||
"acute": 0x00B4,
|
||||
"micro": 0x00B5,
|
||||
"para": 0x00B6,
|
||||
"middot": 0x00B7,
|
||||
"cedil": 0x00B8,
|
||||
"sup1": 0x00B9,
|
||||
"ordm": 0x00BA,
|
||||
"raquo": 0x00BB,
|
||||
"frac14": 0x00BC,
|
||||
"frac12": 0x00BD,
|
||||
"frac34": 0x00BE,
|
||||
"iquest": 0x00BF,
|
||||
"Agrave": 0x00C0,
|
||||
"Aacute": 0x00C1,
|
||||
"Acirc": 0x00C2,
|
||||
"Atilde": 0x00C3,
|
||||
"Auml": 0x00C4,
|
||||
"Aring": 0x00C5,
|
||||
"AElig": 0x00C6,
|
||||
"Ccedil": 0x00C7,
|
||||
"Egrave": 0x00C8,
|
||||
"Eacute": 0x00C9,
|
||||
"Ecirc": 0x00CA,
|
||||
"Euml": 0x00CB,
|
||||
"Igrave": 0x00CC,
|
||||
"Iacute": 0x00CD,
|
||||
"Icirc": 0x00CE,
|
||||
"Iuml": 0x00CF,
|
||||
"ETH": 0x00D0,
|
||||
"Ntilde": 0x00D1,
|
||||
"Ograve": 0x00D2,
|
||||
"Oacute": 0x00D3,
|
||||
"Ocirc": 0x00D4,
|
||||
"Otilde": 0x00D5,
|
||||
"Ouml": 0x00D6,
|
||||
"times": 0x00D7,
|
||||
"Oslash": 0x00D8,
|
||||
"Ugrave": 0x00D9,
|
||||
"Uacute": 0x00DA,
|
||||
"Ucirc": 0x00DB,
|
||||
"Uuml": 0x00DC,
|
||||
"Yacute": 0x00DD,
|
||||
"THORN": 0x00DE,
|
||||
"szlig": 0x00DF,
|
||||
"agrave": 0x00E0,
|
||||
"aacute": 0x00E1,
|
||||
"acirc": 0x00E2,
|
||||
"atilde": 0x00E3,
|
||||
"auml": 0x00E4,
|
||||
"aring": 0x00E5,
|
||||
"aelig": 0x00E6,
|
||||
"ccedil": 0x00E7,
|
||||
"egrave": 0x00E8,
|
||||
"eacute": 0x00E9,
|
||||
"ecirc": 0x00EA,
|
||||
"euml": 0x00EB,
|
||||
"igrave": 0x00EC,
|
||||
"iacute": 0x00ED,
|
||||
"icirc": 0x00EE,
|
||||
"iuml": 0x00EF,
|
||||
"eth": 0x00F0,
|
||||
"ntilde": 0x00F1,
|
||||
"ograve": 0x00F2,
|
||||
"oacute": 0x00F3,
|
||||
"ocirc": 0x00F4,
|
||||
"otilde": 0x00F5,
|
||||
"ouml": 0x00F6,
|
||||
"divide": 0x00F7,
|
||||
"oslash": 0x00F8,
|
||||
"ugrave": 0x00F9,
|
||||
"uacute": 0x00FA,
|
||||
"ucirc": 0x00FB,
|
||||
"uuml": 0x00FC,
|
||||
"yacute": 0x00FD,
|
||||
"thorn": 0x00FE,
|
||||
"yuml": 0x00FF,
|
||||
"OElig": 0x0152,
|
||||
"oelig": 0x0153,
|
||||
"Scaron": 0x0160,
|
||||
"scaron": 0x0161,
|
||||
"Yuml": 0x0178,
|
||||
"fnof": 0x0192,
|
||||
"circ": 0x02C6,
|
||||
"tilde": 0x02DC,
|
||||
"Alpha": 0x0391,
|
||||
"Beta": 0x0392,
|
||||
"Gamma": 0x0393,
|
||||
"Delta": 0x0394,
|
||||
"Epsilon": 0x0395,
|
||||
"Zeta": 0x0396,
|
||||
"Eta": 0x0397,
|
||||
"Theta": 0x0398,
|
||||
"Iota": 0x0399,
|
||||
"Kappa": 0x039A,
|
||||
"Lambda": 0x039B,
|
||||
"Mu": 0x039C,
|
||||
"Nu": 0x039D,
|
||||
"Xi": 0x039E,
|
||||
"Omicron": 0x039F,
|
||||
"Pi": 0x03A0,
|
||||
"Rho": 0x03A1,
|
||||
"Sigma": 0x03A3,
|
||||
"Tau": 0x03A4,
|
||||
"Upsilon": 0x03A5,
|
||||
"Phi": 0x03A6,
|
||||
"Chi": 0x03A7,
|
||||
"Psi": 0x03A8,
|
||||
"Omega": 0x03A9,
|
||||
"alpha": 0x03B1,
|
||||
"beta": 0x03B2,
|
||||
"gamma": 0x03B3,
|
||||
"delta": 0x03B4,
|
||||
"epsilon": 0x03B5,
|
||||
"zeta": 0x03B6,
|
||||
"eta": 0x03B7,
|
||||
"theta": 0x03B8,
|
||||
"iota": 0x03B9,
|
||||
"kappa": 0x03BA,
|
||||
"lambda": 0x03BB,
|
||||
"mu": 0x03BC,
|
||||
"nu": 0x03BD,
|
||||
"xi": 0x03BE,
|
||||
"omicron": 0x03BF,
|
||||
"pi": 0x03C0,
|
||||
"rho": 0x03C1,
|
||||
"sigmaf": 0x03C2,
|
||||
"sigma": 0x03C3,
|
||||
"tau": 0x03C4,
|
||||
"upsilon": 0x03C5,
|
||||
"phi": 0x03C6,
|
||||
"chi": 0x03C7,
|
||||
"psi": 0x03C8,
|
||||
"omega": 0x03C9,
|
||||
"thetasym": 0x03D1,
|
||||
"upsih": 0x03D2,
|
||||
"piv": 0x03D6,
|
||||
"ensp": 0x2002,
|
||||
"emsp": 0x2003,
|
||||
"thinsp": 0x2009,
|
||||
"zwnj": 0x200C,
|
||||
"zwj": 0x200D,
|
||||
"lrm": 0x200E,
|
||||
"rlm": 0x200F,
|
||||
"ndash": 0x2013,
|
||||
"mdash": 0x2014,
|
||||
"lsquo": 0x2018,
|
||||
"rsquo": 0x2019,
|
||||
"sbquo": 0x201A,
|
||||
"ldquo": 0x201C,
|
||||
"rdquo": 0x201D,
|
||||
"bdquo": 0x201E,
|
||||
"dagger": 0x2020,
|
||||
"Dagger": 0x2021,
|
||||
"bull": 0x2022,
|
||||
"hellip": 0x2026,
|
||||
"permil": 0x2030,
|
||||
"prime": 0x2032,
|
||||
"Prime": 0x2033,
|
||||
"lsaquo": 0x2039,
|
||||
"rsaquo": 0x203A,
|
||||
"oline": 0x203E,
|
||||
"frasl": 0x2044,
|
||||
"euro": 0x20AC,
|
||||
"image": 0x2111,
|
||||
"weierp": 0x2118,
|
||||
"real": 0x211C,
|
||||
"trade": 0x2122,
|
||||
"alefsym": 0x2135,
|
||||
"larr": 0x2190,
|
||||
"uarr": 0x2191,
|
||||
"rarr": 0x2192,
|
||||
"darr": 0x2193,
|
||||
"harr": 0x2194,
|
||||
"crarr": 0x21B5,
|
||||
"lArr": 0x21D0,
|
||||
"uArr": 0x21D1,
|
||||
"rArr": 0x21D2,
|
||||
"dArr": 0x21D3,
|
||||
"hArr": 0x21D4,
|
||||
"forall": 0x2200,
|
||||
"part": 0x2202,
|
||||
"exist": 0x2203,
|
||||
"empty": 0x2205,
|
||||
"nabla": 0x2207,
|
||||
"isin": 0x2208,
|
||||
"notin": 0x2209,
|
||||
"ni": 0x220B,
|
||||
"prod": 0x220F,
|
||||
"sum": 0x2211,
|
||||
"minus": 0x2212,
|
||||
"lowast": 0x2217,
|
||||
"radic": 0x221A,
|
||||
"prop": 0x221D,
|
||||
"infin": 0x221E,
|
||||
"ang": 0x2220,
|
||||
"and": 0x2227,
|
||||
"or": 0x2228,
|
||||
"cap": 0x2229,
|
||||
"cup": 0x222A,
|
||||
"int": 0x222B,
|
||||
"there4": 0x2234,
|
||||
"sim": 0x223C,
|
||||
"cong": 0x2245,
|
||||
"asymp": 0x2248,
|
||||
"ne": 0x2260,
|
||||
"equiv": 0x2261,
|
||||
"le": 0x2264,
|
||||
"ge": 0x2265,
|
||||
"sub": 0x2282,
|
||||
"sup": 0x2283,
|
||||
"nsub": 0x2284,
|
||||
"sube": 0x2286,
|
||||
"supe": 0x2287,
|
||||
"oplus": 0x2295,
|
||||
"otimes": 0x2297,
|
||||
"perp": 0x22A5,
|
||||
"sdot": 0x22C5,
|
||||
"lceil": 0x2308,
|
||||
"rceil": 0x2309,
|
||||
"lfloor": 0x230A,
|
||||
"rfloor": 0x230B,
|
||||
"lang": 0x2329,
|
||||
"rang": 0x232A,
|
||||
"loz": 0x25CA,
|
||||
"spades": 0x2660,
|
||||
"clubs": 0x2663,
|
||||
"hearts": 0x2665,
|
||||
"diams": 0x2666
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/// <reference path="../../factory.ts" />
|
||||
/// <reference path="../../visitor.ts" />
|
||||
|
||||
/*@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(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
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(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
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
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+57
-85
@@ -6,6 +6,11 @@ namespace ts {
|
||||
fileWatcher?: FileWatcher;
|
||||
}
|
||||
|
||||
interface Statistic {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const defaultFormatDiagnosticsHost: FormatDiagnosticsHost = {
|
||||
getCurrentDirectory: () => sys.getCurrentDirectory(),
|
||||
getNewLine: () => sys.newLine,
|
||||
@@ -122,11 +127,11 @@ namespace ts {
|
||||
const gutterSeparator = " ";
|
||||
const resetEscapeSequence = "\u001b[0m";
|
||||
const ellipsis = "...";
|
||||
const categoryFormatMap: Map<string> = {
|
||||
const categoryFormatMap = createMap<string>({
|
||||
[DiagnosticCategory.Warning]: yellowForegroundEscapeSequence,
|
||||
[DiagnosticCategory.Error]: redForegroundEscapeSequence,
|
||||
[DiagnosticCategory.Message]: blueForegroundEscapeSequence,
|
||||
};
|
||||
});
|
||||
|
||||
function formatAndReset(text: string, formatStyle: string) {
|
||||
return formatStyle + text + resetEscapeSequence;
|
||||
@@ -230,18 +235,6 @@ namespace ts {
|
||||
return s;
|
||||
}
|
||||
|
||||
function reportStatisticalValue(name: string, value: string) {
|
||||
sys.write(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine);
|
||||
}
|
||||
|
||||
function reportCountStatistic(name: string, count: number) {
|
||||
reportStatisticalValue(name, "" + count);
|
||||
}
|
||||
|
||||
function reportTimeStatistic(name: string, time: number) {
|
||||
reportStatisticalValue(name, (time / 1000).toFixed(2) + "s");
|
||||
}
|
||||
|
||||
function isJSONSupported() {
|
||||
return typeof JSON === "object" && typeof JSON.parse === "function";
|
||||
}
|
||||
@@ -432,7 +425,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// reset the cache of existing files
|
||||
cachedExistingFiles = {};
|
||||
cachedExistingFiles = createMap<boolean>();
|
||||
|
||||
const compileResult = compile(rootFileNames, compilerOptions, compilerHost);
|
||||
|
||||
@@ -445,10 +438,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
function cachedFileExists(fileName: string): boolean {
|
||||
if (hasProperty(cachedExistingFiles, fileName)) {
|
||||
return cachedExistingFiles[fileName];
|
||||
}
|
||||
return cachedExistingFiles[fileName] = hostFileExists(fileName);
|
||||
return fileName in cachedExistingFiles
|
||||
? cachedExistingFiles[fileName]
|
||||
: cachedExistingFiles[fileName] = hostFileExists(fileName);
|
||||
}
|
||||
|
||||
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) {
|
||||
@@ -490,10 +482,7 @@ namespace ts {
|
||||
sourceFile.fileWatcher.close();
|
||||
sourceFile.fileWatcher = undefined;
|
||||
if (removed) {
|
||||
const index = rootFileNames.indexOf(sourceFile.fileName);
|
||||
if (index >= 0) {
|
||||
rootFileNames.splice(index, 1);
|
||||
}
|
||||
unorderedRemoveItem(rootFileNames, sourceFile.fileName);
|
||||
}
|
||||
startTimerForRecompilation();
|
||||
}
|
||||
@@ -551,7 +540,11 @@ namespace ts {
|
||||
|
||||
function compile(fileNames: string[], compilerOptions: CompilerOptions, compilerHost: CompilerHost) {
|
||||
const hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics;
|
||||
if (hasDiagnostics) performance.enable();
|
||||
let statistics: Statistic[];
|
||||
if (hasDiagnostics) {
|
||||
performance.enable();
|
||||
statistics = [];
|
||||
}
|
||||
|
||||
const program = createProgram(fileNames, compilerOptions, compilerHost);
|
||||
const exitStatus = compileProgram();
|
||||
@@ -595,6 +588,7 @@ namespace ts {
|
||||
reportTimeStatistic("Emit time", emitTime);
|
||||
}
|
||||
reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime);
|
||||
reportStatistics();
|
||||
|
||||
performance.disable();
|
||||
}
|
||||
@@ -636,6 +630,36 @@ namespace ts {
|
||||
}
|
||||
return ExitStatus.Success;
|
||||
}
|
||||
|
||||
function reportStatistics() {
|
||||
let nameSize = 0;
|
||||
let valueSize = 0;
|
||||
for (const { name, value } of statistics) {
|
||||
if (name.length > nameSize) {
|
||||
nameSize = name.length;
|
||||
}
|
||||
|
||||
if (value.length > valueSize) {
|
||||
valueSize = value.length;
|
||||
}
|
||||
}
|
||||
|
||||
for (const { name, value } of statistics) {
|
||||
sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + sys.newLine);
|
||||
}
|
||||
}
|
||||
|
||||
function reportStatisticalValue(name: string, value: string) {
|
||||
statistics.push({ name, value });
|
||||
}
|
||||
|
||||
function reportCountStatistic(name: string, count: number) {
|
||||
reportStatisticalValue(name, "" + count);
|
||||
}
|
||||
|
||||
function reportTimeStatistic(name: string, time: number) {
|
||||
reportStatisticalValue(name, (time / 1000).toFixed(2) + "s");
|
||||
}
|
||||
}
|
||||
|
||||
function printVersion() {
|
||||
@@ -676,7 +700,7 @@ 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
|
||||
const optionsDescriptionMap = createMap<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];
|
||||
@@ -704,9 +728,10 @@ namespace ts {
|
||||
description = getDiagnosticText(option.description);
|
||||
const options: string[] = [];
|
||||
const element = (<CommandLineOptionOfListType>option).element;
|
||||
forEachKey(<Map<number | string>>element.type, key => {
|
||||
const typeMap = <Map<number | string>>element.type;
|
||||
for (const key in typeMap) {
|
||||
options.push(`'${key}'`);
|
||||
});
|
||||
}
|
||||
optionsDescriptionMap[description] = options;
|
||||
}
|
||||
else {
|
||||
@@ -763,69 +788,16 @@ namespace ts {
|
||||
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* host */ undefined);
|
||||
}
|
||||
else {
|
||||
const compilerOptions = extend(options, defaultInitCompilerOptions);
|
||||
const configurations: any = {
|
||||
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));
|
||||
sys.writeFile(file, JSON.stringify(generateTSConfig(options, fileNames), undefined, 4));
|
||||
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* host */ undefined);
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
function serializeCompilerOptions(options: CompilerOptions): Map<string | number | boolean> {
|
||||
const result: Map<string | number | boolean> = {};
|
||||
const optionsNameMap = getOptionNameMap().optionNameMap;
|
||||
|
||||
for (const name in options) {
|
||||
if (hasProperty(options, name)) {
|
||||
// tsconfig only options cannot be specified via command line,
|
||||
// so we can assume that only types that can appear here string | number | boolean
|
||||
const value = <string | number | boolean>options[name];
|
||||
switch (name) {
|
||||
case "init":
|
||||
case "watch":
|
||||
case "version":
|
||||
case "help":
|
||||
case "project":
|
||||
break;
|
||||
default:
|
||||
let optionDefinition = optionsNameMap[name.toLowerCase()];
|
||||
if (optionDefinition) {
|
||||
if (typeof optionDefinition.type === "string") {
|
||||
// string, number or boolean
|
||||
result[name] = value;
|
||||
}
|
||||
else {
|
||||
// Enum
|
||||
const typeMap = <Map<number>>optionDefinition.type;
|
||||
for (const key in typeMap) {
|
||||
if (hasProperty(typeMap, key)) {
|
||||
if (typeMap[key] === value)
|
||||
result[name] = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) {
|
||||
ts.sys.tryEnableSourceMapsForHost();
|
||||
}
|
||||
|
||||
ts.executeCommandLine(ts.sys.args);
|
||||
|
||||
@@ -20,6 +20,19 @@
|
||||
"utilities.ts",
|
||||
"binder.ts",
|
||||
"checker.ts",
|
||||
"factory.ts",
|
||||
"visitor.ts",
|
||||
"transformers/ts.ts",
|
||||
"transformers/jsx.ts",
|
||||
"transformers/es7.ts",
|
||||
"transformers/es6.ts",
|
||||
"transformers/generators.ts",
|
||||
"transformers/destructuring.ts",
|
||||
"transformers/module/module.ts",
|
||||
"transformers/module/system.ts",
|
||||
"transformers/module/es6.ts",
|
||||
"transformer.ts",
|
||||
"comments.ts",
|
||||
"sourcemap.ts",
|
||||
"declarationEmitter.ts",
|
||||
"emitter.ts",
|
||||
|
||||
+382
-130
@@ -1,9 +1,13 @@
|
||||
|
||||
namespace ts {
|
||||
export interface Map<T> {
|
||||
|
||||
export interface MapLike<T> {
|
||||
[index: string]: T;
|
||||
}
|
||||
|
||||
export interface Map<T> extends MapLike<T> {
|
||||
__mapBrand: any;
|
||||
}
|
||||
|
||||
// branded string type used to store absolute, normalized and canonicalized paths
|
||||
// arbitrary file name can be converted to Path via toPath function
|
||||
export type Path = string & { __pathBrand: any };
|
||||
@@ -210,7 +214,7 @@ namespace ts {
|
||||
IntersectionType,
|
||||
ParenthesizedType,
|
||||
ThisType,
|
||||
StringLiteralType,
|
||||
LiteralType,
|
||||
// Binding patterns
|
||||
ObjectBindingPattern,
|
||||
ArrayBindingPattern,
|
||||
@@ -346,14 +350,25 @@ namespace ts {
|
||||
JSDocTypedefTag,
|
||||
JSDocPropertyTag,
|
||||
JSDocTypeLiteral,
|
||||
JSDocLiteralType,
|
||||
JSDocNullKeyword,
|
||||
JSDocUndefinedKeyword,
|
||||
JSDocNeverKeyword,
|
||||
|
||||
// Synthesized list
|
||||
SyntaxList,
|
||||
|
||||
// Transformation nodes
|
||||
NotEmittedStatement,
|
||||
PartiallyEmittedExpression,
|
||||
|
||||
// Enum value count
|
||||
Count,
|
||||
// Markers
|
||||
FirstAssignment = EqualsToken,
|
||||
LastAssignment = CaretEqualsToken,
|
||||
FirstCompoundAssignment = PlusEqualsToken,
|
||||
LastCompoundAssignment = CaretEqualsToken,
|
||||
FirstReservedWord = BreakKeyword,
|
||||
LastReservedWord = WithKeyword,
|
||||
FirstKeyword = BreakKeyword,
|
||||
@@ -361,7 +376,7 @@ namespace ts {
|
||||
FirstFutureReservedWord = ImplementsKeyword,
|
||||
LastFutureReservedWord = YieldKeyword,
|
||||
FirstTypeNode = TypePredicate,
|
||||
LastTypeNode = StringLiteralType,
|
||||
LastTypeNode = LiteralType,
|
||||
FirstPunctuation = OpenBraceToken,
|
||||
LastPunctuation = CaretEqualsToken,
|
||||
FirstToken = Unknown,
|
||||
@@ -376,12 +391,53 @@ namespace ts {
|
||||
LastBinaryOperator = CaretEqualsToken,
|
||||
FirstNode = QualifiedName,
|
||||
FirstJSDocNode = JSDocTypeExpression,
|
||||
LastJSDocNode = JSDocTypeLiteral,
|
||||
LastJSDocNode = JSDocLiteralType,
|
||||
FirstJSDocTagNode = JSDocComment,
|
||||
LastJSDocTagNode = JSDocTypeLiteral
|
||||
LastJSDocTagNode = JSDocNeverKeyword
|
||||
}
|
||||
|
||||
export const enum NodeFlags {
|
||||
None = 0,
|
||||
Let = 1 << 0, // Variable declaration
|
||||
Const = 1 << 1, // Variable declaration
|
||||
NestedNamespace = 1 << 2, // Namespace declaration
|
||||
Synthesized = 1 << 3, // Node was synthesized during transformation
|
||||
Namespace = 1 << 4, // Namespace declaration
|
||||
ExportContext = 1 << 5, // Export context (initialized by binding)
|
||||
ContainsThis = 1 << 6, // Interface contains references to "this"
|
||||
HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding)
|
||||
HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding)
|
||||
GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope
|
||||
HasClassExtends = 1 << 10, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
|
||||
HasDecorators = 1 << 11, // If the file has decorators (initialized by binding)
|
||||
HasParamDecorators = 1 << 12, // If the file has parameter decorators (initialized by binding)
|
||||
HasAsyncFunctions = 1 << 13, // If the file has async functions (initialized by binding)
|
||||
HasJsxSpreadAttributes = 1 << 14, // If the file as JSX spread attributes (initialized by binding)
|
||||
DisallowInContext = 1 << 15, // If node was parsed in a context where 'in-expressions' are not allowed
|
||||
YieldContext = 1 << 16, // If node was parsed in the 'yield' context created when parsing a generator
|
||||
DecoratorContext = 1 << 17, // If node was parsed as part of a decorator
|
||||
AwaitContext = 1 << 18, // If node was parsed in the 'await' context created when parsing an async function
|
||||
ThisNodeHasError = 1 << 19, // If the parser encountered an error when parsing the code that created this node
|
||||
JavaScriptFile = 1 << 20, // If node was parsed in a JavaScript
|
||||
ThisNodeOrAnySubNodesHasError = 1 << 21, // If this node or any of its children had an error
|
||||
HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node
|
||||
|
||||
BlockScoped = Let | Const,
|
||||
|
||||
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
|
||||
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions | HasJsxSpreadAttributes,
|
||||
ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags,
|
||||
|
||||
// Parsing context flags
|
||||
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile,
|
||||
|
||||
// Exclude these flags when parsing a Type
|
||||
TypeExcludesFlags = YieldContext | AwaitContext,
|
||||
}
|
||||
|
||||
export type ModifiersArray = NodeArray<Modifier>;
|
||||
|
||||
export const enum ModifierFlags {
|
||||
None = 0,
|
||||
Export = 1 << 0, // Declarations
|
||||
Ambient = 1 << 1, // Declarations
|
||||
@@ -393,43 +449,14 @@ namespace ts {
|
||||
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
|
||||
Namespace = 1 << 12, // Namespace declaration
|
||||
ExportContext = 1 << 13, // Export context (initialized by binding)
|
||||
ContainsThis = 1 << 14, // Interface contains references to "this"
|
||||
HasImplicitReturn = 1 << 15, // If function implicitly returns on one of codepaths (initialized by binding)
|
||||
HasExplicitReturn = 1 << 16, // If function has explicit reachable return on one of codepaths (initialized by binding)
|
||||
GlobalAugmentation = 1 << 17, // Set if module declaration is an augmentation for the global scope
|
||||
HasClassExtends = 1 << 18, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
|
||||
HasDecorators = 1 << 19, // If the file has decorators (initialized by binding)
|
||||
HasParamDecorators = 1 << 20, // If the file has parameter decorators (initialized by binding)
|
||||
HasAsyncFunctions = 1 << 21, // If the file has async functions (initialized by binding)
|
||||
DisallowInContext = 1 << 22, // If node was parsed in a context where 'in-expressions' are not allowed
|
||||
YieldContext = 1 << 23, // If node was parsed in the 'yield' context created when parsing a generator
|
||||
DecoratorContext = 1 << 24, // If node was parsed as part of a decorator
|
||||
AwaitContext = 1 << 25, // If node was parsed in the 'await' context created when parsing an async function
|
||||
ThisNodeHasError = 1 << 26, // If the parser encountered an error when parsing the code that created this node
|
||||
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,
|
||||
Const = 1 << 11, // Variable declaration
|
||||
|
||||
HasComputedFlags = 1 << 29, // Modifier flags have been computed
|
||||
|
||||
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async | Readonly,
|
||||
AccessibilityModifier = Public | Private | Protected,
|
||||
// Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
|
||||
ParameterPropertyModifier = AccessibilityModifier | Readonly,
|
||||
BlockScoped = Let | Const,
|
||||
|
||||
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
|
||||
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions,
|
||||
ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags,
|
||||
|
||||
// Parsing context flags
|
||||
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile,
|
||||
|
||||
// Exclude these flags when parsing a Type
|
||||
TypeExcludesFlags = YieldContext | AwaitContext,
|
||||
NonPublicAccessibilityModifier = Private | Protected,
|
||||
}
|
||||
|
||||
export const enum JsxFlags {
|
||||
@@ -452,26 +479,30 @@ namespace ts {
|
||||
export interface Node extends TextRange {
|
||||
kind: SyntaxKind;
|
||||
flags: NodeFlags;
|
||||
/* @internal */ modifierFlagsCache?: ModifierFlags;
|
||||
/* @internal */ transformFlags?: TransformFlags;
|
||||
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
|
||||
modifiers?: ModifiersArray; // Array of modifiers
|
||||
/* @internal */ id?: number; // Unique id (used to look up NodeLinks)
|
||||
parent?: Node; // Parent node (initialized by binding
|
||||
parent?: Node; // Parent node (initialized by binding)
|
||||
/* @internal */ original?: Node; // The original node if this is an updated node.
|
||||
/* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms).
|
||||
/* @internal */ jsDocComments?: JSDocComment[]; // JSDoc for the node, if it has any. Only for .js files.
|
||||
/* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding)
|
||||
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
|
||||
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
|
||||
/* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
|
||||
/* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding)
|
||||
/* @internal */ transformId?: number; // Associates transient transformation properties with a specific transformation (initialized by transformation).
|
||||
/* @internal */ emitFlags?: NodeEmitFlags; // Transient emit flags for a synthesized node (initialized by transformation).
|
||||
/* @internal */ sourceMapRange?: TextRange; // Transient custom sourcemap range for a synthesized node (initialized by transformation).
|
||||
/* @internal */ commentRange?: TextRange; // Transient custom comment range for a synthesized node (initialized by transformation).
|
||||
}
|
||||
|
||||
export interface NodeArray<T> extends Array<T>, TextRange {
|
||||
export interface NodeArray<T extends Node> extends Array<T>, TextRange {
|
||||
hasTrailingComma?: boolean;
|
||||
}
|
||||
|
||||
export interface ModifiersArray extends NodeArray<Modifier> {
|
||||
flags: NodeFlags;
|
||||
}
|
||||
|
||||
export interface Token extends Node {
|
||||
__tokenTag: any;
|
||||
}
|
||||
@@ -488,10 +519,26 @@ namespace ts {
|
||||
// @kind(SyntaxKind.StaticKeyword)
|
||||
export interface Modifier extends Token { }
|
||||
|
||||
/*@internal*/
|
||||
export const enum GeneratedIdentifierKind {
|
||||
None, // Not automatically generated.
|
||||
Auto, // Automatically generated identifier.
|
||||
Loop, // Automatically generated identifier with a preference for '_i'.
|
||||
Unique, // Unique name based on the 'text' property.
|
||||
Node, // Unique name based on the node in the 'original' property.
|
||||
}
|
||||
|
||||
// @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
|
||||
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
|
||||
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
|
||||
}
|
||||
|
||||
// Transient identifier node (marked by id === -1)
|
||||
export interface TransientIdentifier extends Identifier {
|
||||
resolvedSymbol: Symbol;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.QualifiedName)
|
||||
@@ -548,10 +595,12 @@ namespace ts {
|
||||
// @kind(SyntaxKind.ConstructSignature)
|
||||
export interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { }
|
||||
|
||||
export type BindingName = Identifier | BindingPattern;
|
||||
|
||||
// @kind(SyntaxKind.VariableDeclaration)
|
||||
export interface VariableDeclaration extends Declaration {
|
||||
parent?: VariableDeclarationList;
|
||||
name: Identifier | BindingPattern; // Declared variable name
|
||||
name: BindingName; // Declared variable name
|
||||
type?: TypeNode; // Optional type annotation
|
||||
initializer?: Expression; // Optional initializer
|
||||
}
|
||||
@@ -564,7 +613,7 @@ namespace ts {
|
||||
// @kind(SyntaxKind.Parameter)
|
||||
export interface ParameterDeclaration extends Declaration {
|
||||
dotDotDotToken?: Node; // Present on rest parameter
|
||||
name: Identifier | BindingPattern; // Declared parameter name
|
||||
name: BindingName; // Declared parameter name
|
||||
questionToken?: Node; // Present on optional parameter
|
||||
type?: TypeNode; // Optional type annotation
|
||||
initializer?: Expression; // Optional initializer
|
||||
@@ -574,7 +623,7 @@ namespace ts {
|
||||
export interface BindingElement extends Declaration {
|
||||
propertyName?: PropertyName; // Binding property name (in object binding pattern)
|
||||
dotDotDotToken?: Node; // Present on rest binding element
|
||||
name: Identifier | BindingPattern; // Declared binding element name
|
||||
name: BindingName; // Declared binding element name
|
||||
initializer?: Expression; // Optional initializer
|
||||
}
|
||||
|
||||
@@ -639,14 +688,20 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface BindingPattern extends Node {
|
||||
elements: NodeArray<BindingElement>;
|
||||
elements: NodeArray<BindingElement | ArrayBindingElement>;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.ObjectBindingPattern)
|
||||
export interface ObjectBindingPattern extends BindingPattern { }
|
||||
export interface ObjectBindingPattern extends BindingPattern {
|
||||
elements: NodeArray<BindingElement>;
|
||||
}
|
||||
|
||||
export type ArrayBindingElement = BindingElement | OmittedExpression;
|
||||
|
||||
// @kind(SyntaxKind.ArrayBindingPattern)
|
||||
export interface ArrayBindingPattern extends BindingPattern { }
|
||||
export interface ArrayBindingPattern extends BindingPattern {
|
||||
elements: NodeArray<ArrayBindingElement>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Several node kinds share function-like features such as a signature,
|
||||
@@ -794,13 +849,16 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.StringLiteralType)
|
||||
export interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode {
|
||||
export interface LiteralTypeNode extends TypeNode {
|
||||
_stringLiteralTypeBrand: any;
|
||||
literal: Expression;
|
||||
}
|
||||
|
||||
// @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.
|
||||
@@ -816,7 +874,17 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.OmittedExpression)
|
||||
export interface OmittedExpression extends Expression { }
|
||||
export interface OmittedExpression extends Expression {
|
||||
_omittedExpressionBrand: any;
|
||||
}
|
||||
|
||||
// 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;
|
||||
@@ -928,13 +996,18 @@ namespace ts {
|
||||
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
|
||||
// or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
|
||||
// For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
|
||||
// @kind(SyntaxKind.NumericLiteral)
|
||||
// @kind(SyntaxKind.RegularExpressionLiteral)
|
||||
// @kind(SyntaxKind.NoSubstitutionTemplateLiteral)
|
||||
export interface LiteralExpression extends LiteralLikeNode, PrimaryExpression {
|
||||
_literalExpressionBrand: any;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.NumericLiteral)
|
||||
export interface NumericLiteral extends LiteralExpression {
|
||||
_numericLiteralBrand: any;
|
||||
trailingComment?: string;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.TemplateHead)
|
||||
// @kind(SyntaxKind.TemplateMiddle)
|
||||
// @kind(SyntaxKind.TemplateTail)
|
||||
@@ -942,6 +1015,8 @@ namespace ts {
|
||||
_templateLiteralFragmentBrand: any;
|
||||
}
|
||||
|
||||
export type Template = TemplateExpression | LiteralExpression;
|
||||
|
||||
// @kind(SyntaxKind.TemplateExpression)
|
||||
export interface TemplateExpression extends PrimaryExpression {
|
||||
head: TemplateLiteralFragment;
|
||||
@@ -981,13 +1056,19 @@ namespace ts {
|
||||
multiLine?: boolean;
|
||||
}
|
||||
|
||||
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression;
|
||||
export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
|
||||
|
||||
// @kind(SyntaxKind.PropertyAccessExpression)
|
||||
export interface PropertyAccessExpression extends MemberExpression, Declaration {
|
||||
expression: LeftHandSideExpression;
|
||||
name: Identifier;
|
||||
}
|
||||
|
||||
export type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
|
||||
/** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */
|
||||
export interface PropertyAccessEntityNameExpression extends PropertyAccessExpression {
|
||||
_propertyAccessExpressionLikeQualifiedNameBrand?: any;
|
||||
expression: EntityNameExpression;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.ElementAccessExpression)
|
||||
export interface ElementAccessExpression extends MemberExpression {
|
||||
@@ -1014,7 +1095,7 @@ namespace ts {
|
||||
// @kind(SyntaxKind.TaggedTemplateExpression)
|
||||
export interface TaggedTemplateExpression extends MemberExpression {
|
||||
tag: LeftHandSideExpression;
|
||||
template: LiteralExpression | TemplateExpression;
|
||||
template: Template;
|
||||
}
|
||||
|
||||
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
|
||||
@@ -1065,11 +1146,13 @@ namespace ts {
|
||||
/// Either the opening tag in a <Tag>...</Tag> pair, or the lone <Tag /> in a self-closing form
|
||||
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
|
||||
|
||||
export type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute;
|
||||
|
||||
// @kind(SyntaxKind.JsxAttribute)
|
||||
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)
|
||||
@@ -1098,6 +1181,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 { }
|
||||
|
||||
@@ -1114,6 +1204,7 @@ namespace ts {
|
||||
// @kind(SyntaxKind.Block)
|
||||
export interface Block extends Statement {
|
||||
statements: NodeArray<Statement>;
|
||||
/*@internal*/ multiLine?: boolean;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.VariableStatement)
|
||||
@@ -1147,22 +1238,24 @@ namespace ts {
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
export type ForInitializer = VariableDeclarationList | Expression;
|
||||
|
||||
// @kind(SyntaxKind.ForStatement)
|
||||
export interface ForStatement extends IterationStatement {
|
||||
initializer?: VariableDeclarationList | Expression;
|
||||
initializer?: ForInitializer;
|
||||
condition?: Expression;
|
||||
incrementor?: Expression;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.ForInStatement)
|
||||
export interface ForInStatement extends IterationStatement {
|
||||
initializer: VariableDeclarationList | Expression;
|
||||
initializer: ForInitializer;
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.ForOfStatement)
|
||||
export interface ForOfStatement extends IterationStatement {
|
||||
initializer: VariableDeclarationList | Expression;
|
||||
initializer: ForInitializer;
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
@@ -1292,7 +1385,7 @@ namespace ts {
|
||||
export interface EnumMember extends Declaration {
|
||||
// This does include ComputedPropertyName, but the parser will give an error
|
||||
// if it parses a ComputedPropertyName in an EnumMember
|
||||
name: DeclarationName;
|
||||
name: PropertyName;
|
||||
initializer?: Expression;
|
||||
}
|
||||
|
||||
@@ -1304,6 +1397,8 @@ namespace ts {
|
||||
|
||||
export type ModuleBody = ModuleBlock | ModuleDeclaration;
|
||||
|
||||
export type ModuleName = Identifier | StringLiteral;
|
||||
|
||||
// @kind(SyntaxKind.ModuleDeclaration)
|
||||
export interface ModuleDeclaration extends DeclarationStatement {
|
||||
name: Identifier | LiteralExpression;
|
||||
@@ -1315,13 +1410,15 @@ namespace ts {
|
||||
statements: NodeArray<Statement>;
|
||||
}
|
||||
|
||||
export type ModuleReference = EntityName | ExternalModuleReference;
|
||||
|
||||
// @kind(SyntaxKind.ImportEqualsDeclaration)
|
||||
export interface ImportEqualsDeclaration extends DeclarationStatement {
|
||||
name: Identifier;
|
||||
|
||||
// 'EntityName' for an internal module reference, 'ExternalModuleReference' for an external
|
||||
// module reference.
|
||||
moduleReference: EntityName | ExternalModuleReference;
|
||||
moduleReference: ModuleReference;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.ExternalModuleReference)
|
||||
@@ -1339,6 +1436,8 @@ namespace ts {
|
||||
moduleSpecifier: Expression;
|
||||
}
|
||||
|
||||
export type NamedImportBindings = NamespaceImport | NamedImports;
|
||||
|
||||
// In case of:
|
||||
// import d from "mod" => name = d, namedBinding = undefined
|
||||
// import * as ns from "mod" => name = undefined, namedBinding: NamespaceImport = { name: ns }
|
||||
@@ -1348,7 +1447,7 @@ namespace ts {
|
||||
// @kind(SyntaxKind.ImportClause)
|
||||
export interface ImportClause extends Declaration {
|
||||
name?: Identifier; // Default binding
|
||||
namedBindings?: NamespaceImport | NamedImports;
|
||||
namedBindings?: NamedImportBindings;
|
||||
}
|
||||
|
||||
// @kind(SyntaxKind.NamespaceImport)
|
||||
@@ -1491,6 +1590,10 @@ namespace ts {
|
||||
type: JSDocType;
|
||||
}
|
||||
|
||||
export interface JSDocLiteralType extends JSDocType {
|
||||
literal: LiteralTypeNode;
|
||||
}
|
||||
|
||||
export type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType;
|
||||
|
||||
// @kind(SyntaxKind.JSDocRecordMember)
|
||||
@@ -1605,6 +1708,16 @@ namespace ts {
|
||||
antecedent: FlowNode;
|
||||
}
|
||||
|
||||
export type FlowType = Type | IncompleteType;
|
||||
|
||||
// Incomplete types occur during control flow analysis of loops. An IncompleteType
|
||||
// is distinguished from a regular type by a flags value of zero. Incomplete type
|
||||
// objects are internal to the getFlowTypeOfRefecence function and never escape it.
|
||||
export interface IncompleteType {
|
||||
flags: TypeFlags; // No flags set
|
||||
type: Type; // The type marked incomplete
|
||||
}
|
||||
|
||||
export interface AmdDependency {
|
||||
path: string;
|
||||
name: string;
|
||||
@@ -1673,6 +1786,8 @@ namespace ts {
|
||||
/* @internal */ imports: LiteralExpression[];
|
||||
/* @internal */ moduleAugmentations: LiteralExpression[];
|
||||
/* @internal */ patternAmbientModules?: PatternAmbientModule[];
|
||||
// The synthesized identifier for an imported external helpers module.
|
||||
/* @internal */ externalHelpersModuleName?: Identifier;
|
||||
}
|
||||
|
||||
export interface ScriptReferenceHost {
|
||||
@@ -1860,6 +1975,7 @@ namespace ts {
|
||||
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
|
||||
getJsxIntrinsicTagNames(): Symbol[];
|
||||
isOptionalParameter(node: ParameterDeclaration): boolean;
|
||||
getAmbientModules(): Symbol[];
|
||||
|
||||
// Should not be called directly. Should only be accessed through the Program instance.
|
||||
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
|
||||
@@ -1916,6 +2032,7 @@ namespace ts {
|
||||
InElementType = 0x00000040, // Writing an array or union element type
|
||||
UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
|
||||
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
|
||||
InTypeAlias = 0x00000200, // Writing type in type alias declaration
|
||||
}
|
||||
|
||||
export const enum SymbolFormatFlags {
|
||||
@@ -1989,12 +2106,13 @@ namespace ts {
|
||||
// function that can be reached at runtime (e.g. a `class`
|
||||
// declaration or a `var` declaration for the static side
|
||||
// of a type, such as the global `Promise` type in lib.d.ts).
|
||||
VoidType, // The TypeReferenceNode resolves to a Void-like type.
|
||||
VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
|
||||
NumberLikeType, // The TypeReferenceNode resolves to a Number-like type.
|
||||
StringLikeType, // The TypeReferenceNode resolves to a String-like type.
|
||||
BooleanType, // The TypeReferenceNode resolves to a Boolean-like type.
|
||||
ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type.
|
||||
ESSymbolType, // The TypeReferenceNode resolves to the ESSymbol type.
|
||||
Promise, // The TypeReferenceNode resolved to the global Promise constructor symbol.
|
||||
TypeWithCallSignature, // The TypeReferenceNode resolves to a Function type or a type
|
||||
// with call signatures.
|
||||
ObjectType, // The TypeReferenceNode resolves to any other type.
|
||||
@@ -2003,7 +2121,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;
|
||||
@@ -2019,16 +2137,16 @@ namespace ts {
|
||||
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
|
||||
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;
|
||||
isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, 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[];
|
||||
getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[];
|
||||
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
|
||||
}
|
||||
|
||||
@@ -2069,8 +2187,8 @@ namespace ts {
|
||||
Enum = RegularEnum | ConstEnum,
|
||||
Variable = FunctionScopedVariable | BlockScopedVariable,
|
||||
Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
|
||||
Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
|
||||
Namespace = ValueModule | NamespaceModule,
|
||||
Type = Class | Interface | Enum | EnumMember | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
|
||||
Namespace = ValueModule | NamespaceModule | Enum,
|
||||
Module = ValueModule | NamespaceModule,
|
||||
Accessor = GetAccessor | SetAccessor,
|
||||
|
||||
@@ -2084,7 +2202,7 @@ namespace ts {
|
||||
|
||||
ParameterExcludes = Value,
|
||||
PropertyExcludes = None,
|
||||
EnumMemberExcludes = Value,
|
||||
EnumMemberExcludes = Value | Type,
|
||||
FunctionExcludes = Value & ~(Function | ValueModule),
|
||||
ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts
|
||||
InterfaceExcludes = Type & ~(Interface | Class),
|
||||
@@ -2135,6 +2253,8 @@ namespace ts {
|
||||
/* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
|
||||
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
|
||||
/* @internal */ isReferenced?: boolean; // True if the symbol is referenced elsewhere
|
||||
/* @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
|
||||
/* @internal */ isAssigned?: boolean; // True if the symbol is a parameter with assignments
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -2148,6 +2268,8 @@ namespace ts {
|
||||
mapper?: TypeMapper; // Type mapper for instantiation alias
|
||||
referenced?: boolean; // True if alias symbol has been referenced as a value
|
||||
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
|
||||
hasCommonType?: boolean; // True if constituents of synthetic property all have same type
|
||||
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
|
||||
resolvedExports?: SymbolTable; // Resolved exports of module
|
||||
exportsChecked?: boolean; // True if exports of external module have been checked
|
||||
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
|
||||
@@ -2158,9 +2280,7 @@ namespace ts {
|
||||
/* @internal */
|
||||
export interface TransientSymbol extends Symbol, SymbolLinks { }
|
||||
|
||||
export interface SymbolTable {
|
||||
[index: string]: Symbol;
|
||||
}
|
||||
export type SymbolTable = Map<Symbol>;
|
||||
|
||||
/** Represents a "prefix*suffix" pattern. */
|
||||
/* @internal */
|
||||
@@ -2187,23 +2307,26 @@ namespace ts {
|
||||
AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'.
|
||||
AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'.
|
||||
CaptureArguments = 0x00002000, // Lexical 'arguments' used in body (for async functions)
|
||||
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
|
||||
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
|
||||
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
|
||||
ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body.
|
||||
BodyScopedClassBinding = 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
|
||||
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
|
||||
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
|
||||
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
|
||||
ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body.
|
||||
BodyScopedClassBinding = 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
|
||||
AssignmentsMarked = 0x00400000, // Parameter assignments have been marked
|
||||
ClassWithConstructorReference = 0x00800000, // Class that contains a binding to its constructor inside of the class body.
|
||||
ConstructorReferenceInClass = 0x01000000, // Binding to a class constructor inside of the class's body.
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface NodeLinks {
|
||||
flags?: NodeCheckFlags; // Set of flags specific to Node
|
||||
resolvedType?: Type; // Cached type of type node
|
||||
resolvedSignature?: Signature; // Cached signature of signature node or call expression
|
||||
resolvedSymbol?: Symbol; // Cached name resolution result
|
||||
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
|
||||
flags?: NodeCheckFlags; // Set of flags specific to Node
|
||||
enumMemberValue?: number; // Constant value of enum member
|
||||
isVisible?: boolean; // Is this node visible
|
||||
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
|
||||
@@ -2215,57 +2338,65 @@ namespace ts {
|
||||
}
|
||||
|
||||
export const enum TypeFlags {
|
||||
Any = 0x00000001,
|
||||
String = 0x00000002,
|
||||
Number = 0x00000004,
|
||||
Boolean = 0x00000008,
|
||||
Void = 0x00000010,
|
||||
Undefined = 0x00000020,
|
||||
Null = 0x00000040,
|
||||
Enum = 0x00000080, // Enum type
|
||||
StringLiteral = 0x00000100, // String literal type
|
||||
TypeParameter = 0x00000200, // Type parameter
|
||||
Class = 0x00000400, // Class
|
||||
Interface = 0x00000800, // Interface
|
||||
Reference = 0x00001000, // Generic type reference
|
||||
Tuple = 0x00002000, // Tuple
|
||||
Union = 0x00004000, // Union (T | U)
|
||||
Intersection = 0x00008000, // Intersection (T & U)
|
||||
Anonymous = 0x00010000, // Anonymous
|
||||
Instantiated = 0x00020000, // Instantiated anonymous type
|
||||
Any = 1 << 0,
|
||||
String = 1 << 1,
|
||||
Number = 1 << 2,
|
||||
Boolean = 1 << 3,
|
||||
Enum = 1 << 4,
|
||||
StringLiteral = 1 << 5,
|
||||
NumberLiteral = 1 << 6,
|
||||
BooleanLiteral = 1 << 7,
|
||||
EnumLiteral = 1 << 8,
|
||||
ESSymbol = 1 << 9, // Type of symbol primitive introduced in ES6
|
||||
Void = 1 << 10,
|
||||
Undefined = 1 << 11,
|
||||
Null = 1 << 12,
|
||||
Never = 1 << 13, // Never type
|
||||
TypeParameter = 1 << 14, // Type parameter
|
||||
Class = 1 << 15, // Class
|
||||
Interface = 1 << 16, // Interface
|
||||
Reference = 1 << 17, // Generic type reference
|
||||
Tuple = 1 << 18, // Synthesized generic tuple type
|
||||
Union = 1 << 19, // Union (T | U)
|
||||
Intersection = 1 << 20, // Intersection (T & U)
|
||||
Anonymous = 1 << 21, // Anonymous
|
||||
Instantiated = 1 << 22, // Instantiated anonymous type
|
||||
/* @internal */
|
||||
FromSignature = 0x00040000, // Created for signature assignment check
|
||||
ObjectLiteral = 0x00080000, // Originates in an object literal
|
||||
ObjectLiteral = 1 << 23, // Originates in an object literal
|
||||
/* @internal */
|
||||
FreshObjectLiteral = 0x00100000, // Fresh object literal type
|
||||
FreshObjectLiteral = 1 << 24, // Fresh object literal type
|
||||
/* @internal */
|
||||
ContainsWideningType = 0x00200000, // Type is or contains undefined or null widening type
|
||||
ContainsWideningType = 1 << 25, // Type is or contains undefined or null widening type
|
||||
/* @internal */
|
||||
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
|
||||
ContainsObjectLiteral = 1 << 26, // Type is or contains object literal type
|
||||
/* @internal */
|
||||
ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type
|
||||
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
|
||||
Never = 0x08000000, // Never type
|
||||
ContainsAnyFunctionType = 1 << 27, // Type is or contains object literal type
|
||||
ThisType = 1 << 28, // This type
|
||||
ObjectLiteralPatternWithComputedProperties = 1 << 29, // Object literal type implied by binding pattern has computed properties
|
||||
|
||||
/* @internal */
|
||||
Nullable = Undefined | Null,
|
||||
Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral,
|
||||
/* @internal */
|
||||
Falsy = Void | Undefined | Null, // TODO: Add false, 0, and ""
|
||||
DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null,
|
||||
PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean,
|
||||
/* @internal */
|
||||
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null | Never,
|
||||
Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never,
|
||||
/* @internal */
|
||||
Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum,
|
||||
Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal,
|
||||
StringLike = String | StringLiteral,
|
||||
NumberLike = Number | Enum,
|
||||
NumberLike = Number | NumberLiteral | Enum | EnumLiteral,
|
||||
BooleanLike = Boolean | BooleanLiteral,
|
||||
EnumLike = Enum | EnumLiteral,
|
||||
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
|
||||
UnionOrIntersection = Union | Intersection,
|
||||
StructuredType = ObjectType | Union | Intersection,
|
||||
StructuredOrTypeParameter = StructuredType | TypeParameter,
|
||||
|
||||
// 'Narrowable' types are types where narrowing actually narrows.
|
||||
// This *should* be every type other than null, undefined, void, and never
|
||||
Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | Boolean | ESSymbol,
|
||||
Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | BooleanLike | ESSymbol,
|
||||
NotUnionOrUnit = Any | String | Number | ESSymbol | ObjectType,
|
||||
/* @internal */
|
||||
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
|
||||
/* @internal */
|
||||
@@ -2280,6 +2411,8 @@ namespace ts {
|
||||
/* @internal */ id: number; // Unique ID
|
||||
symbol?: Symbol; // Symbol associated with type (if any)
|
||||
pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any)
|
||||
aliasSymbol?: Symbol; // Alias associated with type
|
||||
aliasTypeArguments?: Type[]; // Alias type arguments (if any)
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -2289,10 +2422,20 @@ namespace ts {
|
||||
}
|
||||
|
||||
// String literal types (TypeFlags.StringLiteral)
|
||||
export interface StringLiteralType extends Type {
|
||||
export interface LiteralType extends Type {
|
||||
text: string; // Text of string literal
|
||||
}
|
||||
|
||||
// Enum types (TypeFlags.Enum)
|
||||
export interface EnumType extends Type {
|
||||
memberTypes: Map<EnumLiteralType>;
|
||||
}
|
||||
|
||||
// Enum types (TypeFlags.EnumLiteral)
|
||||
export interface EnumLiteralType extends LiteralType {
|
||||
baseType: EnumType & UnionType;
|
||||
}
|
||||
|
||||
// Object types (TypeFlags.ObjectType)
|
||||
export interface ObjectType extends Type { }
|
||||
|
||||
@@ -2335,16 +2478,12 @@ namespace ts {
|
||||
instantiations: Map<TypeReference>; // Generic instantiation cache
|
||||
}
|
||||
|
||||
export interface TupleType extends ObjectType {
|
||||
elementTypes: Type[]; // Element types
|
||||
}
|
||||
|
||||
export interface UnionOrIntersectionType extends Type {
|
||||
types: Type[]; // Constituent types
|
||||
/* @internal */
|
||||
reducedType: Type; // Reduced union type (all subtypes removed)
|
||||
/* @internal */
|
||||
resolvedProperties: SymbolTable; // Cache of resolved properties
|
||||
/* @internal */
|
||||
couldContainTypeParameters: boolean;
|
||||
}
|
||||
|
||||
export interface UnionType extends UnionOrIntersectionType { }
|
||||
@@ -2413,7 +2552,7 @@ namespace ts {
|
||||
/* @internal */
|
||||
hasRestParameter: boolean; // True if last parameter is rest parameter
|
||||
/* @internal */
|
||||
hasStringLiterals: boolean; // True if specialized
|
||||
hasLiteralTypes: boolean; // True if specialized
|
||||
/* @internal */
|
||||
target?: Signature; // Instantiation target
|
||||
/* @internal */
|
||||
@@ -2443,6 +2582,7 @@ namespace ts {
|
||||
export interface TypeMapper {
|
||||
(t: TypeParameter): Type;
|
||||
mappedTypes?: Type[]; // Types mapped by this mapper
|
||||
targetTypes?: Type[]; // Types substituted for mapped types
|
||||
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).
|
||||
@@ -2453,13 +2593,14 @@ namespace ts {
|
||||
export interface TypeInferences {
|
||||
primary: Type[]; // Inferences made directly to a type parameter
|
||||
secondary: Type[]; // Inferences made to a type parameter in a union type
|
||||
topLevel: boolean; // True if all inferences were made from top-level (not nested in object type) locations
|
||||
isFixed: boolean; // Whether the type parameter is fixed, as defined in section 4.12.2 of the TypeScript spec
|
||||
// If a type parameter is fixed, no more inferences can be made for the type parameter
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface InferenceContext {
|
||||
typeParameters: TypeParameter[]; // Type parameters for which inferences are made
|
||||
signature: Signature; // Generic signature for which inferences are made
|
||||
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
|
||||
inferences: TypeInferences[]; // Inferences made for each type parameter
|
||||
inferredTypes: Type[]; // Inferred type for each type parameter
|
||||
@@ -2522,7 +2663,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export type RootPaths = string[];
|
||||
export type PathSubstitutions = Map<string[]>;
|
||||
export type PathSubstitutions = MapLike<string[]>;
|
||||
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
|
||||
|
||||
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
|
||||
@@ -2546,6 +2687,7 @@ namespace ts {
|
||||
experimentalDecorators?: boolean;
|
||||
forceConsistentCasingInFileNames?: boolean;
|
||||
/*@internal*/help?: boolean;
|
||||
importHelpers?: boolean;
|
||||
/*@internal*/init?: boolean;
|
||||
inlineSourceMap?: boolean;
|
||||
inlineSources?: boolean;
|
||||
@@ -2682,7 +2824,7 @@ namespace ts {
|
||||
fileNames: string[];
|
||||
raw?: any;
|
||||
errors: Diagnostic[];
|
||||
wildcardDirectories?: Map<WatchDirectoryFlags>;
|
||||
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
|
||||
}
|
||||
|
||||
export const enum WatchDirectoryFlags {
|
||||
@@ -2692,7 +2834,7 @@ namespace ts {
|
||||
|
||||
export interface ExpandResult {
|
||||
fileNames: string[];
|
||||
wildcardDirectories: Map<WatchDirectoryFlags>;
|
||||
wildcardDirectories: MapLike<WatchDirectoryFlags>;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -2714,7 +2856,7 @@ namespace ts {
|
||||
|
||||
/* @internal */
|
||||
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
|
||||
type: Map<number | string>; // an object literal mapping named values to actual values
|
||||
type: Map<number | string>; // an object literal mapping named values to actual values
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -2877,6 +3019,7 @@ namespace ts {
|
||||
directoryExists?(directoryName: string): boolean;
|
||||
realpath?(path: string): string;
|
||||
getCurrentDirectory?(): string;
|
||||
getDirectories?(path: string): string[];
|
||||
}
|
||||
|
||||
export interface ResolvedModule {
|
||||
@@ -2932,8 +3075,117 @@ namespace ts {
|
||||
* 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,
|
||||
ContainsTypeScript = 1 << 1,
|
||||
Jsx = 1 << 2,
|
||||
ContainsJsx = 1 << 3,
|
||||
ES7 = 1 << 4,
|
||||
ContainsES7 = 1 << 5,
|
||||
ES6 = 1 << 6,
|
||||
ContainsES6 = 1 << 7,
|
||||
DestructuringAssignment = 1 << 8,
|
||||
Generator = 1 << 9,
|
||||
ContainsGenerator = 1 << 10,
|
||||
|
||||
// Markers
|
||||
// - Flags used to indicate that a subtree contains a specific transformation.
|
||||
ContainsDecorators = 1 << 11,
|
||||
ContainsPropertyInitializer = 1 << 12,
|
||||
ContainsLexicalThis = 1 << 13,
|
||||
ContainsCapturedLexicalThis = 1 << 14,
|
||||
ContainsLexicalThisInComputedPropertyName = 1 << 15,
|
||||
ContainsDefaultValueAssignments = 1 << 16,
|
||||
ContainsParameterPropertyAssignments = 1 << 17,
|
||||
ContainsSpreadElementExpression = 1 << 18,
|
||||
ContainsComputedPropertyName = 1 << 19,
|
||||
ContainsBlockScopedBinding = 1 << 20,
|
||||
ContainsBindingPattern = 1 << 21,
|
||||
ContainsYield = 1 << 22,
|
||||
ContainsHoistedDeclarationOrCompletion = 1 << 23,
|
||||
|
||||
HasComputedFlags = 1 << 29, // Transform flags have been computed.
|
||||
|
||||
// Assertions
|
||||
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
|
||||
AssertTypeScript = TypeScript | ContainsTypeScript,
|
||||
AssertJsx = Jsx | ContainsJsx,
|
||||
AssertES7 = ES7 | ContainsES7,
|
||||
AssertES6 = ES6 | ContainsES6,
|
||||
AssertGenerator = Generator | ContainsGenerator,
|
||||
|
||||
// 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 | Generator | HasComputedFlags,
|
||||
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName,
|
||||
ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
|
||||
TypeExcludes = ~ContainsTypeScript,
|
||||
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
|
||||
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadElementExpression,
|
||||
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern,
|
||||
ParameterExcludes = NodeExcludes | ContainsBindingPattern,
|
||||
|
||||
// Masks
|
||||
// - Additional bitmasks
|
||||
TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators,
|
||||
ES6FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments,
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const enum NodeEmitFlags {
|
||||
EmitEmitHelpers = 1 << 0, // Any emit helpers should be written to this node.
|
||||
EmitExportStar = 1 << 1, // The export * helper should be written to this node.
|
||||
EmitSuperHelper = 1 << 2, // Emit the basic _super helper for async methods.
|
||||
EmitAdvancedSuperHelper = 1 << 3, // Emit the advanced _super helper for async methods.
|
||||
UMDDefine = 1 << 4, // This node should be replaced with the UMD define helper.
|
||||
SingleLine = 1 << 5, // The contents of this node should be emitted on a single line.
|
||||
AdviseOnEmitNode = 1 << 6, // The printer should invoke the onEmitNode callback when printing this node.
|
||||
NoSubstitution = 1 << 7, // Disables further substitution of an expression.
|
||||
CapturesThis = 1 << 8, // The function captures a lexical `this`
|
||||
NoLeadingSourceMap = 1 << 9, // Do not emit a leading source map location for this node.
|
||||
NoTrailingSourceMap = 1 << 10, // 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 << 11, // Do not emit source map locations for children of this node.
|
||||
NoTokenLeadingSourceMaps = 1 << 12, // Do not emit leading source map location for token nodes.
|
||||
NoTokenTrailingSourceMaps = 1 << 13, // 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 << 14, // Do not emit leading comments for this node.
|
||||
NoTrailingComments = 1 << 15, // Do not emit trailing comments for this node.
|
||||
NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node.
|
||||
NoNestedComments = 1 << 16,
|
||||
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).
|
||||
NoIndentation = 1 << 20, // Do not indent the node.
|
||||
AsyncFunctionBody = 1 << 21,
|
||||
ReuseTempVariableScope = 1 << 22, // Reuse the existing temp variable scope during emit.
|
||||
CustomPrologue = 1 << 23, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
|
||||
}
|
||||
|
||||
/** Additional context provided to `visitEachChild` */
|
||||
/* @internal */
|
||||
export interface LexicalEnvironment {
|
||||
/** Starts a new lexical environment. */
|
||||
startLexicalEnvironment(): void;
|
||||
|
||||
/** Ends a lexical environment, returning any declarations. */
|
||||
endLexicalEnvironment(): Statement[];
|
||||
}
|
||||
|
||||
|
||||
export interface TextSpan {
|
||||
start: number;
|
||||
length: number;
|
||||
|
||||
+1639
-368
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+11
-219
@@ -1,8 +1,6 @@
|
||||
/// <reference path="harness.ts" />
|
||||
/// <reference path="runnerbase.ts" />
|
||||
/// <reference path="typeWriter.ts" />
|
||||
// In harness baselines, null is different than undefined. See `generateActual` in `harness.ts`.
|
||||
/* tslint:disable:no-null-keyword */
|
||||
|
||||
const enum CompilerTestType {
|
||||
Conformance,
|
||||
@@ -52,7 +50,7 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
private makeUnitName(name: string, root: string) {
|
||||
const path = ts.toPath(name, root, (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
|
||||
const pathStart = ts.toPath(Harness.IO.getCurrentDirectory(), "", (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
|
||||
return path.replace(pathStart, "/");
|
||||
return pathStart ? path.replace(pathStart, "/") : path;
|
||||
};
|
||||
|
||||
public checkTestCodeOutput(fileName: string) {
|
||||
@@ -136,27 +134,16 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
otherFiles = undefined;
|
||||
});
|
||||
|
||||
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
|
||||
return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : "";
|
||||
}
|
||||
|
||||
function getErrorBaseline(toBeCompiled: Harness.Compiler.TestFile[], otherFiles: Harness.Compiler.TestFile[], result: Harness.Compiler.CompilerResult) {
|
||||
return Harness.Compiler.getErrorBaseline(toBeCompiled.concat(otherFiles), result.errors);
|
||||
}
|
||||
|
||||
// check errors
|
||||
it("Correct errors for " + fileName, () => {
|
||||
if (this.errors) {
|
||||
Harness.Baseline.runBaseline("Correct errors for " + fileName, justName.replace(/\.tsx?$/, ".errors.txt"), (): string => {
|
||||
if (result.errors.length === 0) return null;
|
||||
return getErrorBaseline(toBeCompiled, otherFiles, result);
|
||||
});
|
||||
Harness.Compiler.doErrorBaseline(justName, toBeCompiled.concat(otherFiles), result.errors);
|
||||
}
|
||||
});
|
||||
|
||||
it (`Correct module resolution tracing for ${fileName}`, () => {
|
||||
if (options.traceResolution) {
|
||||
Harness.Baseline.runBaseline("Correct module resolution tracing for " + fileName, justName.replace(/\.tsx?$/, ".trace.json"), () => {
|
||||
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".trace.json"), () => {
|
||||
return JSON.stringify(result.traceResults || [], undefined, 4);
|
||||
});
|
||||
}
|
||||
@@ -165,11 +152,13 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
// Source maps?
|
||||
it("Correct sourcemap content for " + fileName, () => {
|
||||
if (options.sourceMap || options.inlineSourceMap) {
|
||||
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => {
|
||||
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => {
|
||||
const record = result.getSourceMapRecord();
|
||||
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
|
||||
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn"t required.
|
||||
if ((options.noEmitOnError && result.errors.length !== 0) || record === undefined) {
|
||||
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
|
||||
/* tslint:disable:no-null-keyword */
|
||||
return null;
|
||||
/* tslint:enable:no-null-keyword */
|
||||
}
|
||||
return record;
|
||||
});
|
||||
@@ -178,87 +167,12 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
|
||||
it("Correct JS output for " + fileName, () => {
|
||||
if (hasNonDtsFiles && this.emit) {
|
||||
if (!options.noEmit && result.files.length === 0 && result.errors.length === 0) {
|
||||
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
|
||||
}
|
||||
|
||||
// check js output
|
||||
Harness.Baseline.runBaseline("Correct JS output for " + fileName, justName.replace(/\.tsx?/, ".js"), () => {
|
||||
let tsCode = "";
|
||||
const tsSources = otherFiles.concat(toBeCompiled);
|
||||
if (tsSources.length > 1) {
|
||||
tsCode += "//// [" + fileName + "] ////\r\n\r\n";
|
||||
}
|
||||
for (let i = 0; i < tsSources.length; i++) {
|
||||
tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n";
|
||||
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : "");
|
||||
}
|
||||
|
||||
let jsCode = "";
|
||||
for (let i = 0; i < result.files.length; i++) {
|
||||
jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n";
|
||||
jsCode += getByteOrderMarkText(result.files[i]);
|
||||
jsCode += result.files[i].code;
|
||||
}
|
||||
|
||||
if (result.declFilesCode.length > 0) {
|
||||
jsCode += "\r\n\r\n";
|
||||
for (let i = 0; i < result.declFilesCode.length; i++) {
|
||||
jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n";
|
||||
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
|
||||
jsCode += result.declFilesCode[i].code;
|
||||
}
|
||||
}
|
||||
|
||||
const declFileCompilationResult =
|
||||
Harness.Compiler.compileDeclarationFiles(
|
||||
toBeCompiled, otherFiles, result, harnessSettings, options, /*currentDirectory*/ undefined);
|
||||
|
||||
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
|
||||
jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
|
||||
jsCode += "\r\n\r\n";
|
||||
jsCode += getErrorBaseline(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles, declFileCompilationResult.declResult);
|
||||
}
|
||||
|
||||
if (jsCode.length > 0) {
|
||||
return tsCode + "\r\n\r\n" + jsCode;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
Harness.Compiler.doJsEmitBaseline(justName, fileName, options, result, toBeCompiled, otherFiles, harnessSettings);
|
||||
}
|
||||
});
|
||||
|
||||
it("Correct Sourcemap output for " + fileName, () => {
|
||||
if (options.inlineSourceMap) {
|
||||
if (result.sourceMaps.length > 0) {
|
||||
throw new Error("No sourcemap files should be generated if inlineSourceMaps was set.");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
else if (options.sourceMap) {
|
||||
if (result.sourceMaps.length !== result.files.length) {
|
||||
throw new Error("Number of sourcemap files should be same as js files.");
|
||||
}
|
||||
|
||||
Harness.Baseline.runBaseline("Correct Sourcemap output for " + fileName, justName.replace(/\.tsx?/, ".js.map"), () => {
|
||||
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
|
||||
// We need to return null here or the runBaseLine will actually create a empty file.
|
||||
// Baselining isn't required here because there is no output.
|
||||
return null;
|
||||
}
|
||||
|
||||
let sourceMapCode = "";
|
||||
for (let i = 0; i < result.sourceMaps.length; i++) {
|
||||
sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n";
|
||||
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
|
||||
sourceMapCode += result.sourceMaps[i].code;
|
||||
}
|
||||
|
||||
return sourceMapCode;
|
||||
});
|
||||
}
|
||||
Harness.Compiler.doSourcemapBaseline(justName, options, result);
|
||||
});
|
||||
|
||||
it("Correct type/symbol baselines for " + fileName, () => {
|
||||
@@ -266,129 +180,7 @@ class CompilerBaselineRunner extends RunnerBase {
|
||||
return;
|
||||
}
|
||||
|
||||
// NEWTODO: Type baselines
|
||||
if (result.errors.length !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
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("");
|
||||
}
|
||||
|
||||
Harness.Compiler.doTypeAndSymbolBaseline(justName, result, toBeCompiled.concat(otherFiles).filter(file => !!result.program.getSourceFile(file.unitName)));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+291
-212
@@ -95,14 +95,14 @@ namespace FourSlash {
|
||||
|
||||
export import IndentStyle = ts.IndentStyle;
|
||||
|
||||
const entityMap: ts.Map<string> = {
|
||||
const entityMap = ts.createMap({
|
||||
"&": "&",
|
||||
"\"": """,
|
||||
"'": "'",
|
||||
"/": "/",
|
||||
"<": "<",
|
||||
">": ">"
|
||||
};
|
||||
});
|
||||
|
||||
export function escapeXmlAttributeValue(s: string) {
|
||||
return s.replace(/[&<>"'\/]/g, ch => entityMap[ch]);
|
||||
@@ -204,7 +204,25 @@ namespace FourSlash {
|
||||
|
||||
public formatCodeOptions: ts.FormatCodeOptions;
|
||||
|
||||
private inputFiles: ts.Map<string> = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references
|
||||
private inputFiles = ts.createMap<string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
|
||||
|
||||
private static getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
|
||||
let result = "";
|
||||
ts.forEach(displayParts, part => {
|
||||
if (result) {
|
||||
result += ",\n ";
|
||||
}
|
||||
else {
|
||||
result = "[\n ";
|
||||
}
|
||||
result += JSON.stringify(part);
|
||||
});
|
||||
if (result) {
|
||||
result += "\n]";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Add input file which has matched file name with the given reference-file path.
|
||||
// This is necessary when resolveReference flag is specified
|
||||
@@ -245,14 +263,8 @@ namespace FourSlash {
|
||||
constructor(private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) {
|
||||
// Create a new Services Adapter
|
||||
this.cancellationToken = new TestCancellationToken();
|
||||
const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
|
||||
if (compilationOptions.typeRoots) {
|
||||
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
|
||||
}
|
||||
|
||||
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
|
||||
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
|
||||
this.languageService = languageServiceAdapter.getLanguageService();
|
||||
let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
|
||||
compilationOptions.skipDefaultLibCheck = true;
|
||||
|
||||
// Initialize the language service with all the scripts
|
||||
let startResolveFileRef: FourSlashFile;
|
||||
@@ -260,6 +272,22 @@ namespace FourSlash {
|
||||
ts.forEach(testData.files, file => {
|
||||
// Create map between fileName and its content for easily looking up when resolveReference flag is specified
|
||||
this.inputFiles[file.fileName] = file.content;
|
||||
|
||||
if (ts.getBaseFileName(file.fileName).toLowerCase() === "tsconfig.json") {
|
||||
const configJson = ts.parseConfigFileTextToJson(file.fileName, file.content);
|
||||
assert.isTrue(configJson.config !== undefined);
|
||||
|
||||
// Extend our existing compiler options so that we can also support tsconfig only options
|
||||
if (configJson.config.compilerOptions) {
|
||||
const baseDirectory = ts.normalizePath(ts.getDirectoryPath(file.fileName));
|
||||
const tsConfig = ts.convertCompilerOptionsFromJson(configJson.config.compilerOptions, baseDirectory, file.fileName);
|
||||
|
||||
if (!tsConfig.errors || !tsConfig.errors.length) {
|
||||
compilationOptions = ts.extend(compilationOptions, tsConfig.options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!startResolveFileRef && file.fileOptions[metadataOptionNames.resolveReference] === "true") {
|
||||
startResolveFileRef = file;
|
||||
}
|
||||
@@ -269,6 +297,15 @@ namespace FourSlash {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
if (compilationOptions.typeRoots) {
|
||||
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
|
||||
}
|
||||
|
||||
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
|
||||
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
|
||||
this.languageService = languageServiceAdapter.getLanguageService();
|
||||
|
||||
if (startResolveFileRef) {
|
||||
// Add the entry-point file itself into the languageServiceShimHost
|
||||
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content, /*isRootFile*/ true);
|
||||
@@ -300,11 +337,11 @@ namespace FourSlash {
|
||||
}
|
||||
else {
|
||||
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
|
||||
ts.forEachKey(this.inputFiles, fileName => {
|
||||
for (const fileName in this.inputFiles) {
|
||||
if (!Harness.isDefaultLibraryFile(fileName)) {
|
||||
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName], /*isRootFile*/ true);
|
||||
}
|
||||
});
|
||||
}
|
||||
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
|
||||
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
|
||||
}
|
||||
@@ -323,6 +360,7 @@ namespace FourSlash {
|
||||
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
|
||||
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
|
||||
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
|
||||
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
|
||||
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
|
||||
InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
|
||||
PlaceOpenBraceOnNewLineForFunctions: false,
|
||||
@@ -376,7 +414,7 @@ namespace FourSlash {
|
||||
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
|
||||
const startMarker = this.getMarkerByName(startMarkerName);
|
||||
const endMarker = this.getMarkerByName(endMarkerName);
|
||||
const predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
|
||||
const predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
|
||||
return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
|
||||
};
|
||||
|
||||
@@ -428,12 +466,12 @@ namespace FourSlash {
|
||||
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean;
|
||||
|
||||
if (after) {
|
||||
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
|
||||
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
|
||||
return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
|
||||
};
|
||||
}
|
||||
else {
|
||||
predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
|
||||
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
|
||||
return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
|
||||
};
|
||||
}
|
||||
@@ -458,7 +496,7 @@ namespace FourSlash {
|
||||
endPos = endMarker.position;
|
||||
}
|
||||
|
||||
errors.forEach(function (error: ts.Diagnostic) {
|
||||
errors.forEach(function(error: ts.Diagnostic) {
|
||||
if (predicate(error.start, error.start + error.length, startPos, endPos)) {
|
||||
exists = true;
|
||||
}
|
||||
@@ -475,7 +513,7 @@ namespace FourSlash {
|
||||
Harness.IO.log("Unexpected error(s) found. Error list is:");
|
||||
}
|
||||
|
||||
errors.forEach(function (error: ts.Diagnostic) {
|
||||
errors.forEach(function(error: ts.Diagnostic) {
|
||||
Harness.IO.log(" minChar: " + error.start +
|
||||
", limChar: " + (error.start + error.length) +
|
||||
", message: " + ts.flattenDiagnosticMessageText(error.messageText, Harness.IO.newLine()) + "\n");
|
||||
@@ -506,6 +544,67 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
public verifyGoToDefinitionIs(endMarker: string | string[]) {
|
||||
this.verifyGoToDefinitionWorker(endMarker instanceof Array ? endMarker : [endMarker]);
|
||||
}
|
||||
|
||||
public verifyGoToDefinition(arg0: any, endMarkerNames?: string | string[]) {
|
||||
if (endMarkerNames) {
|
||||
this.verifyGoToDefinitionPlain(arg0, endMarkerNames);
|
||||
}
|
||||
else if (arg0 instanceof Array) {
|
||||
const pairs: [string | string[], string | string[]][] = arg0;
|
||||
for (const [start, end] of pairs) {
|
||||
this.verifyGoToDefinitionPlain(start, end);
|
||||
}
|
||||
}
|
||||
else {
|
||||
const obj: { [startMarkerName: string]: string | string[] } = arg0;
|
||||
for (const startMarkerName in obj) {
|
||||
if (ts.hasProperty(obj, startMarkerName)) {
|
||||
this.verifyGoToDefinitionPlain(startMarkerName, obj[startMarkerName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private verifyGoToDefinitionPlain(startMarkerNames: string | string[], endMarkerNames: string | string[]) {
|
||||
if (startMarkerNames instanceof Array) {
|
||||
for (const start of startMarkerNames) {
|
||||
this.verifyGoToDefinitionSingle(start, endMarkerNames);
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.verifyGoToDefinitionSingle(startMarkerNames, endMarkerNames);
|
||||
}
|
||||
}
|
||||
|
||||
public verifyGoToDefinitionForMarkers(markerNames: string[]) {
|
||||
for (const markerName of markerNames) {
|
||||
this.verifyGoToDefinitionSingle(`${markerName}Reference`, `${markerName}Definition`);
|
||||
}
|
||||
}
|
||||
|
||||
private verifyGoToDefinitionSingle(startMarkerName: string, endMarkerNames: string | string[]) {
|
||||
this.goToMarker(startMarkerName);
|
||||
this.verifyGoToDefinitionWorker(endMarkerNames instanceof Array ? endMarkerNames : [endMarkerNames]);
|
||||
}
|
||||
|
||||
private verifyGoToDefinitionWorker(endMarkers: string[]) {
|
||||
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition) || [];
|
||||
|
||||
if (endMarkers.length !== definitions.length) {
|
||||
this.raiseError(`goToDefinitions failed - expected to find ${endMarkers.length} definitions but got ${definitions.length}`);
|
||||
}
|
||||
|
||||
for (let i = 0; i < endMarkers.length; i++) {
|
||||
const marker = this.getMarkerByName(endMarkers[i]), definition = definitions[i];
|
||||
if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) {
|
||||
this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public verifyGetEmitOutputForCurrentFile(expected: string): void {
|
||||
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
|
||||
if (emit.outputFiles.length !== 1) {
|
||||
@@ -593,9 +692,9 @@ namespace FourSlash {
|
||||
|
||||
public noItemsWithSameNameButDifferentKind(): void {
|
||||
const completions = this.getCompletionListAtCaret();
|
||||
const uniqueItems: ts.Map<string> = {};
|
||||
const uniqueItems = ts.createMap<string>();
|
||||
for (const item of completions.entries) {
|
||||
if (!ts.hasProperty(uniqueItems, item.name)) {
|
||||
if (!(item.name in uniqueItems)) {
|
||||
uniqueItems[item.name] = item.kind;
|
||||
}
|
||||
else {
|
||||
@@ -650,10 +749,10 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
|
||||
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
|
||||
const completions = this.getCompletionListAtCaret();
|
||||
if (completions) {
|
||||
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
|
||||
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind, spanIndex);
|
||||
}
|
||||
else {
|
||||
this.raiseError(`No completions at position '${this.currentCaretPosition}' when looking for '${symbol}'.`);
|
||||
@@ -669,25 +768,32 @@ namespace FourSlash {
|
||||
* @param expectedText the text associated with the symbol
|
||||
* @param expectedDocumentation the documentation text associated with the symbol
|
||||
* @param expectedKind the kind of symbol (see ScriptElementKind)
|
||||
* @param spanIndex the index of the range that the completion item's replacement text span should match
|
||||
*/
|
||||
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) {
|
||||
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string, spanIndex?: number) {
|
||||
const that = this;
|
||||
let replacementSpan: ts.TextSpan;
|
||||
if (spanIndex !== undefined) {
|
||||
replacementSpan = this.getTextSpanForRangeAtIndex(spanIndex);
|
||||
}
|
||||
|
||||
function filterByTextOrDocumentation(entry: ts.CompletionEntry) {
|
||||
const details = that.getCompletionEntryDetails(entry.name);
|
||||
const documentation = ts.displayPartsToString(details.documentation);
|
||||
const text = ts.displayPartsToString(details.displayParts);
|
||||
if (expectedText && expectedDocumentation) {
|
||||
return (documentation === expectedDocumentation && text === expectedText) ? true : false;
|
||||
|
||||
// If any of the expected values are undefined, assume that users don't
|
||||
// care about them.
|
||||
if (replacementSpan && !TestState.textSpansEqual(replacementSpan, entry.replacementSpan)) {
|
||||
return false;
|
||||
}
|
||||
else if (expectedText && !expectedDocumentation) {
|
||||
return text === expectedText ? true : false;
|
||||
else if (expectedText && text !== expectedText) {
|
||||
return false;
|
||||
}
|
||||
else if (expectedDocumentation && !expectedText) {
|
||||
return documentation === expectedDocumentation ? true : false;
|
||||
else if (expectedDocumentation && documentation !== expectedDocumentation) {
|
||||
return false;
|
||||
}
|
||||
// Because expectedText and expectedDocumentation are undefined, we assume that
|
||||
// users don"t care to compare them so we will treat that entry as if the entry has matching text and documentation
|
||||
// and keep it in the list of filtered entry.
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -711,6 +817,10 @@ namespace FourSlash {
|
||||
if (expectedKind) {
|
||||
error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + ".";
|
||||
}
|
||||
if (replacementSpan) {
|
||||
const spanText = filterCompletions[0].replacementSpan ? stringify(filterCompletions[0].replacementSpan) : undefined;
|
||||
error += "Expected replacement span: " + stringify(replacementSpan) + " to equal: " + spanText + ".";
|
||||
}
|
||||
this.raiseError(error);
|
||||
}
|
||||
}
|
||||
@@ -773,7 +883,21 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
public verifyRangesWithSameTextReferenceEachOther() {
|
||||
ts.forEachValue(this.rangesByText(), ranges => this.verifyRangesReferenceEachOther(ranges));
|
||||
ts.forEachProperty(this.rangesByText(), ranges => this.verifyRangesReferenceEachOther(ranges));
|
||||
}
|
||||
|
||||
public verifyDisplayPartsOfReferencedSymbol(expected: ts.SymbolDisplayPart[]) {
|
||||
const referencedSymbols = this.findReferencesAtCaret();
|
||||
|
||||
if (referencedSymbols.length === 0) {
|
||||
this.raiseError("No referenced symbols found at current caret position");
|
||||
}
|
||||
else if (referencedSymbols.length > 1) {
|
||||
this.raiseError("More than one referenced symbol found");
|
||||
}
|
||||
|
||||
assert.equal(TestState.getDisplayPartsJson(referencedSymbols[0].definition.displayParts),
|
||||
TestState.getDisplayPartsJson(expected), this.messageAtLastKnownMarker("referenced symbol definition display parts"));
|
||||
}
|
||||
|
||||
private verifyReferencesWorker(references: ts.ReferenceEntry[], fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) {
|
||||
@@ -810,6 +934,10 @@ namespace FourSlash {
|
||||
return this.languageService.getReferencesAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
}
|
||||
|
||||
private findReferencesAtCaret() {
|
||||
return this.languageService.findReferences(this.activeFile.fileName, this.currentCaretPosition);
|
||||
}
|
||||
|
||||
public getSyntacticDiagnostics(expected: string) {
|
||||
const diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
|
||||
this.testDiagnostics(expected, diagnostics);
|
||||
@@ -826,26 +954,20 @@ namespace FourSlash {
|
||||
assert.equal(actual, expected);
|
||||
}
|
||||
|
||||
public verifyQuickInfoString(negative: boolean, expectedText?: string, expectedDocumentation?: string) {
|
||||
public verifyQuickInfoString(negative: boolean, expectedText: string, expectedDocumentation?: string) {
|
||||
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
const actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : "";
|
||||
const actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : "";
|
||||
|
||||
if (negative) {
|
||||
if (expectedText !== undefined) {
|
||||
assert.notEqual(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
|
||||
}
|
||||
// TODO: should be '==='?
|
||||
if (expectedDocumentation != undefined) {
|
||||
assert.notEqual(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
|
||||
if (expectedDocumentation !== undefined) {
|
||||
assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, this.messageAtLastKnownMarker("quick info doc comment"));
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (expectedText !== undefined) {
|
||||
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
|
||||
}
|
||||
// TODO: should be '==='?
|
||||
if (expectedDocumentation != undefined) {
|
||||
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
|
||||
if (expectedDocumentation !== undefined) {
|
||||
assert.equal(actualQuickInfoDocumentation, expectedDocumentation, this.assertionMessageAtLastKnownMarker("quick info doc"));
|
||||
}
|
||||
}
|
||||
@@ -855,30 +977,12 @@ namespace FourSlash {
|
||||
displayParts: ts.SymbolDisplayPart[],
|
||||
documentation: ts.SymbolDisplayPart[]) {
|
||||
|
||||
function getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
|
||||
let result = "";
|
||||
ts.forEach(displayParts, part => {
|
||||
if (result) {
|
||||
result += ",\n ";
|
||||
}
|
||||
else {
|
||||
result = "[\n ";
|
||||
}
|
||||
result += JSON.stringify(part);
|
||||
});
|
||||
if (result) {
|
||||
result += "\n]";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind"));
|
||||
assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers"));
|
||||
assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan"));
|
||||
assert.equal(getDisplayPartsJson(actualQuickInfo.displayParts), getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
|
||||
assert.equal(getDisplayPartsJson(actualQuickInfo.documentation), getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
|
||||
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
|
||||
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
|
||||
}
|
||||
|
||||
public verifyRenameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]) {
|
||||
@@ -1131,12 +1235,10 @@ namespace FourSlash {
|
||||
|
||||
}
|
||||
Harness.Baseline.runBaseline(
|
||||
"Breakpoint Locations for " + this.activeFile.fileName,
|
||||
baselineFile,
|
||||
() => {
|
||||
return this.baselineCurrentFileLocations(pos => this.getBreakpointStatementLocation(pos));
|
||||
},
|
||||
true /* run immediately */);
|
||||
});
|
||||
}
|
||||
|
||||
public baselineGetEmitOutput() {
|
||||
@@ -1158,7 +1260,6 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
Harness.Baseline.runBaseline(
|
||||
"Generate getEmitOutput baseline : " + emitFiles.join(" "),
|
||||
this.testData.globalOptions[metadataOptionNames.baselineFile],
|
||||
() => {
|
||||
let resultString = "";
|
||||
@@ -1184,8 +1285,23 @@ namespace FourSlash {
|
||||
});
|
||||
|
||||
return resultString;
|
||||
},
|
||||
true /* run immediately */);
|
||||
});
|
||||
}
|
||||
|
||||
public baselineQuickInfo() {
|
||||
let baselineFile = this.testData.globalOptions[metadataOptionNames.baselineFile];
|
||||
if (!baselineFile) {
|
||||
baselineFile = ts.getBaseFileName(this.activeFile.fileName).replace(".ts", ".baseline");
|
||||
}
|
||||
|
||||
Harness.Baseline.runBaseline(
|
||||
baselineFile,
|
||||
() => stringify(
|
||||
this.testData.markers.map(marker => ({
|
||||
marker,
|
||||
quickInfo: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position)
|
||||
}))
|
||||
));
|
||||
}
|
||||
|
||||
public printBreakpointLocation(pos: number) {
|
||||
@@ -1348,14 +1464,7 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
// Enters lines of text at the current caret position
|
||||
public type(text: string) {
|
||||
return this.typeHighFidelity(text);
|
||||
}
|
||||
|
||||
// Enters lines of text at the current caret position, invoking
|
||||
// language service APIs to mimic Visual Studio's behavior
|
||||
// as much as possible
|
||||
private typeHighFidelity(text: string) {
|
||||
public type(text: string, highFidelity = false) {
|
||||
let offset = this.currentCaretPosition;
|
||||
const prevChar = " ";
|
||||
const checkCadence = (text.length >> 2) + 1;
|
||||
@@ -1364,24 +1473,26 @@ namespace FourSlash {
|
||||
// Make the edit
|
||||
const ch = text.charAt(i);
|
||||
this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, ch);
|
||||
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
|
||||
if (highFidelity) {
|
||||
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
|
||||
}
|
||||
|
||||
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, ch);
|
||||
offset++;
|
||||
|
||||
if (ch === "(" || ch === ",") {
|
||||
/* Signature help*/
|
||||
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
|
||||
}
|
||||
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
|
||||
/* Completions */
|
||||
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
|
||||
}
|
||||
if (highFidelity) {
|
||||
if (ch === "(" || ch === ",") {
|
||||
/* Signature help*/
|
||||
this.languageService.getSignatureHelpItems(this.activeFile.fileName, offset);
|
||||
}
|
||||
else if (prevChar === " " && /A-Za-z_/.test(ch)) {
|
||||
/* Completions */
|
||||
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
|
||||
}
|
||||
|
||||
if (i % checkCadence === 0) {
|
||||
this.checkPostEditInvariants();
|
||||
// this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
|
||||
// this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
|
||||
if (i % checkCadence === 0) {
|
||||
this.checkPostEditInvariants();
|
||||
}
|
||||
}
|
||||
|
||||
// Handle post-keystroke formatting
|
||||
@@ -1389,14 +1500,12 @@ 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.checkPostEditInvariants();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Move the caret to wherever we ended up
|
||||
this.currentCaretPosition = offset;
|
||||
|
||||
this.fixCaretPosition();
|
||||
this.checkPostEditInvariants();
|
||||
}
|
||||
@@ -1415,7 +1524,6 @@ namespace FourSlash {
|
||||
const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions);
|
||||
if (edits.length) {
|
||||
offset += this.applyEdits(this.activeFile.fileName, edits, /*isFormattingEdit*/ true);
|
||||
this.checkPostEditInvariants();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1554,25 +1662,10 @@ namespace FourSlash {
|
||||
this.goToPosition(len);
|
||||
}
|
||||
|
||||
public goToDefinition(definitionIndex: number) {
|
||||
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
if (!definitions || !definitions.length) {
|
||||
this.raiseError("goToDefinition failed - expected to at least one definition location but got 0");
|
||||
}
|
||||
|
||||
if (definitionIndex >= definitions.length) {
|
||||
this.raiseError(`goToDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`);
|
||||
}
|
||||
|
||||
const definition = definitions[definitionIndex];
|
||||
this.openFile(definition.fileName);
|
||||
this.currentCaretPosition = definition.textSpan.start;
|
||||
}
|
||||
|
||||
public goToTypeDefinition(definitionIndex: number) {
|
||||
const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
if (!definitions || !definitions.length) {
|
||||
this.raiseError("goToTypeDefinition failed - expected to at least one definition location but got 0");
|
||||
this.raiseError("goToTypeDefinition failed - expected to find at least one definition location but got 0");
|
||||
}
|
||||
|
||||
if (definitionIndex >= definitions.length) {
|
||||
@@ -1584,28 +1677,6 @@ namespace FourSlash {
|
||||
this.currentCaretPosition = definition.textSpan.start;
|
||||
}
|
||||
|
||||
public verifyDefinitionLocationExists(negative: boolean) {
|
||||
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
|
||||
const foundDefinitions = definitions && definitions.length;
|
||||
|
||||
if (foundDefinitions && negative) {
|
||||
this.raiseError(`goToDefinition - expected to 0 definition locations but got ${definitions.length}`);
|
||||
}
|
||||
else if (!foundDefinitions && !negative) {
|
||||
this.raiseError("goToDefinition - expected to at least one definition location but got 0");
|
||||
}
|
||||
}
|
||||
|
||||
public verifyDefinitionsCount(negative: boolean, expectedCount: number) {
|
||||
const assertFn = negative ? assert.notEqual : assert.equal;
|
||||
|
||||
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
const actualCount = definitions && definitions.length || 0;
|
||||
|
||||
assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Definitions Count"));
|
||||
}
|
||||
|
||||
public verifyTypeDefinitionsCount(negative: boolean, expectedCount: number) {
|
||||
const assertFn = negative ? assert.notEqual : assert.equal;
|
||||
|
||||
@@ -1615,18 +1686,12 @@ namespace FourSlash {
|
||||
assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Type definitions Count"));
|
||||
}
|
||||
|
||||
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
|
||||
public verifyGoToDefinitionName(expectedName: string, expectedContainerName: string) {
|
||||
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
const actualDefinitionName = definitions && definitions.length ? definitions[0].name : "";
|
||||
const actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : "";
|
||||
if (negative) {
|
||||
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
|
||||
assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
|
||||
}
|
||||
else {
|
||||
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
|
||||
assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
|
||||
}
|
||||
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
|
||||
assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
|
||||
}
|
||||
|
||||
public getMarkers(): Marker[] {
|
||||
@@ -1634,15 +1699,19 @@ namespace FourSlash {
|
||||
return this.testData.markers.slice(0);
|
||||
}
|
||||
|
||||
public getMarkerNames(): string[] {
|
||||
return Object.keys(this.testData.markerPositions);
|
||||
}
|
||||
|
||||
public getRanges(): Range[] {
|
||||
return this.testData.ranges;
|
||||
}
|
||||
|
||||
public rangesByText(): ts.Map<Range[]> {
|
||||
const result: ts.Map<Range[]> = {};
|
||||
const result = ts.createMap<Range[]>();
|
||||
for (const range of this.getRanges()) {
|
||||
const text = this.rangeText(range);
|
||||
(ts.getProperty(result, text) || (result[text] = [])).push(range);
|
||||
ts.multiMapAdd(result, text, range);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1736,13 +1805,11 @@ namespace FourSlash {
|
||||
|
||||
public baselineCurrentFileNameOrDottedNameSpans() {
|
||||
Harness.Baseline.runBaseline(
|
||||
"Name OrDottedNameSpans for " + this.activeFile.fileName,
|
||||
this.testData.globalOptions[metadataOptionNames.baselineFile],
|
||||
() => {
|
||||
return this.baselineCurrentFileLocations(pos =>
|
||||
this.getNameOrDottedNameSpan(pos));
|
||||
},
|
||||
true /* run immediately */);
|
||||
});
|
||||
}
|
||||
|
||||
public printNameOrDottedNameSpans(pos: number) {
|
||||
@@ -1897,7 +1964,7 @@ namespace FourSlash {
|
||||
|
||||
public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) {
|
||||
|
||||
const openBraceMap: ts.Map<ts.CharacterCodes> = {
|
||||
const openBraceMap = ts.createMap<ts.CharacterCodes>({
|
||||
"(": ts.CharacterCodes.openParen,
|
||||
"{": ts.CharacterCodes.openBrace,
|
||||
"[": ts.CharacterCodes.openBracket,
|
||||
@@ -1905,7 +1972,7 @@ namespace FourSlash {
|
||||
'"': ts.CharacterCodes.doubleQuote,
|
||||
"`": ts.CharacterCodes.backtick,
|
||||
"<": ts.CharacterCodes.lessThan
|
||||
};
|
||||
});
|
||||
|
||||
const charCode = openBraceMap[openingBrace];
|
||||
|
||||
@@ -2161,7 +2228,7 @@ namespace FourSlash {
|
||||
return text.substring(startPos, endPos);
|
||||
}
|
||||
|
||||
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string) {
|
||||
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
if (item.name === name) {
|
||||
@@ -2180,6 +2247,11 @@ namespace FourSlash {
|
||||
assert.equal(item.kind, kind, this.assertionMessageAtLastKnownMarker("completion item kind for " + name));
|
||||
}
|
||||
|
||||
if (spanIndex !== undefined) {
|
||||
const span = this.getTextSpanForRangeAtIndex(spanIndex);
|
||||
assert.isTrue(TestState.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + name));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -2236,6 +2308,17 @@ namespace FourSlash {
|
||||
return `line ${(pos.line + 1)}, col ${pos.character}`;
|
||||
}
|
||||
|
||||
private getTextSpanForRangeAtIndex(index: number): ts.TextSpan {
|
||||
const ranges = this.getRanges();
|
||||
if (ranges && ranges.length > index) {
|
||||
const range = ranges[index];
|
||||
return { start: range.start, length: range.end - range.start };
|
||||
}
|
||||
else {
|
||||
this.raiseError("Supplied span index: " + index + " does not exist in range list of size: " + (ranges ? 0 : ranges.length));
|
||||
}
|
||||
}
|
||||
|
||||
public getMarkerByName(markerName: string) {
|
||||
const markerPos = this.testData.markerPositions[markerName];
|
||||
if (markerPos === undefined) {
|
||||
@@ -2259,6 +2342,10 @@ namespace FourSlash {
|
||||
public resetCancelled(): void {
|
||||
this.cancellationToken.resetCancelled();
|
||||
}
|
||||
|
||||
private static textSpansEqual(a: ts.TextSpan, b: ts.TextSpan) {
|
||||
return a && b && a.start === b.start && a.length === b.length;
|
||||
}
|
||||
}
|
||||
|
||||
export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) {
|
||||
@@ -2267,42 +2354,18 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): void {
|
||||
// Give file paths an absolute path for the virtual file system
|
||||
const absoluteBasePath = ts.combinePaths(Harness.virtualFileSystemRoot, basePath);
|
||||
const absoluteFileName = ts.combinePaths(Harness.virtualFileSystemRoot, fileName);
|
||||
|
||||
// Parse out the files and their metadata
|
||||
const testData = parseTestData(basePath, content, fileName);
|
||||
|
||||
const state = new TestState(basePath, testType, testData);
|
||||
|
||||
let result = "";
|
||||
const fourslashFile: Harness.Compiler.TestFile = {
|
||||
unitName: Harness.Compiler.fourslashFileName,
|
||||
content: undefined,
|
||||
};
|
||||
const testFile: Harness.Compiler.TestFile = {
|
||||
unitName: fileName,
|
||||
content: content
|
||||
};
|
||||
|
||||
const host = Harness.Compiler.createCompilerHost(
|
||||
[fourslashFile, testFile],
|
||||
(fn, contents) => result = contents,
|
||||
ts.ScriptTarget.Latest,
|
||||
Harness.IO.useCaseSensitiveFileNames(),
|
||||
Harness.IO.getCurrentDirectory());
|
||||
|
||||
const program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host);
|
||||
|
||||
const sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3);
|
||||
|
||||
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 testData = parseTestData(absoluteBasePath, content, absoluteFileName);
|
||||
const state = new TestState(absoluteBasePath, testType, testData);
|
||||
const output = ts.transpileModule(content, { reportDiagnostics: true });
|
||||
if (output.diagnostics.length > 0) {
|
||||
throw new Error(`Syntax error in ${absoluteBasePath}: ${output.diagnostics[0].messageText}`);
|
||||
}
|
||||
|
||||
program.emit(sourceFile);
|
||||
|
||||
ts.Debug.assert(!!result);
|
||||
runCode(result, state);
|
||||
runCode(output.outputText, state);
|
||||
}
|
||||
|
||||
function runCode(code: string, state: TestState): void {
|
||||
@@ -2395,13 +2458,14 @@ ${code}
|
||||
// Comment line, check for global/file @options and record them
|
||||
const match = optionRegex.exec(line.substr(2));
|
||||
if (match) {
|
||||
const fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]);
|
||||
const [key, value] = match.slice(1);
|
||||
const fileMetadataNamesIndex = fileMetadataNames.indexOf(key);
|
||||
if (fileMetadataNamesIndex === -1) {
|
||||
// Check if the match is already existed in the global options
|
||||
if (globalOptions[match[1]] !== undefined) {
|
||||
throw new Error("Global Option : '" + match[1] + "' is already existed");
|
||||
if (globalOptions[key] !== undefined) {
|
||||
throw new Error(`Global option '${key}' already exists`);
|
||||
}
|
||||
globalOptions[match[1]] = match[2];
|
||||
globalOptions[key] = value;
|
||||
}
|
||||
else {
|
||||
if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) {
|
||||
@@ -2416,12 +2480,12 @@ ${code}
|
||||
resetLocalData();
|
||||
}
|
||||
|
||||
currentFileName = basePath + "/" + match[2];
|
||||
currentFileOptions[match[1]] = match[2];
|
||||
currentFileName = basePath + "/" + value;
|
||||
currentFileOptions[key] = value;
|
||||
}
|
||||
else {
|
||||
// Add other fileMetadata flag
|
||||
currentFileOptions[match[1]] = match[2];
|
||||
currentFileOptions[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2509,7 +2573,7 @@ ${code}
|
||||
}
|
||||
|
||||
const marker: Marker = {
|
||||
fileName: fileName,
|
||||
fileName,
|
||||
position: location.position,
|
||||
data: markerValue
|
||||
};
|
||||
@@ -2526,7 +2590,7 @@ ${code}
|
||||
|
||||
function recordMarker(fileName: string, location: LocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker {
|
||||
const marker: Marker = {
|
||||
fileName: fileName,
|
||||
fileName,
|
||||
position: location.position
|
||||
};
|
||||
|
||||
@@ -2764,6 +2828,10 @@ namespace FourSlashInterface {
|
||||
return this.state.getMarkers();
|
||||
}
|
||||
|
||||
public markerNames(): string[] {
|
||||
return this.state.getMarkerNames();
|
||||
}
|
||||
|
||||
public marker(name?: string): FourSlash.Marker {
|
||||
return this.state.getMarkerByName(name);
|
||||
}
|
||||
@@ -2799,10 +2867,6 @@ namespace FourSlashInterface {
|
||||
this.state.goToEOF();
|
||||
}
|
||||
|
||||
public definition(definitionIndex = 0) {
|
||||
this.state.goToDefinition(definitionIndex);
|
||||
}
|
||||
|
||||
public type(definitionIndex = 0) {
|
||||
this.state.goToTypeDefinition(definitionIndex);
|
||||
}
|
||||
@@ -2852,12 +2916,12 @@ namespace FourSlashInterface {
|
||||
|
||||
// Verifies the completion list contains the specified symbol. The
|
||||
// completion list is brought up if necessary
|
||||
public completionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
|
||||
public completionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
|
||||
if (this.negative) {
|
||||
this.state.verifyCompletionListDoesNotContain(symbol, text, documentation, kind);
|
||||
this.state.verifyCompletionListDoesNotContain(symbol, text, documentation, kind, spanIndex);
|
||||
}
|
||||
else {
|
||||
this.state.verifyCompletionListContains(symbol, text, documentation, kind);
|
||||
this.state.verifyCompletionListContains(symbol, text, documentation, kind, spanIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2899,7 +2963,7 @@ namespace FourSlashInterface {
|
||||
this.state.verifyErrorExistsAfterMarker(markerName, !this.negative, /*after*/ false);
|
||||
}
|
||||
|
||||
public quickInfoIs(expectedText?: string, expectedDocumentation?: string) {
|
||||
public quickInfoIs(expectedText: string, expectedDocumentation?: string) {
|
||||
this.state.verifyQuickInfoString(this.negative, expectedText, expectedDocumentation);
|
||||
}
|
||||
|
||||
@@ -2907,22 +2971,10 @@ namespace FourSlashInterface {
|
||||
this.state.verifyQuickInfoExists(this.negative);
|
||||
}
|
||||
|
||||
public definitionCountIs(expectedCount: number) {
|
||||
this.state.verifyDefinitionsCount(this.negative, expectedCount);
|
||||
}
|
||||
|
||||
public typeDefinitionCountIs(expectedCount: number) {
|
||||
this.state.verifyTypeDefinitionsCount(this.negative, expectedCount);
|
||||
}
|
||||
|
||||
public definitionLocationExists() {
|
||||
this.state.verifyDefinitionLocationExists(this.negative);
|
||||
}
|
||||
|
||||
public verifyDefinitionsName(name: string, containerName: string) {
|
||||
this.state.verifyDefinitionsName(this.negative, name, containerName);
|
||||
}
|
||||
|
||||
public isValidBraceCompletionAtPosition(openingBrace: string) {
|
||||
this.state.verifyBraceCompletionAtPosition(this.negative, openingBrace);
|
||||
}
|
||||
@@ -2966,6 +3018,25 @@ namespace FourSlashInterface {
|
||||
this.state.verifyCurrentFileContent(text);
|
||||
}
|
||||
|
||||
public goToDefinitionIs(endMarkers: string | string[]) {
|
||||
this.state.verifyGoToDefinitionIs(endMarkers);
|
||||
}
|
||||
|
||||
public goToDefinition(startMarkerName: string | string[], endMarkerName: string | string[]): void;
|
||||
public goToDefinition(startsAndEnds: [string | string[], string | string[]][]): void;
|
||||
public goToDefinition(startsAndEnds: { [startMarkerName: string]: string | string[] }): void;
|
||||
public goToDefinition(arg0: any, endMarkerName?: string | string[]) {
|
||||
this.state.verifyGoToDefinition(arg0, endMarkerName);
|
||||
}
|
||||
|
||||
public goToDefinitionForMarkers(...markerNames: string[]) {
|
||||
this.state.verifyGoToDefinitionForMarkers(markerNames);
|
||||
}
|
||||
|
||||
public goToDefinitionName(name: string, containerName: string) {
|
||||
this.state.verifyGoToDefinitionName(name, containerName);
|
||||
}
|
||||
|
||||
public verifyGetEmitOutputForCurrentFile(expected: string): void {
|
||||
this.state.verifyGetEmitOutputForCurrentFile(expected);
|
||||
}
|
||||
@@ -2986,6 +3057,10 @@ namespace FourSlashInterface {
|
||||
this.state.verifyRangesReferenceEachOther(ranges);
|
||||
}
|
||||
|
||||
public findReferencesDefinitionDisplayPartsAtCaretAre(expected: ts.SymbolDisplayPart[]) {
|
||||
this.state.verifyDisplayPartsOfReferencedSymbol(expected);
|
||||
}
|
||||
|
||||
public rangesWithSameTextReferenceEachOther() {
|
||||
this.state.verifyRangesWithSameTextReferenceEachOther();
|
||||
}
|
||||
@@ -3038,6 +3113,10 @@ namespace FourSlashInterface {
|
||||
this.state.baselineGetEmitOutput();
|
||||
}
|
||||
|
||||
public baselineQuickInfo() {
|
||||
this.state.baselineQuickInfo();
|
||||
}
|
||||
|
||||
public nameOrDottedNameSpanTextIs(text: string) {
|
||||
this.state.verifyCurrentNameOrDottedNameSpanText(text);
|
||||
}
|
||||
|
||||
+363
-88
@@ -416,6 +416,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 {
|
||||
@@ -452,12 +506,17 @@ namespace Harness {
|
||||
getExecutingFilePath(): string;
|
||||
exit(exitCode?: number): void;
|
||||
readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]): string[];
|
||||
tryEnableSourceMapsForHost?(): void;
|
||||
getEnvironmentVariable?(name: string): string;
|
||||
}
|
||||
export var IO: IO;
|
||||
|
||||
// harness always uses one kind of new line
|
||||
const harnessNewLine = "\r\n";
|
||||
|
||||
// Root for file paths that are stored in a virtual file system
|
||||
export const virtualFileSystemRoot = "/";
|
||||
|
||||
namespace IOImpl {
|
||||
declare class Enumerator {
|
||||
public atEnd(): boolean;
|
||||
@@ -490,6 +549,7 @@ namespace Harness {
|
||||
export const directoryExists: typeof IO.directoryExists = fso.FolderExists;
|
||||
export const fileExists: typeof IO.fileExists = fso.FileExists;
|
||||
export const log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
|
||||
export const getEnvironmentVariable: typeof IO.getEnvironmentVariable = name => ts.sys.getEnvironmentVariable(name);
|
||||
export const readDirectory: typeof IO.readDirectory = (path, extension, exclude, include) => ts.sys.readDirectory(path, extension, exclude, include);
|
||||
|
||||
export function createDirectory(path: string) {
|
||||
@@ -559,7 +619,13 @@ namespace Harness {
|
||||
export const writeFile: typeof IO.writeFile = (path, content) => ts.sys.writeFile(path, content);
|
||||
export const fileExists: typeof IO.fileExists = fs.existsSync;
|
||||
export const log: typeof IO.log = s => console.log(s);
|
||||
export const getEnvironmentVariable: typeof IO.getEnvironmentVariable = name => ts.sys.getEnvironmentVariable(name);
|
||||
|
||||
export function tryEnableSourceMapsForHost() {
|
||||
if (ts.sys.tryEnableSourceMapsForHost) {
|
||||
ts.sys.tryEnableSourceMapsForHost();
|
||||
}
|
||||
}
|
||||
export const readDirectory: typeof IO.readDirectory = (path, extension, exclude, include) => ts.sys.readDirectory(path, extension, exclude, include);
|
||||
|
||||
export function createDirectory(path: string) {
|
||||
@@ -710,7 +776,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 undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function fileExists(path: string): boolean {
|
||||
const response = Http.getFileFromServerSync(serverRoot + path);
|
||||
@@ -750,7 +825,7 @@ namespace Harness {
|
||||
|
||||
export function readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]) {
|
||||
const fs = new Utils.VirtualFileSystem(path, useCaseSensitiveFileNames());
|
||||
for (const file in listFiles(path)) {
|
||||
for (const file of listFiles(path)) {
|
||||
fs.addFile(file);
|
||||
}
|
||||
return ts.matchFiles(path, extension, exclude, include, useCaseSensitiveFileNames(), getCurrentDirectory(), path => {
|
||||
@@ -784,7 +859,9 @@ namespace Harness {
|
||||
namespace Harness {
|
||||
export const libFolder = "built/local/";
|
||||
const tcServicesFileName = ts.combinePaths(libFolder, Utils.getExecutionEnvironment() === Utils.ExecutionEnvironment.Browser ? "typescriptServicesInBrowserTest.js" : "typescriptServices.js");
|
||||
export const tcServicesFile = IO.readFile(tcServicesFileName);
|
||||
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;
|
||||
@@ -848,9 +925,9 @@ namespace Harness {
|
||||
export const defaultLibFileName = "lib.d.ts";
|
||||
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
|
||||
|
||||
const libFileNameSourceFileMap: ts.Map<ts.SourceFile> = {
|
||||
const libFileNameSourceFileMap= ts.createMap<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)) {
|
||||
@@ -1005,13 +1082,13 @@ namespace Harness {
|
||||
let optionsIndex: ts.Map<ts.CommandLineOption>;
|
||||
function getCommandLineOption(name: string): ts.CommandLineOption {
|
||||
if (!optionsIndex) {
|
||||
optionsIndex = {};
|
||||
optionsIndex = ts.createMap<ts.CommandLineOption>();
|
||||
const optionDeclarations = harnessOptionDeclarations.concat(ts.optionDeclarations);
|
||||
for (const option of optionDeclarations) {
|
||||
optionsIndex[option.name.toLowerCase()] = option;
|
||||
}
|
||||
}
|
||||
return ts.lookUp(optionsIndex, name.toLowerCase());
|
||||
return optionsIndex[name.toLowerCase()];
|
||||
}
|
||||
|
||||
export function setCompilerOptionsFromHarnessSetting(settings: Harness.TestCaseParser.CompilerSettings, options: ts.CompilerOptions & HarnessOptions): void {
|
||||
@@ -1210,18 +1287,7 @@ namespace Harness {
|
||||
}
|
||||
|
||||
export function minimalDiagnosticsToString(diagnostics: ts.Diagnostic[]) {
|
||||
// This is basically copied from tsc.ts's reportError to replicate what tsc does
|
||||
let errorOutput = "";
|
||||
ts.forEach(diagnostics, diagnostic => {
|
||||
if (diagnostic.file) {
|
||||
const lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
|
||||
errorOutput += diagnostic.file.fileName + "(" + (lineAndCharacter.line + 1) + "," + (lineAndCharacter.character + 1) + "): ";
|
||||
}
|
||||
|
||||
errorOutput += ts.DiagnosticCategory[diagnostic.category].toLowerCase() + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, Harness.IO.newLine()) + Harness.IO.newLine();
|
||||
});
|
||||
|
||||
return errorOutput;
|
||||
return ts.formatDiagnostics(diagnostics, { getCanonicalFileName, getCurrentDirectory: () => "", getNewLine: () => Harness.IO.newLine() });
|
||||
}
|
||||
|
||||
export function getErrorBaseline(inputFiles: TestFile[], diagnostics: ts.Diagnostic[]) {
|
||||
@@ -1339,6 +1405,233 @@ namespace Harness {
|
||||
Harness.IO.newLine() + Harness.IO.newLine() + outputLines.join("\r\n");
|
||||
}
|
||||
|
||||
export function doErrorBaseline(baselinePath: string, inputFiles: TestFile[], errors: ts.Diagnostic[]) {
|
||||
Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), (): string => {
|
||||
if (errors.length === 0) {
|
||||
/* tslint:disable:no-null-keyword */
|
||||
return null;
|
||||
/* tslint:enable:no-null-keyword */
|
||||
}
|
||||
return getErrorBaseline(inputFiles, errors);
|
||||
});
|
||||
}
|
||||
|
||||
export function doTypeAndSymbolBaseline(baselinePath: string, result: CompilerResult, allFiles: {unitName: string, content: string}[], opts?: Harness.Baseline.BaselineOptions) {
|
||||
if (result.errors.length !== 0) {
|
||||
return;
|
||||
}
|
||||
// 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 program = result.program;
|
||||
|
||||
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
|
||||
|
||||
const fullResults = ts.createMap<TypeWriterResult[]>();
|
||||
|
||||
for (const sourceFile of allFiles) {
|
||||
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
|
||||
}
|
||||
|
||||
// Produce baselines. The first gives the types for all expressions.
|
||||
// The second gives symbols for all identifiers.
|
||||
let typesError: Error, symbolsError: Error;
|
||||
try {
|
||||
checkBaseLines(/*isSymbolBaseLine*/ false);
|
||||
}
|
||||
catch (e) {
|
||||
typesError = e;
|
||||
}
|
||||
|
||||
try {
|
||||
checkBaseLines(/*isSymbolBaseLine*/ true);
|
||||
}
|
||||
catch (e) {
|
||||
symbolsError = e;
|
||||
}
|
||||
|
||||
if (typesError && symbolsError) {
|
||||
throw new Error(typesError.message + ts.sys.newLine + symbolsError.message);
|
||||
}
|
||||
|
||||
if (typesError) {
|
||||
throw typesError;
|
||||
}
|
||||
|
||||
if (symbolsError) {
|
||||
throw symbolsError;
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
function checkBaseLines(isSymbolBaseLine: boolean) {
|
||||
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
|
||||
|
||||
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
|
||||
|
||||
// When calling this function from rwc-runner, the baselinePath will have no extension.
|
||||
// As rwc test- file is stored in json which ".json" will get stripped off.
|
||||
// When calling this function from compiler-runner, the baselinePath will then has either ".ts" or ".tsx" extension
|
||||
const outputFileName = ts.endsWith(baselinePath, ".ts") || ts.endsWith(baselinePath, ".tsx") ?
|
||||
baselinePath.replace(/\.tsx?/, fullExtension) : baselinePath.concat(fullExtension);
|
||||
Harness.Baseline.runBaseline(outputFileName, () => fullBaseLine, opts);
|
||||
}
|
||||
|
||||
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("");
|
||||
}
|
||||
}
|
||||
|
||||
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
|
||||
return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : "";
|
||||
}
|
||||
|
||||
export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult) {
|
||||
if (options.inlineSourceMap) {
|
||||
if (result.sourceMaps.length > 0) {
|
||||
throw new Error("No sourcemap files should be generated if inlineSourceMaps was set.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
else if (options.sourceMap) {
|
||||
if (result.sourceMaps.length !== result.files.length) {
|
||||
throw new Error("Number of sourcemap files should be same as js files.");
|
||||
}
|
||||
|
||||
Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ".js.map"), () => {
|
||||
if ((options.noEmitOnError && result.errors.length !== 0) || result.sourceMaps.length === 0) {
|
||||
// We need to return null here or the runBaseLine will actually create a empty file.
|
||||
// Baselining isn't required here because there is no output.
|
||||
/* tslint:disable:no-null-keyword */
|
||||
return null;
|
||||
/* tslint:enable:no-null-keyword */
|
||||
}
|
||||
|
||||
let sourceMapCode = "";
|
||||
for (let i = 0; i < result.sourceMaps.length; i++) {
|
||||
sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n";
|
||||
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
|
||||
sourceMapCode += result.sourceMaps[i].code;
|
||||
}
|
||||
|
||||
return sourceMapCode;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function doJsEmitBaseline(baselinePath: string, header: string, options: ts.CompilerOptions, result: CompilerResult, toBeCompiled: Harness.Compiler.TestFile[], otherFiles: Harness.Compiler.TestFile[], harnessSettings: Harness.TestCaseParser.CompilerSettings) {
|
||||
if (!options.noEmit && result.files.length === 0 && result.errors.length === 0) {
|
||||
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
|
||||
}
|
||||
|
||||
// check js output
|
||||
Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ".js"), () => {
|
||||
let tsCode = "";
|
||||
const tsSources = otherFiles.concat(toBeCompiled);
|
||||
if (tsSources.length > 1) {
|
||||
tsCode += "//// [" + header + "] ////\r\n\r\n";
|
||||
}
|
||||
for (let i = 0; i < tsSources.length; i++) {
|
||||
tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n";
|
||||
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : "");
|
||||
}
|
||||
|
||||
let jsCode = "";
|
||||
for (let i = 0; i < result.files.length; i++) {
|
||||
jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n";
|
||||
jsCode += getByteOrderMarkText(result.files[i]);
|
||||
jsCode += result.files[i].code;
|
||||
}
|
||||
|
||||
if (result.declFilesCode.length > 0) {
|
||||
jsCode += "\r\n\r\n";
|
||||
for (let i = 0; i < result.declFilesCode.length; i++) {
|
||||
jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n";
|
||||
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
|
||||
jsCode += result.declFilesCode[i].code;
|
||||
}
|
||||
}
|
||||
|
||||
const declFileCompilationResult =
|
||||
Harness.Compiler.compileDeclarationFiles(
|
||||
toBeCompiled, otherFiles, result, harnessSettings, options, /*currentDirectory*/ undefined);
|
||||
|
||||
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
|
||||
jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
|
||||
jsCode += "\r\n\r\n";
|
||||
jsCode += Harness.Compiler.getErrorBaseline(declFileCompilationResult.declInputFiles.concat(declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.errors);
|
||||
}
|
||||
|
||||
if (jsCode.length > 0) {
|
||||
return tsCode + "\r\n\r\n" + jsCode;
|
||||
}
|
||||
else {
|
||||
/* tslint:disable:no-null-keyword */
|
||||
return null;
|
||||
/* tslint:enable:no-null-keyword */
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string {
|
||||
// Collect, test, and sort the fileNames
|
||||
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
|
||||
@@ -1432,7 +1725,7 @@ namespace Harness {
|
||||
}
|
||||
|
||||
public getSourceMapRecord() {
|
||||
if (this.sourceMapData) {
|
||||
if (this.sourceMapData && this.sourceMapData.length > 0) {
|
||||
return Harness.SourceMapRecorder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
|
||||
}
|
||||
}
|
||||
@@ -1569,7 +1862,7 @@ namespace Harness {
|
||||
tsConfig.options.configFilePath = data.name;
|
||||
|
||||
// delete entry from the list
|
||||
testUnitData.splice(i, 1);
|
||||
ts.orderedRemoveItemAt(testUnitData, i);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -1580,6 +1873,7 @@ namespace Harness {
|
||||
|
||||
/** Support class for baseline files */
|
||||
export namespace Baseline {
|
||||
const NoContent = "<no content>";
|
||||
|
||||
export interface BaselineOptions {
|
||||
Subfolder?: string;
|
||||
@@ -1614,7 +1908,42 @@ namespace Harness {
|
||||
}
|
||||
|
||||
const fileCache: { [idx: string]: boolean } = {};
|
||||
function generateActual(actualFileName: string, generateContent: () => string): string {
|
||||
function generateActual(generateContent: () => string): string {
|
||||
|
||||
const actual = generateContent();
|
||||
|
||||
if (actual === undefined) {
|
||||
throw new Error("The generated content was \"undefined\". Return \"null\" if no baselining is required.\"");
|
||||
}
|
||||
|
||||
return actual;
|
||||
}
|
||||
|
||||
function compareToBaseline(actual: string, relativeFileName: string, opts: BaselineOptions) {
|
||||
// actual is now either undefined (the generator had an error), null (no file requested),
|
||||
// or some real output of the function
|
||||
if (actual === undefined) {
|
||||
// Nothing to do
|
||||
return;
|
||||
}
|
||||
|
||||
const refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
|
||||
|
||||
/* tslint:disable:no-null-keyword */
|
||||
if (actual === null) {
|
||||
/* tslint:enable:no-null-keyword */
|
||||
actual = NoContent;
|
||||
}
|
||||
|
||||
let expected = "<no content>";
|
||||
if (IO.fileExists(refFileName)) {
|
||||
expected = IO.readFile(refFileName);
|
||||
}
|
||||
|
||||
return { expected, actual };
|
||||
}
|
||||
|
||||
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string) {
|
||||
// For now this is written using TypeScript, because sys is not available when running old test cases.
|
||||
// But we need to move to sys once we have
|
||||
// Creates the directory including its parent if not already present
|
||||
@@ -1640,77 +1969,23 @@ namespace Harness {
|
||||
IO.deleteFile(actualFileName);
|
||||
}
|
||||
|
||||
const actual = generateContent();
|
||||
|
||||
if (actual === undefined) {
|
||||
throw new Error("The generated content was \"undefined\". Return \"null\" if no baselining is required.\"");
|
||||
}
|
||||
|
||||
// Store the content in the 'local' folder so we
|
||||
// can accept it later (manually)
|
||||
/* tslint:disable:no-null-keyword */
|
||||
if (actual !== null) {
|
||||
/* tslint:enable:no-null-keyword */
|
||||
IO.writeFile(actualFileName, actual);
|
||||
}
|
||||
|
||||
return actual;
|
||||
}
|
||||
|
||||
function compareToBaseline(actual: string, relativeFileName: string, opts: BaselineOptions) {
|
||||
// actual is now either undefined (the generator had an error), null (no file requested),
|
||||
// or some real output of the function
|
||||
if (actual === undefined) {
|
||||
// Nothing to do
|
||||
return;
|
||||
}
|
||||
|
||||
const refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
|
||||
|
||||
/* tslint:disable:no-null-keyword */
|
||||
if (actual === null) {
|
||||
/* tslint:enable:no-null-keyword */
|
||||
actual = "<no content>";
|
||||
}
|
||||
|
||||
let expected = "<no content>";
|
||||
if (IO.fileExists(refFileName)) {
|
||||
expected = IO.readFile(refFileName);
|
||||
}
|
||||
|
||||
return { expected, actual };
|
||||
}
|
||||
|
||||
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
|
||||
const encoded_actual = Utils.encodeString(actual);
|
||||
if (expected != encoded_actual) {
|
||||
// Overwrite & issue error
|
||||
const errMsg = "The baseline file " + relativeFileName + " has changed.";
|
||||
throw new Error(errMsg);
|
||||
if (expected !== encoded_actual) {
|
||||
if (actual === NoContent) {
|
||||
IO.writeFile(actualFileName + ".delete", "");
|
||||
}
|
||||
else {
|
||||
IO.writeFile(actualFileName, actual);
|
||||
}
|
||||
throw new Error(`The baseline file ${relativeFileName} has changed.`);
|
||||
}
|
||||
}
|
||||
|
||||
export function runBaseline(
|
||||
descriptionForDescribe: string,
|
||||
relativeFileName: string,
|
||||
generateContent: () => string,
|
||||
runImmediately = false,
|
||||
opts?: BaselineOptions): void {
|
||||
|
||||
let actual = <string>undefined;
|
||||
export function runBaseline(relativeFileName: string, generateContent: () => string, opts?: BaselineOptions): void {
|
||||
const actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
|
||||
|
||||
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);
|
||||
|
||||
const comparison = compareToBaseline(actual, relativeFileName, opts);
|
||||
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
|
||||
}
|
||||
const actual = generateActual(generateContent);
|
||||
const comparison = compareToBaseline(actual, relativeFileName, opts);
|
||||
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ namespace Harness.LanguageService {
|
||||
}
|
||||
|
||||
export class LanguageServiceAdapterHost {
|
||||
protected fileNameToScript: ts.Map<ScriptInfo> = {};
|
||||
protected virtualFileSystem: Utils.VirtualFileSystem = new Utils.VirtualFileSystem(virtualFileSystemRoot, /*useCaseSensitiveFilenames*/false);
|
||||
|
||||
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
|
||||
protected settings = ts.getDefaultCompilerOptions()) {
|
||||
@@ -135,22 +135,24 @@ namespace Harness.LanguageService {
|
||||
|
||||
public getFilenames(): string[] {
|
||||
const fileNames: string[] = [];
|
||||
ts.forEachValue(this.fileNameToScript, (scriptInfo) => {
|
||||
for (const virtualEntry of this.virtualFileSystem.getAllFileEntries()){
|
||||
const scriptInfo = virtualEntry.content;
|
||||
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;
|
||||
}
|
||||
|
||||
public getScriptInfo(fileName: string): ScriptInfo {
|
||||
return ts.lookUp(this.fileNameToScript, fileName);
|
||||
const fileEntry = this.virtualFileSystem.traversePath(fileName);
|
||||
return fileEntry && fileEntry.isFile() ? (<Utils.VirtualFile>fileEntry).content : undefined;
|
||||
}
|
||||
|
||||
public addScript(fileName: string, content: string, isRootFile: boolean): void {
|
||||
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content, isRootFile);
|
||||
this.virtualFileSystem.addFile(fileName, new ScriptInfo(fileName, content, isRootFile));
|
||||
}
|
||||
|
||||
public editScript(fileName: string, start: number, end: number, newText: string) {
|
||||
@@ -171,7 +173,7 @@ namespace Harness.LanguageService {
|
||||
* @param col 0 based index
|
||||
*/
|
||||
public positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter {
|
||||
const script: ScriptInfo = this.fileNameToScript[fileName];
|
||||
const script: ScriptInfo = this.getScriptInfo(fileName);
|
||||
assert.isOk(script);
|
||||
|
||||
return ts.computeLineAndCharacterOfPosition(script.getLineMap(), position);
|
||||
@@ -182,8 +184,14 @@ namespace Harness.LanguageService {
|
||||
class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost {
|
||||
getCompilationSettings() { return this.settings; }
|
||||
getCancellationToken() { return this.cancellationToken; }
|
||||
getDirectories(path: string): string[] { return []; }
|
||||
getCurrentDirectory(): string { return ""; }
|
||||
getDirectories(path: string): string[] {
|
||||
const dir = this.virtualFileSystem.traversePath(path);
|
||||
if (dir && dir.isDirectory()) {
|
||||
return ts.map((<Utils.VirtualDirectory>dir).getDirectories(), (d) => ts.combinePaths(path, d.name));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
getCurrentDirectory(): string { return virtualFileSystemRoot; }
|
||||
getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; }
|
||||
getScriptFileNames(): string[] { return this.getFilenames(); }
|
||||
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
|
||||
@@ -196,6 +204,22 @@ namespace Harness.LanguageService {
|
||||
return script ? script.version.toString() : undefined;
|
||||
}
|
||||
|
||||
fileExists(fileName: string): boolean {
|
||||
const script = this.getScriptSnapshot(fileName);
|
||||
return script !== undefined;
|
||||
}
|
||||
readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[] {
|
||||
return ts.matchFiles(path, extensions, exclude, include,
|
||||
/*useCaseSensitiveFileNames*/false,
|
||||
this.getCurrentDirectory(),
|
||||
(p) => this.virtualFileSystem.getAccessibleFileSystemEntries(p));
|
||||
}
|
||||
readFile(path: string, encoding?: string): string {
|
||||
const snapshot = this.getScriptSnapshot(path);
|
||||
return snapshot.getText(0, snapshot.getLength());
|
||||
}
|
||||
|
||||
|
||||
log(s: string): void { }
|
||||
trace(s: string): void { }
|
||||
error(s: string): void { }
|
||||
@@ -235,7 +259,7 @@ namespace Harness.LanguageService {
|
||||
this.getModuleResolutionsForFile = (fileName) => {
|
||||
const scriptInfo = this.getScriptInfo(fileName);
|
||||
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ true);
|
||||
const imports: ts.Map<string> = {};
|
||||
const imports = ts.createMap<string>();
|
||||
for (const module of preprocessInfo.importedFiles) {
|
||||
const resolutionInfo = ts.resolveModuleName(module.fileName, fileName, compilerOptions, moduleResolutionHost);
|
||||
if (resolutionInfo.resolvedModule) {
|
||||
@@ -248,7 +272,7 @@ namespace Harness.LanguageService {
|
||||
const scriptInfo = this.getScriptInfo(fileName);
|
||||
if (scriptInfo) {
|
||||
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false);
|
||||
const resolutions: ts.Map<ts.ResolvedTypeReferenceDirective> = {};
|
||||
const resolutions = ts.createMap<ts.ResolvedTypeReferenceDirective>();
|
||||
const settings = this.nativeHost.getCompilationSettings();
|
||||
for (const typeReferenceDirective of preprocessInfo.typeReferenceDirectives) {
|
||||
const resolutionInfo = ts.resolveTypeReferenceDirective(typeReferenceDirective.fileName, fileName, settings, moduleResolutionHost);
|
||||
@@ -384,6 +408,9 @@ namespace Harness.LanguageService {
|
||||
getCompletionEntryDetails(fileName: string, position: number, entryName: string): ts.CompletionEntryDetails {
|
||||
return unwrapJSONCallResult(this.shim.getCompletionEntryDetails(fileName, position, entryName));
|
||||
}
|
||||
getCompletionEntrySymbol(fileName: string, position: number, entryName: string): ts.Symbol {
|
||||
throw new Error("getCompletionEntrySymbol not implemented across the shim layer.");
|
||||
}
|
||||
getQuickInfoAtPosition(fileName: string, position: number): ts.QuickInfo {
|
||||
return unwrapJSONCallResult(this.shim.getQuickInfoAtPosition(fileName, position));
|
||||
}
|
||||
@@ -617,6 +644,10 @@ namespace Harness.LanguageService {
|
||||
return [];
|
||||
}
|
||||
|
||||
getEnvironmentVariable(name: string): string {
|
||||
return ts.sys.getEnvironmentVariable(name);
|
||||
}
|
||||
|
||||
readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]): string[] {
|
||||
throw new Error("Not implemented Yet.");
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ namespace Playback {
|
||||
memoize(path => findResultByFields(replayLog.pathsResolved, { path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + "/" + path : ts.normalizeSlashes(path))));
|
||||
|
||||
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
|
||||
path => {
|
||||
(path: string) => {
|
||||
const result = underlying.readFile(path);
|
||||
const logEntry = { path, codepage: 0, result: { contents: result, codepage: 0 } };
|
||||
recordLog.filesRead.push(logEntry);
|
||||
|
||||
@@ -253,18 +253,15 @@ class ProjectRunner extends RunnerBase {
|
||||
moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
|
||||
};
|
||||
// Set the values specified using json
|
||||
const optionNameMap: ts.Map<ts.CommandLineOption> = {};
|
||||
ts.forEach(ts.optionDeclarations, option => {
|
||||
optionNameMap[option.name] = option;
|
||||
});
|
||||
const optionNameMap = ts.arrayToMap(ts.optionDeclarations, option => option.name);
|
||||
for (const name in testCase) {
|
||||
if (name !== "mapRoot" && name !== "sourceRoot" && ts.hasProperty(optionNameMap, name)) {
|
||||
if (name !== "mapRoot" && name !== "sourceRoot" && name in optionNameMap) {
|
||||
const option = optionNameMap[name];
|
||||
const optType = option.type;
|
||||
let value = <any>testCase[name];
|
||||
if (typeof optType !== "string") {
|
||||
const key = value.toLowerCase();
|
||||
if (ts.hasProperty(optType, key)) {
|
||||
if (key in optType) {
|
||||
value = optType[key];
|
||||
}
|
||||
}
|
||||
@@ -462,7 +459,7 @@ class ProjectRunner extends RunnerBase {
|
||||
});
|
||||
|
||||
it("Resolution information of (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
|
||||
Harness.Baseline.runBaseline("Resolution information of (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".json", () => {
|
||||
Harness.Baseline.runBaseline(getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".json", () => {
|
||||
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
|
||||
});
|
||||
});
|
||||
@@ -470,13 +467,12 @@ class ProjectRunner extends RunnerBase {
|
||||
|
||||
it("Errors for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
|
||||
if (compilerResult.errors.length) {
|
||||
Harness.Baseline.runBaseline("Errors for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".errors.txt", () => {
|
||||
Harness.Baseline.runBaseline(getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".errors.txt", () => {
|
||||
return getErrorsBaseline(compilerResult);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
|
||||
if (testCase.baselineCheck) {
|
||||
const errs: Error[] = [];
|
||||
@@ -484,7 +480,7 @@ class ProjectRunner extends RunnerBase {
|
||||
// There may be multiple files with different baselines. Run all and report at the end, else
|
||||
// it stops copying the remaining emitted files from 'local/projectOutput' to 'local/project'.
|
||||
try {
|
||||
Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
|
||||
Harness.Baseline.runBaseline(getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
|
||||
try {
|
||||
return Harness.IO.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
|
||||
}
|
||||
@@ -503,23 +499,21 @@ class ProjectRunner extends RunnerBase {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
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)));
|
||||
});
|
||||
}
|
||||
});
|
||||
// it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
|
||||
// if (compilerResult.sourceMapData) {
|
||||
// Harness.Baseline.runBaseline(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
|
||||
|
||||
it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
|
||||
if (!compilerResult.errors.length && testCase.declaration) {
|
||||
const dTsCompileResult = compileCompileDTsFiles(compilerResult);
|
||||
if (dTsCompileResult && dTsCompileResult.errors.length) {
|
||||
Harness.Baseline.runBaseline("Errors in generated Dts files for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
|
||||
Harness.Baseline.runBaseline(getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
|
||||
return getErrorsBaseline(dTsCompileResult);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ interface TestConfig {
|
||||
light?: boolean;
|
||||
taskConfigsFolder?: string;
|
||||
workerCount?: number;
|
||||
stackTraceLimit?: number | "full";
|
||||
tasks?: TaskSet[];
|
||||
test?: string[];
|
||||
runUnitTests?: boolean;
|
||||
@@ -116,6 +117,13 @@ if (testConfigContent !== "") {
|
||||
}
|
||||
}
|
||||
|
||||
if (testConfig.stackTraceLimit === "full") {
|
||||
(<any>Error).stackTraceLimit = Infinity;
|
||||
}
|
||||
else if ((+testConfig.stackTraceLimit | 0) > 0) {
|
||||
(<any>Error).stackTraceLimit = testConfig.stackTraceLimit;
|
||||
}
|
||||
|
||||
if (testConfig.test && testConfig.test.length > 0) {
|
||||
for (const option of testConfig.test) {
|
||||
if (!option) {
|
||||
|
||||
+21
-14
@@ -158,55 +158,56 @@ namespace RWC {
|
||||
|
||||
|
||||
it("has the expected emitted code", () => {
|
||||
Harness.Baseline.runBaseline("has the expected emitted code", baseName + ".output.js", () => {
|
||||
Harness.Baseline.runBaseline(`${baseName}.output.js`, () => {
|
||||
return Harness.Compiler.collateOutputs(compilerResult.files);
|
||||
}, false, baselineOpts);
|
||||
}, baselineOpts);
|
||||
});
|
||||
|
||||
it("has the expected declaration file content", () => {
|
||||
Harness.Baseline.runBaseline("has the expected declaration file content", baseName + ".d.ts", () => {
|
||||
Harness.Baseline.runBaseline(`${baseName}.d.ts`, () => {
|
||||
if (!compilerResult.declFilesCode.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Harness.Compiler.collateOutputs(compilerResult.declFilesCode);
|
||||
}, false, baselineOpts);
|
||||
}, baselineOpts);
|
||||
});
|
||||
|
||||
it("has the expected source maps", () => {
|
||||
Harness.Baseline.runBaseline("has the expected source maps", baseName + ".map", () => {
|
||||
Harness.Baseline.runBaseline(`${baseName}.map`, () => {
|
||||
if (!compilerResult.sourceMaps.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Harness.Compiler.collateOutputs(compilerResult.sourceMaps);
|
||||
}, false, baselineOpts);
|
||||
}, baselineOpts);
|
||||
});
|
||||
|
||||
/*it("has correct source map record", () => {
|
||||
if (compilerOptions.sourceMap) {
|
||||
Harness.Baseline.runBaseline("has correct source map record", baseName + ".sourcemap.txt", () => {
|
||||
Harness.Baseline.runBaseline(baseName + ".sourcemap.txt", () => {
|
||||
return compilerResult.getSourceMapRecord();
|
||||
}, false, baselineOpts);
|
||||
}, baselineOpts);
|
||||
}
|
||||
});*/
|
||||
|
||||
it("has the expected errors", () => {
|
||||
Harness.Baseline.runBaseline("has the expected errors", baseName + ".errors.txt", () => {
|
||||
Harness.Baseline.runBaseline(`${baseName}.errors.txt`, () => {
|
||||
if (compilerResult.errors.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// 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);
|
||||
const errors = compilerResult.errors.filter(e => !Harness.isDefaultLibraryFile(e.file.fileName));
|
||||
return Harness.Compiler.getErrorBaseline(baselineFiles, errors);
|
||||
}, baselineOpts);
|
||||
});
|
||||
|
||||
// Ideally, a generated declaration file will have no errors. But we allow generated
|
||||
// declaration file errors as part of the baseline.
|
||||
it("has the expected errors in generated declaration files", () => {
|
||||
if (compilerOptions.declaration && !compilerResult.errors.length) {
|
||||
Harness.Baseline.runBaseline("has the expected errors in generated declaration files", baseName + ".dts.errors.txt", () => {
|
||||
Harness.Baseline.runBaseline(`${baseName}.dts.errors.txt`, () => {
|
||||
const declFileCompilationResult = Harness.Compiler.compileDeclarationFiles(
|
||||
inputFiles, otherFiles, compilerResult, /*harnessSettings*/ undefined, compilerOptions, currentDirectory);
|
||||
|
||||
@@ -217,11 +218,17 @@ namespace RWC {
|
||||
return Harness.Compiler.minimalDiagnosticsToString(declFileCompilationResult.declResult.errors) +
|
||||
Harness.IO.newLine() + Harness.IO.newLine() +
|
||||
Harness.Compiler.getErrorBaseline(declFileCompilationResult.declInputFiles.concat(declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.errors);
|
||||
}, false, baselineOpts);
|
||||
}, baselineOpts);
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: Type baselines (need to refactor out from compilerRunner)
|
||||
it("has the expected types", () => {
|
||||
// We don't need to pass the extension here because "doTypeAndSymbolBaseline" will append appropriate extension of ".types" or ".symbols"
|
||||
Harness.Compiler.doTypeAndSymbolBaseline(baseName, compilerResult, inputFiles
|
||||
.concat(otherFiles)
|
||||
.filter(file => !!compilerResult.program.getSourceFile(file.unitName))
|
||||
.filter(e => !Harness.isDefaultLibraryFile(e.unitName)), baselineOpts);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,21 +67,21 @@ class Test262BaselineRunner extends RunnerBase {
|
||||
});
|
||||
|
||||
it("has the expected emitted code", () => {
|
||||
Harness.Baseline.runBaseline("has the expected emitted code", testState.filename + ".output.js", () => {
|
||||
Harness.Baseline.runBaseline(testState.filename + ".output.js", () => {
|
||||
const files = testState.compilerResult.files.filter(f => f.fileName !== Test262BaselineRunner.helpersFilePath);
|
||||
return Harness.Compiler.collateOutputs(files);
|
||||
}, false, Test262BaselineRunner.baselineOptions);
|
||||
}, Test262BaselineRunner.baselineOptions);
|
||||
});
|
||||
|
||||
it("has the expected errors", () => {
|
||||
Harness.Baseline.runBaseline("has the expected errors", testState.filename + ".errors.txt", () => {
|
||||
Harness.Baseline.runBaseline(testState.filename + ".errors.txt", () => {
|
||||
const errors = testState.compilerResult.errors;
|
||||
if (errors.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Harness.Compiler.getErrorBaseline(testState.inputFiles, errors);
|
||||
}, false, Test262BaselineRunner.baselineOptions);
|
||||
}, Test262BaselineRunner.baselineOptions);
|
||||
});
|
||||
|
||||
it("satisfies invariants", () => {
|
||||
@@ -90,10 +90,10 @@ class Test262BaselineRunner extends RunnerBase {
|
||||
});
|
||||
|
||||
it("has the expected AST", () => {
|
||||
Harness.Baseline.runBaseline("has the expected AST", testState.filename + ".AST.txt", () => {
|
||||
Harness.Baseline.runBaseline(testState.filename + ".AST.txt", () => {
|
||||
const sourceFile = testState.compilerResult.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
|
||||
return Utils.sourceFileToJSON(sourceFile);
|
||||
}, false, Test262BaselineRunner.baselineOptions);
|
||||
}, Test262BaselineRunner.baselineOptions);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -89,6 +89,7 @@
|
||||
"./unittests/convertCompilerOptionsFromJson.ts",
|
||||
"./unittests/convertTypingOptionsFromJson.ts",
|
||||
"./unittests/tsserverProjectSystem.ts",
|
||||
"./unittests/matchFiles.ts"
|
||||
"./unittests/matchFiles.ts",
|
||||
"./unittests/initializeTSConfig.ts"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ class TypeWriterWalker {
|
||||
}
|
||||
|
||||
private visitNode(node: ts.Node): void {
|
||||
if (ts.isExpression(node) || node.kind === ts.SyntaxKind.Identifier) {
|
||||
if (ts.isPartOfExpression(node) || node.kind === ts.SyntaxKind.Identifier) {
|
||||
this.logTypeAndSymbol(node);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,16 +7,16 @@ namespace ts {
|
||||
}
|
||||
|
||||
function createDefaultServerHost(fileMap: Map<File>): server.ServerHost {
|
||||
const existingDirectories: Map<boolean> = {};
|
||||
forEachValue(fileMap, v => {
|
||||
let dir = getDirectoryPath(v.name);
|
||||
const existingDirectories = createMap<boolean>();
|
||||
for (const name in fileMap) {
|
||||
let dir = getDirectoryPath(name);
|
||||
let previous: string;
|
||||
do {
|
||||
existingDirectories[dir] = true;
|
||||
previous = dir;
|
||||
dir = getDirectoryPath(dir);
|
||||
} while (dir !== previous);
|
||||
});
|
||||
}
|
||||
return {
|
||||
args: <string[]>[],
|
||||
newLine: "\r\n",
|
||||
@@ -24,7 +24,7 @@ namespace ts {
|
||||
write: (s: string) => {
|
||||
},
|
||||
readFile: (path: string, encoding?: string): string => {
|
||||
return hasProperty(fileMap, path) && fileMap[path].content;
|
||||
return path in fileMap ? fileMap[path].content : undefined;
|
||||
},
|
||||
writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => {
|
||||
throw new Error("NYI");
|
||||
@@ -33,10 +33,10 @@ namespace ts {
|
||||
throw new Error("NYI");
|
||||
},
|
||||
fileExists: (path: string): boolean => {
|
||||
return hasProperty(fileMap, path);
|
||||
return path in fileMap;
|
||||
},
|
||||
directoryExists: (path: string): boolean => {
|
||||
return hasProperty(existingDirectories, path);
|
||||
return existingDirectories[path] || false;
|
||||
},
|
||||
createDirectory: (path: string) => {
|
||||
},
|
||||
@@ -47,6 +47,7 @@ namespace ts {
|
||||
return "";
|
||||
},
|
||||
getDirectories: (path: string) => [],
|
||||
getEnvironmentVariable: (name: string) => "",
|
||||
readDirectory: (path: string, extension?: string[], exclude?: string[], include?: string[]): string[] => {
|
||||
throw new Error("NYI");
|
||||
},
|
||||
@@ -101,7 +102,7 @@ namespace ts {
|
||||
content: `foo()`
|
||||
};
|
||||
|
||||
const serverHost = createDefaultServerHost({ [root.name]: root, [imported.name]: imported });
|
||||
const serverHost = createDefaultServerHost(createMap({ [root.name]: root, [imported.name]: imported }));
|
||||
const { project, rootScriptInfo } = createProject(root.name, serverHost);
|
||||
|
||||
// ensure that imported file was found
|
||||
@@ -193,7 +194,7 @@ namespace ts {
|
||||
content: `export var y = 1`
|
||||
};
|
||||
|
||||
const fileMap: Map<File> = { [root.name]: root };
|
||||
const fileMap = createMap({ [root.name]: root });
|
||||
const serverHost = createDefaultServerHost(fileMap);
|
||||
const originalFileExists = serverHost.fileExists;
|
||||
|
||||
|
||||
@@ -403,6 +403,7 @@ namespace ts {
|
||||
{
|
||||
compilerOptions: <CompilerOptions>{
|
||||
allowJs: true,
|
||||
maxNodeModuleJsDepth: 2,
|
||||
module: ModuleKind.CommonJS,
|
||||
target: ScriptTarget.ES5,
|
||||
noImplicitAny: false,
|
||||
@@ -429,6 +430,7 @@ namespace ts {
|
||||
{
|
||||
compilerOptions: <CompilerOptions>{
|
||||
allowJs: false,
|
||||
maxNodeModuleJsDepth: 2,
|
||||
module: ModuleKind.CommonJS,
|
||||
target: ScriptTarget.ES5,
|
||||
noImplicitAny: false,
|
||||
@@ -450,7 +452,8 @@ namespace ts {
|
||||
{
|
||||
compilerOptions:
|
||||
{
|
||||
allowJs: true
|
||||
allowJs: true,
|
||||
maxNodeModuleJsDepth: 2
|
||||
},
|
||||
errors: [{
|
||||
file: undefined,
|
||||
@@ -469,7 +472,8 @@ namespace ts {
|
||||
{
|
||||
compilerOptions:
|
||||
{
|
||||
allowJs: true
|
||||
allowJs: true,
|
||||
maxNodeModuleJsDepth: 2
|
||||
},
|
||||
errors: <Diagnostic[]>[]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/// <reference path="..\harness.ts" />
|
||||
/// <reference path="..\..\compiler\commandLineParser.ts" />
|
||||
|
||||
namespace ts {
|
||||
describe("initTSConfig", () => {
|
||||
function initTSConfigCorrectly(name: string, commandLinesArgs: string[]) {
|
||||
describe(name, () => {
|
||||
const commandLine = parseCommandLine(commandLinesArgs);
|
||||
const initResult = generateTSConfig(commandLine.options, commandLine.fileNames);
|
||||
const outputFileName = `tsConfig/${name.replace(/[^a-z0-9\-. ]/ig, "")}/tsconfig.json`;
|
||||
|
||||
it(`Correct output for ${outputFileName}`, () => {
|
||||
Harness.Baseline.runBaseline(outputFileName, () => {
|
||||
if (initResult) {
|
||||
return JSON.stringify(initResult, undefined, 4);
|
||||
}
|
||||
else {
|
||||
// This can happen if compiler recieve invalid compiler-options
|
||||
/* tslint:disable:no-null-keyword */
|
||||
return null;
|
||||
/* tslint:enable:no-null-keyword */
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
initTSConfigCorrectly("Default initialized TSConfig", ["--init"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with files options", ["--init", "file0.st", "file1.ts", "file2.ts"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with boolean value compiler options", ["--init", "--noUnusedLocals"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with enum value compiler options", ["--init", "--target", "es5", "--jsx", "react"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with list compiler options", ["--init", "--types", "jquery,mocha"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with list compiler options with enum value", ["--init", "--lib", "es5,es2015.core"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with incorrect compiler option", ["--init", "--someNonExistOption"]);
|
||||
|
||||
initTSConfigCorrectly("Initialized TSConfig with incorrect compiler option value", ["--init", "--lib", "nonExistLib,es5,es2015.promise"]);
|
||||
});
|
||||
}
|
||||
+193
-2283
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,8 @@ namespace ts {
|
||||
"c:/dev/x/y/b.ts",
|
||||
"c:/dev/js/a.js",
|
||||
"c:/dev/js/b.js",
|
||||
"c:/dev/js/d.min.js",
|
||||
"c:/dev/js/ab.min.js",
|
||||
"c:/ext/ext.ts",
|
||||
"c:/ext/b/a..b.ts"
|
||||
]);
|
||||
@@ -75,6 +77,17 @@ namespace ts {
|
||||
"c:/dev/jspm_packages/a.ts"
|
||||
]);
|
||||
|
||||
const caseInsensitiveDottedFoldersHost = new Utils.MockParseConfigHost(caseInsensitiveBasePath, /*useCaseSensitiveFileNames*/ false, [
|
||||
"c:/dev/x/d.ts",
|
||||
"c:/dev/x/y/d.ts",
|
||||
"c:/dev/x/y/.e.ts",
|
||||
"c:/dev/x/.y/a.ts",
|
||||
"c:/dev/.z/.b.ts",
|
||||
"c:/dev/.z/c.ts",
|
||||
"c:/dev/w/.u/e.ts",
|
||||
"c:/dev/g.min.js/.g/g.ts"
|
||||
]);
|
||||
|
||||
describe("matchFiles", () => {
|
||||
describe("with literal file list", () => {
|
||||
it("without exclusions", () => {
|
||||
@@ -726,6 +739,33 @@ namespace ts {
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
it("include explicitly listed .min.js files when allowJs=true", () => {
|
||||
const json = {
|
||||
compilerOptions: {
|
||||
allowJs: true
|
||||
},
|
||||
include: [
|
||||
"js/*.min.js"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {
|
||||
allowJs: true
|
||||
},
|
||||
errors: [],
|
||||
fileNames: [
|
||||
"c:/dev/js/ab.min.js",
|
||||
"c:/dev/js/d.min.js"
|
||||
],
|
||||
wildcardDirectories: {
|
||||
"c:/dev/js": ts.WatchDirectoryFlags.None
|
||||
}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
it("include paths outside of the project", () => {
|
||||
const json = {
|
||||
include: [
|
||||
@@ -951,6 +991,35 @@ namespace ts {
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
it("exclude .min.js files using wildcards", () => {
|
||||
const json = {
|
||||
compilerOptions: {
|
||||
allowJs: true
|
||||
},
|
||||
include: [
|
||||
"js/*.min.js"
|
||||
],
|
||||
exclude: [
|
||||
"js/a*"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {
|
||||
allowJs: true
|
||||
},
|
||||
errors: [],
|
||||
fileNames: [
|
||||
"c:/dev/js/d.min.js"
|
||||
],
|
||||
wildcardDirectories: {
|
||||
"c:/dev/js": ts.WatchDirectoryFlags.None
|
||||
}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
describe("with trailing recursive directory", () => {
|
||||
it("in includes", () => {
|
||||
const json = {
|
||||
@@ -1145,5 +1214,122 @@ namespace ts {
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("with files or folders that begin with a .", () => {
|
||||
it("that are not explicitly included", () => {
|
||||
const json = {
|
||||
include: [
|
||||
"x/**/*",
|
||||
"w/*/*"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {},
|
||||
errors: [],
|
||||
fileNames: [
|
||||
"c:/dev/x/d.ts",
|
||||
"c:/dev/x/y/d.ts",
|
||||
],
|
||||
wildcardDirectories: {
|
||||
"c:/dev/x": ts.WatchDirectoryFlags.Recursive,
|
||||
"c:/dev/w": ts.WatchDirectoryFlags.Recursive
|
||||
}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
describe("that are explicitly included", () => {
|
||||
it("without wildcards", () => {
|
||||
const json = {
|
||||
include: [
|
||||
"x/.y/a.ts",
|
||||
"c:/dev/.z/.b.ts"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {},
|
||||
errors: [],
|
||||
fileNames: [
|
||||
"c:/dev/.z/.b.ts",
|
||||
"c:/dev/x/.y/a.ts"
|
||||
],
|
||||
wildcardDirectories: {}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
it("with recursive wildcards that match directories", () => {
|
||||
const json = {
|
||||
include: [
|
||||
"**/.*/*"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {},
|
||||
errors: [],
|
||||
fileNames: [
|
||||
"c:/dev/.z/c.ts",
|
||||
"c:/dev/g.min.js/.g/g.ts",
|
||||
"c:/dev/w/.u/e.ts",
|
||||
"c:/dev/x/.y/a.ts"
|
||||
],
|
||||
wildcardDirectories: {
|
||||
"c:/dev": ts.WatchDirectoryFlags.Recursive
|
||||
}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
it("with recursive wildcards that match nothing", () => {
|
||||
const json = {
|
||||
include: [
|
||||
"x/**/.y/*",
|
||||
".z/**/.*"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {},
|
||||
errors: [],
|
||||
fileNames: [
|
||||
"c:/dev/.z/.b.ts",
|
||||
"c:/dev/x/.y/a.ts"
|
||||
],
|
||||
wildcardDirectories: {
|
||||
"c:/dev/.z": ts.WatchDirectoryFlags.Recursive,
|
||||
"c:/dev/x": ts.WatchDirectoryFlags.Recursive
|
||||
}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
it("with wildcard excludes that implicitly exclude dotted files", () => {
|
||||
const json = {
|
||||
include: [
|
||||
"**/.*/*"
|
||||
],
|
||||
exclude: [
|
||||
"**/*"
|
||||
]
|
||||
};
|
||||
const expected: ts.ParsedCommandLine = {
|
||||
options: {},
|
||||
errors: [],
|
||||
fileNames: [],
|
||||
wildcardDirectories: {}
|
||||
};
|
||||
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
|
||||
assert.deepEqual(actual.fileNames, expected.fileNames);
|
||||
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
|
||||
assert.deepEqual(actual.errors, expected.errors);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,21 +1,6 @@
|
||||
/// <reference path="..\harness.ts" />
|
||||
|
||||
namespace ts {
|
||||
function diagnosticToString(diagnostic: Diagnostic) {
|
||||
let output = "";
|
||||
|
||||
if (diagnostic.file) {
|
||||
const loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
|
||||
|
||||
output += `${diagnostic.file.fileName}(${loc.line + 1},${loc.character + 1}): `;
|
||||
}
|
||||
|
||||
const category = DiagnosticCategory[diagnostic.category].toLowerCase();
|
||||
output += `${category} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine)}${sys.newLine}`;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
interface File {
|
||||
name: string;
|
||||
content?: string;
|
||||
@@ -25,7 +10,7 @@ namespace ts {
|
||||
const map = arrayToMap(files, f => f.name);
|
||||
|
||||
if (hasDirectoryExists) {
|
||||
const directories: Map<string> = {};
|
||||
const directories = createMap<string>();
|
||||
for (const f of files) {
|
||||
let name = getDirectoryPath(f.name);
|
||||
while (true) {
|
||||
@@ -40,19 +25,19 @@ namespace ts {
|
||||
return {
|
||||
readFile,
|
||||
directoryExists: path => {
|
||||
return hasProperty(directories, path);
|
||||
return path in directories;
|
||||
},
|
||||
fileExists: path => {
|
||||
assert.isTrue(hasProperty(directories, getDirectoryPath(path)), `'fileExists' '${path}' request in non-existing directory`);
|
||||
return hasProperty(map, path);
|
||||
assert.isTrue(getDirectoryPath(path) in directories, `'fileExists' '${path}' request in non-existing directory`);
|
||||
return path in map;
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
return { readFile, fileExists: path => hasProperty(map, path), };
|
||||
return { readFile, fileExists: path => path in map, };
|
||||
}
|
||||
function readFile(path: string): string {
|
||||
return hasProperty(map, path) ? map[path].content : undefined;
|
||||
return path in map ? map[path].content : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,7 +287,7 @@ namespace ts {
|
||||
const host: CompilerHost = {
|
||||
getSourceFile: (fileName: string, languageVersion: ScriptTarget) => {
|
||||
const path = normalizePath(combinePaths(currentDirectory, fileName));
|
||||
return hasProperty(files, path) ? createSourceFile(fileName, files[path], languageVersion) : undefined;
|
||||
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
|
||||
},
|
||||
getDefaultLibFileName: () => "lib.d.ts",
|
||||
writeFile: (fileName, content): void => { throw new Error("NotImplemented"); },
|
||||
@@ -313,7 +298,7 @@ namespace ts {
|
||||
useCaseSensitiveFileNames: () => false,
|
||||
fileExists: fileName => {
|
||||
const path = normalizePath(combinePaths(currentDirectory, fileName));
|
||||
return hasProperty(files, path);
|
||||
return path in files;
|
||||
},
|
||||
readFile: (fileName): string => { throw new Error("NotImplemented"); }
|
||||
};
|
||||
@@ -322,9 +307,9 @@ namespace ts {
|
||||
|
||||
assert.equal(program.getSourceFiles().length, expectedFilesCount);
|
||||
const syntacticDiagnostics = program.getSyntacticDiagnostics();
|
||||
assert.equal(syntacticDiagnostics.length, 0, `expect no syntactic diagnostics, got: ${JSON.stringify(syntacticDiagnostics.map(diagnosticToString))}`);
|
||||
assert.equal(syntacticDiagnostics.length, 0, `expect no syntactic diagnostics, got: ${JSON.stringify(Harness.Compiler.minimalDiagnosticsToString(syntacticDiagnostics))}`);
|
||||
const semanticDiagnostics = program.getSemanticDiagnostics();
|
||||
assert.equal(semanticDiagnostics.length, 0, `expect no semantic diagnostics, got: ${JSON.stringify(semanticDiagnostics.map(diagnosticToString))}`);
|
||||
assert.equal(semanticDiagnostics.length, 0, `expect no semantic diagnostics, got: ${JSON.stringify(Harness.Compiler.minimalDiagnosticsToString(semanticDiagnostics))}`);
|
||||
|
||||
// try to get file using a relative name
|
||||
for (const relativeFileName of relativeNamesToCheck) {
|
||||
@@ -333,7 +318,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
it("should find all modules", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/b/c/first/shared.ts": `
|
||||
class A {}
|
||||
export = A`,
|
||||
@@ -347,23 +332,23 @@ import Shared = require('../first/shared');
|
||||
class C {}
|
||||
export = C;
|
||||
`
|
||||
};
|
||||
});
|
||||
test(files, "/a/b/c/first/second", ["class_a.ts"], 3, ["../../../c/third/class_c.ts"]);
|
||||
});
|
||||
|
||||
it("should find modules in node_modules", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/parent/node_modules/mod/index.d.ts": "export var x",
|
||||
"/parent/app/myapp.ts": `import {x} from "mod"`
|
||||
};
|
||||
});
|
||||
test(files, "/parent/app", ["myapp.ts"], 2, []);
|
||||
});
|
||||
|
||||
it("should find file referenced via absolute and relative names", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/b/c.ts": `/// <reference path="b.ts"/>`,
|
||||
"/a/b/b.ts": "var x"
|
||||
};
|
||||
});
|
||||
test(files, "/a/b", ["c.ts", "/a/b/b.ts"], 2, []);
|
||||
});
|
||||
});
|
||||
@@ -373,11 +358,7 @@ export = C;
|
||||
function test(files: Map<string>, options: CompilerOptions, currentDirectory: string, useCaseSensitiveFileNames: boolean, rootFiles: string[], diagnosticCodes: number[]): void {
|
||||
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
|
||||
if (!useCaseSensitiveFileNames) {
|
||||
const f: Map<string> = {};
|
||||
for (const fileName in files) {
|
||||
f[getCanonicalFileName(fileName)] = files[fileName];
|
||||
}
|
||||
files = f;
|
||||
files = reduceProperties(files, (files, file, fileName) => (files[getCanonicalFileName(fileName)] = file, files), createMap<string>());
|
||||
}
|
||||
|
||||
const host: CompilerHost = {
|
||||
@@ -386,7 +367,7 @@ export = C;
|
||||
return library;
|
||||
}
|
||||
const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName)));
|
||||
return hasProperty(files, path) ? createSourceFile(fileName, files[path], languageVersion) : undefined;
|
||||
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
|
||||
},
|
||||
getDefaultLibFileName: () => "lib.d.ts",
|
||||
writeFile: (fileName, content): void => { throw new Error("NotImplemented"); },
|
||||
@@ -397,90 +378,90 @@ export = C;
|
||||
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
|
||||
fileExists: fileName => {
|
||||
const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName)));
|
||||
return hasProperty(files, path);
|
||||
return path in files;
|
||||
},
|
||||
readFile: (fileName): string => { throw new Error("NotImplemented"); }
|
||||
};
|
||||
const program = createProgram(rootFiles, options, host);
|
||||
const diagnostics = sortAndDeduplicateDiagnostics(program.getSemanticDiagnostics().concat(program.getOptionsDiagnostics()));
|
||||
assert.equal(diagnostics.length, diagnosticCodes.length, `Incorrect number of expected diagnostics, expected ${diagnosticCodes.length}, got '${map(diagnostics, diagnosticToString).join("\r\n")}'`);
|
||||
assert.equal(diagnostics.length, diagnosticCodes.length, `Incorrect number of expected diagnostics, expected ${diagnosticCodes.length}, got '${Harness.Compiler.minimalDiagnosticsToString(diagnostics)}'`);
|
||||
for (let i = 0; i < diagnosticCodes.length; i++) {
|
||||
assert.equal(diagnostics[i].code, diagnosticCodes[i], `Expected diagnostic code ${diagnosticCodes[i]}, got '${diagnostics[i].code}': '${diagnostics[i].messageText}'`);
|
||||
}
|
||||
}
|
||||
|
||||
it("should succeed when the same file is referenced using absolute and relative names", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/b/c.ts": `/// <reference path="d.ts"/>`,
|
||||
"/a/b/d.ts": "var x"
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "/a/b/d.ts"], []);
|
||||
});
|
||||
|
||||
it("should fail when two files used in program differ only in casing (tripleslash references)", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/b/c.ts": `/// <reference path="D.ts"/>`,
|
||||
"/a/b/d.ts": "var x"
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]);
|
||||
});
|
||||
|
||||
it("should fail when two files used in program differ only in casing (imports)", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/b/c.ts": `import {x} from "D"`,
|
||||
"/a/b/d.ts": "export var x"
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]);
|
||||
});
|
||||
|
||||
it("should fail when two files used in program differ only in casing (imports, relative module names)", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"moduleA.ts": `import {x} from "./ModuleB"`,
|
||||
"moduleB.ts": "export var x"
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts"], [1149]);
|
||||
});
|
||||
|
||||
it("should fail when two files exist on disk that differs only in casing", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/b/c.ts": `import {x} from "D"`,
|
||||
"/a/b/D.ts": "export var x",
|
||||
"/a/b/d.ts": "export var y"
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ true, ["c.ts", "d.ts"], [1149]);
|
||||
});
|
||||
|
||||
it("should fail when module name in 'require' calls has inconsistent casing", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"moduleA.ts": `import a = require("./ModuleC")`,
|
||||
"moduleB.ts": `import a = require("./moduleC")`,
|
||||
"moduleC.ts": "export var x"
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts", "moduleC.ts"], [1149, 1149]);
|
||||
});
|
||||
|
||||
it("should fail when module names in 'require' calls has inconsistent casing and current directory has uppercase chars", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/B/c/moduleA.ts": `import a = require("./ModuleC")`,
|
||||
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
|
||||
"/a/B/c/moduleC.ts": "export var x",
|
||||
"/a/B/c/moduleD.ts": `
|
||||
import a = require("./moduleA.ts");
|
||||
import b = require("./moduleB.ts");
|
||||
import a = require("./moduleA");
|
||||
import b = require("./moduleB");
|
||||
`
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]);
|
||||
});
|
||||
it("should not fail when module names in 'require' calls has consistent casing and current directory has uppercase chars", () => {
|
||||
const files: Map<string> = {
|
||||
const files = createMap({
|
||||
"/a/B/c/moduleA.ts": `import a = require("./moduleC")`,
|
||||
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
|
||||
"/a/B/c/moduleC.ts": "export var x",
|
||||
"/a/B/c/moduleD.ts": `
|
||||
import a = require("./moduleA.ts");
|
||||
import b = require("./moduleB.ts");
|
||||
import a = require("./moduleA");
|
||||
import b = require("./moduleB");
|
||||
`
|
||||
};
|
||||
});
|
||||
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []);
|
||||
});
|
||||
});
|
||||
@@ -1038,7 +1019,7 @@ import b = require("./moduleB.ts");
|
||||
const names = map(files, f => f.name);
|
||||
const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES6)), f => f.fileName);
|
||||
const compilerHost: CompilerHost = {
|
||||
fileExists : fileName => hasProperty(sourceFiles, fileName),
|
||||
fileExists : fileName => fileName in sourceFiles,
|
||||
getSourceFile: fileName => sourceFiles[fileName],
|
||||
getDefaultLibFileName: () => "lib.d.ts",
|
||||
writeFile(file, text) {
|
||||
@@ -1049,7 +1030,7 @@ import b = require("./moduleB.ts");
|
||||
getCanonicalFileName: f => f.toLowerCase(),
|
||||
getNewLine: () => "\r\n",
|
||||
useCaseSensitiveFileNames: () => false,
|
||||
readFile: fileName => hasProperty(sourceFiles, fileName) ? sourceFiles[fileName].text : undefined
|
||||
readFile: fileName => fileName in sourceFiles ? sourceFiles[fileName].text : undefined
|
||||
};
|
||||
const program1 = createProgram(names, {}, compilerHost);
|
||||
const diagnostics1 = program1.getFileProcessingDiagnostics().getDiagnostics();
|
||||
|
||||
@@ -95,13 +95,14 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function createSourceFileWithText(fileName: string, sourceText: SourceText, target: ScriptTarget) {
|
||||
const file = <SourceFileWithText>createSourceFile(fileName, sourceText.getFullText(), target);
|
||||
file.sourceText = sourceText;
|
||||
return file;
|
||||
}
|
||||
|
||||
function createTestCompilerHost(texts: NamedSourceText[], target: ScriptTarget): CompilerHost {
|
||||
const files: Map<SourceFileWithText> = {};
|
||||
for (const t of texts) {
|
||||
const file = <SourceFileWithText>createSourceFile(t.name, t.text.getFullText(), target);
|
||||
file.sourceText = t.text;
|
||||
files[t.name] = file;
|
||||
}
|
||||
const files = arrayToMap(texts, t => t.name, t => createSourceFileWithText(t.name, t.text, target));
|
||||
|
||||
return {
|
||||
getSourceFile(fileName): SourceFile {
|
||||
@@ -128,10 +129,9 @@ namespace ts {
|
||||
getNewLine(): string {
|
||||
return sys ? sys.newLine : newLine;
|
||||
},
|
||||
fileExists: fileName => hasProperty(files, fileName),
|
||||
fileExists: fileName => fileName in files,
|
||||
readFile: fileName => {
|
||||
const file = lookUp(files, fileName);
|
||||
return file && file.text;
|
||||
return fileName in files ? files[fileName].text : undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -152,29 +152,29 @@ namespace ts {
|
||||
return program;
|
||||
}
|
||||
|
||||
function getSizeOfMap(map: Map<any>): number {
|
||||
let size = 0;
|
||||
for (const id in map) {
|
||||
if (hasProperty(map, id)) {
|
||||
size++;
|
||||
function checkResolvedModule(expected: ResolvedModule, actual: ResolvedModule): boolean {
|
||||
if (!expected === !actual) {
|
||||
if (expected) {
|
||||
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
|
||||
assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return size;
|
||||
return false;
|
||||
}
|
||||
|
||||
function checkResolvedModule(expected: ResolvedModule, actual: ResolvedModule): void {
|
||||
assert.isTrue(actual !== undefined);
|
||||
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
|
||||
assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`);
|
||||
function checkResolvedTypeDirective(expected: ResolvedTypeReferenceDirective, actual: ResolvedTypeReferenceDirective): boolean {
|
||||
if (!expected === !actual) {
|
||||
if (expected) {
|
||||
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
|
||||
assert.isTrue(expected.primary === actual.primary, `'primary': expected '${expected.primary}' to be equal to '${actual.primary}'`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function checkResolvedTypeDirective(expected: ResolvedTypeReferenceDirective, actual: ResolvedTypeReferenceDirective): void {
|
||||
assert.isTrue(actual !== undefined);
|
||||
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
|
||||
assert.isTrue(expected.primary === actual.primary, `'primary': expected '${expected.primary}' to be equal to '${actual.primary}'`);
|
||||
}
|
||||
|
||||
function checkCache<T>(caption: string, program: Program, fileName: string, expectedContent: Map<T>, getCache: (f: SourceFile) => Map<T>, entryChecker: (expected: T, original: T) => void): void {
|
||||
function checkCache<T>(caption: string, program: Program, fileName: string, expectedContent: Map<T>, getCache: (f: SourceFile) => Map<T>, entryChecker: (expected: T, original: T) => boolean): void {
|
||||
const file = program.getSourceFile(fileName);
|
||||
assert.isTrue(file !== undefined, `cannot find file ${fileName}`);
|
||||
const cache = getCache(file);
|
||||
@@ -183,23 +183,7 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
assert.isTrue(cache !== undefined, `expected ${caption} to be set`);
|
||||
const actualCacheSize = getSizeOfMap(cache);
|
||||
const expectedSize = getSizeOfMap(expectedContent);
|
||||
assert.isTrue(actualCacheSize === expectedSize, `expected actual size: ${actualCacheSize} to be equal to ${expectedSize}`);
|
||||
|
||||
for (const id in expectedContent) {
|
||||
if (hasProperty(expectedContent, id)) {
|
||||
|
||||
if (expectedContent[id]) {
|
||||
const expected = expectedContent[id];
|
||||
const actual = cache[id];
|
||||
entryChecker(expected, actual);
|
||||
}
|
||||
}
|
||||
else {
|
||||
assert.isTrue(cache[id] === undefined);
|
||||
}
|
||||
}
|
||||
assert.isTrue(equalOwnProperties(expectedContent, cache, entryChecker), `contents of ${caption} did not match the expected contents.`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,6 +297,8 @@ namespace ts {
|
||||
});
|
||||
|
||||
it("resolution cache follows imports", () => {
|
||||
(<any>Error).stackTraceLimit = Infinity;
|
||||
|
||||
const files = [
|
||||
{ name: "a.ts", text: SourceText.New("", "import {_} from 'b'", "var x = 1") },
|
||||
{ name: "b.ts", text: SourceText.New("", "", "var y = 2") },
|
||||
@@ -320,7 +306,7 @@ namespace ts {
|
||||
const options: CompilerOptions = { target };
|
||||
|
||||
const program_1 = newProgram(files, ["a.ts"], options);
|
||||
checkResolvedModulesCache(program_1, "a.ts", { "b": { resolvedFileName: "b.ts" } });
|
||||
checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" } }));
|
||||
checkResolvedModulesCache(program_1, "b.ts", undefined);
|
||||
|
||||
const program_2 = updateProgram(program_1, ["a.ts"], options, files => {
|
||||
@@ -329,7 +315,7 @@ namespace ts {
|
||||
assert.isTrue(program_1.structureIsReused);
|
||||
|
||||
// content of resolution cache should not change
|
||||
checkResolvedModulesCache(program_1, "a.ts", { "b": { resolvedFileName: "b.ts" } });
|
||||
checkResolvedModulesCache(program_1, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" } }));
|
||||
checkResolvedModulesCache(program_1, "b.ts", undefined);
|
||||
|
||||
// imports has changed - program is not reused
|
||||
@@ -346,7 +332,7 @@ namespace ts {
|
||||
files[0].text = files[0].text.updateImportsAndExports(newImports);
|
||||
});
|
||||
assert.isTrue(!program_3.structureIsReused);
|
||||
checkResolvedModulesCache(program_4, "a.ts", { "b": { resolvedFileName: "b.ts" }, "c": undefined });
|
||||
checkResolvedModulesCache(program_4, "a.ts", createMap({ "b": { resolvedFileName: "b.ts" }, "c": undefined }));
|
||||
});
|
||||
|
||||
it("resolved type directives cache follows type directives", () => {
|
||||
@@ -357,7 +343,7 @@ namespace ts {
|
||||
const options: CompilerOptions = { target, typeRoots: ["/types"] };
|
||||
|
||||
const program_1 = newProgram(files, ["/a.ts"], options);
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", { "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } });
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", undefined);
|
||||
|
||||
const program_2 = updateProgram(program_1, ["/a.ts"], options, files => {
|
||||
@@ -366,7 +352,7 @@ namespace ts {
|
||||
assert.isTrue(program_1.structureIsReused);
|
||||
|
||||
// content of resolution cache should not change
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", { "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } });
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", undefined);
|
||||
|
||||
// type reference directives has changed - program is not reused
|
||||
@@ -384,7 +370,7 @@ namespace ts {
|
||||
files[0].text = files[0].text.updateReferences(newReferences);
|
||||
});
|
||||
assert.isTrue(!program_3.structureIsReused);
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", { "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } });
|
||||
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMap({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
class a {
|
||||
constructor ( n : number ) ;
|
||||
constructor ( s : string ) ;
|
||||
constructor ( ns : any ) {
|
||||
|
||||
}
|
||||
|
||||
public pgF ( ) { } ;
|
||||
|
||||
public pv ;
|
||||
public get d ( ) {
|
||||
return 30 ;
|
||||
}
|
||||
public set d ( ) {
|
||||
}
|
||||
|
||||
public static get p2 ( ) {
|
||||
return { x : 30 , y : 40 } ;
|
||||
}
|
||||
|
||||
private static d2 ( ) {
|
||||
}
|
||||
private static get p3 ( ) {
|
||||
return "string" ;
|
||||
}
|
||||
private pv3 ;
|
||||
|
||||
private foo ( n : number ) : string ;
|
||||
private foo ( s : string ) : string ;
|
||||
private foo ( ns : any ) {
|
||||
return ns.toString ( ) ;
|
||||
}
|
||||
}
|
||||
|
||||
class b extends a {
|
||||
}
|
||||
|
||||
class m1b {
|
||||
|
||||
}
|
||||
|
||||
interface m1ib {
|
||||
|
||||
}
|
||||
class c extends m1b {
|
||||
}
|
||||
|
||||
class ib2 implements m1ib {
|
||||
}
|
||||
|
||||
declare class aAmbient {
|
||||
constructor ( n : number ) ;
|
||||
constructor ( s : string ) ;
|
||||
public pgF ( ) : void ;
|
||||
public pv ;
|
||||
public d : number ;
|
||||
static p2 : { x : number ; y : number ; } ;
|
||||
static d2 ( ) ;
|
||||
static p3 ;
|
||||
private pv3 ;
|
||||
private foo ( s ) ;
|
||||
}
|
||||
|
||||
class d {
|
||||
private foo ( n : number ) : string ;
|
||||
private foo ( ns : any ) {
|
||||
return ns.toString ( ) ;
|
||||
}
|
||||
private foo ( s : string ) : string ;
|
||||
}
|
||||
|
||||
class e {
|
||||
private foo ( ns : any ) {
|
||||
return ns.toString ( ) ;
|
||||
}
|
||||
private foo ( s : string ) : string ;
|
||||
private foo ( n : number ) : string ;
|
||||
}
|
||||
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
class a {
|
||||
constructor(n: number);
|
||||
constructor(s: string);
|
||||
constructor(ns: any) {
|
||||
|
||||
}
|
||||
|
||||
public pgF() { };
|
||||
|
||||
public pv;
|
||||
public get d() {
|
||||
return 30;
|
||||
}
|
||||
public set d() {
|
||||
}
|
||||
|
||||
public static get p2() {
|
||||
return { x: 30, y: 40 };
|
||||
}
|
||||
|
||||
private static d2() {
|
||||
}
|
||||
private static get p3() {
|
||||
return "string";
|
||||
}
|
||||
private pv3;
|
||||
|
||||
private foo(n: number): string;
|
||||
private foo(s: string): string;
|
||||
private foo(ns: any) {
|
||||
return ns.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class b extends a {
|
||||
}
|
||||
|
||||
class m1b {
|
||||
|
||||
}
|
||||
|
||||
interface m1ib {
|
||||
|
||||
}
|
||||
class c extends m1b {
|
||||
}
|
||||
|
||||
class ib2 implements m1ib {
|
||||
}
|
||||
|
||||
declare class aAmbient {
|
||||
constructor(n: number);
|
||||
constructor(s: string);
|
||||
public pgF(): void;
|
||||
public pv;
|
||||
public d: number;
|
||||
static p2: { x: number; y: number; };
|
||||
static d2();
|
||||
static p3;
|
||||
private pv3;
|
||||
private foo(s);
|
||||
}
|
||||
|
||||
class d {
|
||||
private foo(n: number): string;
|
||||
private foo(ns: any) {
|
||||
return ns.toString();
|
||||
}
|
||||
private foo(s: string): string;
|
||||
}
|
||||
|
||||
class e {
|
||||
private foo(ns: any) {
|
||||
return ns.toString();
|
||||
}
|
||||
private foo(s: string): string;
|
||||
private foo(n: number): string;
|
||||
}
|
||||
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
class foo {
|
||||
constructor (n?: number, m? = 5, o?: string = "") { }
|
||||
x:number = 1?2:3;
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
class foo {
|
||||
constructor(n?: number, m? = 5, o?: string = "") { }
|
||||
x: number = 1 ? 2 : 3;
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
$ ( document ) . ready ( function ( ) {
|
||||
alert ( 'i am ready' ) ;
|
||||
} );
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
$(document).ready(function() {
|
||||
alert('i am ready');
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
-1
@@ -1 +0,0 @@
|
||||
{ }
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
function foo ( x : { } ) { }
|
||||
|
||||
foo ( { } ) ;
|
||||
|
||||
|
||||
|
||||
interface bar {
|
||||
x : { } ;
|
||||
y : ( ) => { } ;
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
function foo(x: {}) { }
|
||||
|
||||
foo({});
|
||||
|
||||
|
||||
|
||||
interface bar {
|
||||
x: {};
|
||||
y: () => {};
|
||||
}
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
// valid
|
||||
( ) => 1 ;
|
||||
( arg ) => 2 ;
|
||||
arg => 2 ;
|
||||
( arg = 1 ) => 3 ;
|
||||
( arg ? ) => 4 ;
|
||||
( arg : number ) => 5 ;
|
||||
( arg : number = 0 ) => 6 ;
|
||||
( arg ? : number ) => 7 ;
|
||||
( ... arg : number [ ] ) => 8 ;
|
||||
( arg1 , arg2 ) => 12 ;
|
||||
( arg1 = 1 , arg2 =3 ) => 13 ;
|
||||
( arg1 ? , arg2 ? ) => 14 ;
|
||||
( arg1 : number , arg2 : number ) => 15 ;
|
||||
( arg1 : number = 0 , arg2 : number = 1 ) => 16 ;
|
||||
( arg1 ? : number , arg2 ? : number ) => 17 ;
|
||||
( arg1 , ... arg2 : number [ ] ) => 18 ;
|
||||
( arg1 , arg2 ? : number ) => 19 ;
|
||||
|
||||
// in paren
|
||||
( ( ) => 21 ) ;
|
||||
( ( arg ) => 22 ) ;
|
||||
( ( arg = 1 ) => 23 ) ;
|
||||
( ( arg ? ) => 24 ) ;
|
||||
( ( arg : number ) => 25 ) ;
|
||||
( ( arg : number = 0 ) => 26 ) ;
|
||||
( ( arg ? : number ) => 27 ) ;
|
||||
( ( ... arg : number [ ] ) => 28 ) ;
|
||||
|
||||
// in multiple paren
|
||||
( ( ( ( ( arg ) => { return 32 ; } ) ) ) ) ;
|
||||
|
||||
// in ternary exression
|
||||
false ? ( ) => 41 : null ;
|
||||
false ? ( arg ) => 42 : null ;
|
||||
false ? ( arg = 1 ) => 43 : null ;
|
||||
false ? ( arg ? ) => 44 : null ;
|
||||
false ? ( arg : number ) => 45 : null ;
|
||||
false ? ( arg ? : number ) => 46 : null ;
|
||||
false ? ( arg ? : number = 0 ) => 47 : null ;
|
||||
false ? ( ... arg : number [ ] ) => 48 : null ;
|
||||
|
||||
// in ternary exression within paren
|
||||
false ? ( ( ) => 51 ) : null ;
|
||||
false ? ( ( arg ) => 52 ) : null ;
|
||||
false ? ( ( arg = 1 ) => 53 ) : null ;
|
||||
false ? ( ( arg ? ) => 54 ) : null ;
|
||||
false ? ( ( arg : number ) => 55 ) : null ;
|
||||
false ? ( ( arg ? : number ) => 56 ) : null ;
|
||||
false ? ( ( arg ? : number = 0 ) => 57 ) : null ;
|
||||
false ? ( ( ... arg : number [ ] ) => 58 ) : null ;
|
||||
|
||||
// ternary exression's else clause
|
||||
false ? null : ( ) => 61 ;
|
||||
false ? null : ( arg ) => 62 ;
|
||||
false ? null : ( arg = 1 ) => 63 ;
|
||||
false ? null : ( arg ? ) => 64 ;
|
||||
false ? null : ( arg : number ) => 65 ;
|
||||
false ? null : ( arg ? : number ) => 66 ;
|
||||
false ? null : ( arg ? : number = 0 ) => 67 ;
|
||||
false ? null : ( ... arg : number [ ] ) => 68 ;
|
||||
|
||||
|
||||
// nested ternary expressions
|
||||
( a ? ) => { return a ; } ? ( b ? ) => { return b ; } : ( c ? ) => { return c ; } ;
|
||||
|
||||
//multiple levels
|
||||
( a ? ) => { return a ; } ? ( b ) => ( c ) => 81 : ( c ) => ( d ) => 82 ;
|
||||
|
||||
|
||||
// In Expressions
|
||||
( ( arg ) => 90 ) instanceof Function ;
|
||||
( ( arg = 1 ) => 91 ) instanceof Function ;
|
||||
( ( arg ? ) => 92 ) instanceof Function ;
|
||||
( ( arg : number ) => 93 ) instanceof Function ;
|
||||
( ( arg : number = 1 ) => 94 ) instanceof Function ;
|
||||
( ( arg ? : number ) => 95 ) instanceof Function ;
|
||||
( ( ... arg : number [ ] ) => 96 ) instanceof Function ;
|
||||
|
||||
'' + ( arg ) => 100 ;
|
||||
( ( arg ) => 0 ) + '' + ( arg ) => 101 ;
|
||||
( ( arg = 1 ) => 0 ) + '' + ( arg = 2 ) => 102 ;
|
||||
( ( arg ? ) => 0 ) + '' + ( arg ? ) => 103 ;
|
||||
( ( arg : number ) => 0 ) + '' + ( arg : number ) => 104 ;
|
||||
( ( arg : number = 1 ) => 0 ) + '' + ( arg : number = 2 ) => 105 ;
|
||||
( ( arg ? : number = 1 ) => 0 ) + '' + ( arg ? : number = 2 ) => 106 ;
|
||||
( ( ... arg : number [ ] ) => 0 ) + '' + ( ... arg : number [ ] ) => 107 ;
|
||||
( ( arg1 , arg2 ? ) => 0 ) + '' + ( arg1 , arg2 ? ) => 108 ;
|
||||
( ( arg1 , ... arg2 : number [ ] ) => 0 ) + '' + ( arg1 , ... arg2 : number [ ] ) => 108 ;
|
||||
|
||||
|
||||
// Function Parameters
|
||||
function foo ( ... arg : any [ ] ) { }
|
||||
|
||||
foo (
|
||||
( a ) => 110 ,
|
||||
( ( a ) => 111 ) ,
|
||||
( a ) => {
|
||||
return 112 ;
|
||||
} ,
|
||||
( a ? ) => 113 ,
|
||||
( a , b ? ) => 114 ,
|
||||
( a : number ) => 115 ,
|
||||
( a : number = 0 ) => 116 ,
|
||||
( a = 0 ) => 117 ,
|
||||
( a ? : number = 0 ) => 118 ,
|
||||
( a ? , b ? : number = 0 ) => 118 ,
|
||||
( ... a : number [ ] ) => 119 ,
|
||||
( a , b ? = 0 , ... c : number [ ] ) => 120 ,
|
||||
( a ) => ( b ) => ( c ) => 121 ,
|
||||
false ? ( a ) => 0 : ( b ) => 122
|
||||
) ;
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
// valid
|
||||
() => 1;
|
||||
(arg) => 2;
|
||||
arg => 2;
|
||||
(arg = 1) => 3;
|
||||
(arg?) => 4;
|
||||
(arg: number) => 5;
|
||||
(arg: number = 0) => 6;
|
||||
(arg?: number) => 7;
|
||||
(...arg: number[]) => 8;
|
||||
(arg1, arg2) => 12;
|
||||
(arg1 = 1, arg2 = 3) => 13;
|
||||
(arg1?, arg2?) => 14;
|
||||
(arg1: number, arg2: number) => 15;
|
||||
(arg1: number = 0, arg2: number = 1) => 16;
|
||||
(arg1?: number, arg2?: number) => 17;
|
||||
(arg1, ...arg2: number[]) => 18;
|
||||
(arg1, arg2?: number) => 19;
|
||||
|
||||
// in paren
|
||||
(() => 21);
|
||||
((arg) => 22);
|
||||
((arg = 1) => 23);
|
||||
((arg?) => 24);
|
||||
((arg: number) => 25);
|
||||
((arg: number = 0) => 26);
|
||||
((arg?: number) => 27);
|
||||
((...arg: number[]) => 28);
|
||||
|
||||
// in multiple paren
|
||||
(((((arg) => { return 32; }))));
|
||||
|
||||
// in ternary exression
|
||||
false ? () => 41 : null;
|
||||
false ? (arg) => 42 : null;
|
||||
false ? (arg = 1) => 43 : null;
|
||||
false ? (arg?) => 44 : null;
|
||||
false ? (arg: number) => 45 : null;
|
||||
false ? (arg?: number) => 46 : null;
|
||||
false ? (arg?: number = 0) => 47 : null;
|
||||
false ? (...arg: number[]) => 48 : null;
|
||||
|
||||
// in ternary exression within paren
|
||||
false ? (() => 51) : null;
|
||||
false ? ((arg) => 52) : null;
|
||||
false ? ((arg = 1) => 53) : null;
|
||||
false ? ((arg?) => 54) : null;
|
||||
false ? ((arg: number) => 55) : null;
|
||||
false ? ((arg?: number) => 56) : null;
|
||||
false ? ((arg?: number = 0) => 57) : null;
|
||||
false ? ((...arg: number[]) => 58) : null;
|
||||
|
||||
// ternary exression's else clause
|
||||
false ? null : () => 61;
|
||||
false ? null : (arg) => 62;
|
||||
false ? null : (arg = 1) => 63;
|
||||
false ? null : (arg?) => 64;
|
||||
false ? null : (arg: number) => 65;
|
||||
false ? null : (arg?: number) => 66;
|
||||
false ? null : (arg?: number = 0) => 67;
|
||||
false ? null : (...arg: number[]) => 68;
|
||||
|
||||
|
||||
// nested ternary expressions
|
||||
(a?) => { return a; } ? (b?) => { return b; } : (c?) => { return c; };
|
||||
|
||||
//multiple levels
|
||||
(a?) => { return a; } ? (b) => (c) => 81 : (c) => (d) => 82;
|
||||
|
||||
|
||||
// In Expressions
|
||||
((arg) => 90) instanceof Function;
|
||||
((arg = 1) => 91) instanceof Function;
|
||||
((arg?) => 92) instanceof Function;
|
||||
((arg: number) => 93) instanceof Function;
|
||||
((arg: number = 1) => 94) instanceof Function;
|
||||
((arg?: number) => 95) instanceof Function;
|
||||
((...arg: number[]) => 96) instanceof Function;
|
||||
|
||||
'' + (arg) => 100;
|
||||
((arg) => 0) + '' + (arg) => 101;
|
||||
((arg = 1) => 0) + '' + (arg = 2) => 102;
|
||||
((arg?) => 0) + '' + (arg?) => 103;
|
||||
((arg: number) => 0) + '' + (arg: number) => 104;
|
||||
((arg: number = 1) => 0) + '' + (arg: number = 2) => 105;
|
||||
((arg?: number = 1) => 0) + '' + (arg?: number = 2) => 106;
|
||||
((...arg: number[]) => 0) + '' + (...arg: number[]) => 107;
|
||||
((arg1, arg2?) => 0) + '' + (arg1, arg2?) => 108;
|
||||
((arg1, ...arg2: number[]) => 0) + '' + (arg1, ...arg2: number[]) => 108;
|
||||
|
||||
|
||||
// Function Parameters
|
||||
function foo(...arg: any[]) { }
|
||||
|
||||
foo(
|
||||
(a) => 110,
|
||||
((a) => 111),
|
||||
(a) => {
|
||||
return 112;
|
||||
},
|
||||
(a?) => 113,
|
||||
(a, b?) => 114,
|
||||
(a: number) => 115,
|
||||
(a: number = 0) => 116,
|
||||
(a = 0) => 117,
|
||||
(a?: number = 0) => 118,
|
||||
(a?, b?: number = 0) => 118,
|
||||
(...a: number[]) => 119,
|
||||
(a, b? = 0, ...c: number[]) => 120,
|
||||
(a) => (b) => (c) => 121,
|
||||
false ? (a) => 0 : (b) => 122
|
||||
);
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
if(false){debugger;}
|
||||
if ( false ) { debugger ; }
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
if (false) { debugger; }
|
||||
if (false) { debugger; }
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
var fun1 = function ( ) {
|
||||
var x = 'foo' ,
|
||||
z = 'bar' ;
|
||||
return x ;
|
||||
},
|
||||
|
||||
fun2 = ( function ( f ) {
|
||||
var fun = function ( ) {
|
||||
console . log ( f ( ) ) ;
|
||||
},
|
||||
x = 'Foo' ;
|
||||
return fun ;
|
||||
} ( fun1 ) ) ;
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
var fun1 = function() {
|
||||
var x = 'foo',
|
||||
z = 'bar';
|
||||
return x;
|
||||
},
|
||||
|
||||
fun2 = (function(f) {
|
||||
var fun = function() {
|
||||
console.log(f());
|
||||
},
|
||||
x = 'Foo';
|
||||
return fun;
|
||||
} (fun1));
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
export class A {
|
||||
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
export class A {
|
||||
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
module Foo {
|
||||
}
|
||||
|
||||
import bar = Foo;
|
||||
|
||||
import bar2=Foo;
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
module Foo {
|
||||
}
|
||||
|
||||
import bar = Foo;
|
||||
|
||||
import bar2 = Foo;
|
||||
@@ -1,95 +0,0 @@
|
||||
|
||||
var a;var c , b;var $d
|
||||
var $e
|
||||
var f
|
||||
a++;b++;
|
||||
|
||||
function f ( ) {
|
||||
for (i = 0; i < 10; i++) {
|
||||
k = abc + 123 ^ d;
|
||||
a = XYZ[m (a[b[c][d]])];
|
||||
break;
|
||||
|
||||
switch ( variable){
|
||||
case 1: abc += 425;
|
||||
break;
|
||||
case 404 : a [x--/2]%=3 ;
|
||||
break ;
|
||||
case vari : v[--x ] *=++y*( m + n / k[z]);
|
||||
for (a in b){
|
||||
for (a = 0; a < 10; ++a) {
|
||||
a++;--a;
|
||||
if (a == b) {
|
||||
a++;b--;
|
||||
}
|
||||
else
|
||||
if (a == c){
|
||||
++a;
|
||||
(--c)+=d;
|
||||
$c = $a + --$b;
|
||||
}
|
||||
if (a == b)
|
||||
if (a != b) {
|
||||
if (a !== b)
|
||||
if (a === b)
|
||||
--a;
|
||||
else
|
||||
--a;
|
||||
else {
|
||||
a--;++b;
|
||||
a++
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x in y) {
|
||||
m-=m;
|
||||
k=1+2+3+4;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
var a ={b:function(){}};
|
||||
return {a:1,b:2}
|
||||
}
|
||||
|
||||
var z = 1;
|
||||
for (i = 0; i < 10; i++)
|
||||
for (j = 0; j < 10; j++)
|
||||
for (k = 0; k < 10; ++k) {
|
||||
z++;
|
||||
}
|
||||
|
||||
for (k = 0; k < 10; k += 2) {
|
||||
z++;
|
||||
}
|
||||
|
||||
$(document).ready ();
|
||||
|
||||
|
||||
function pageLoad() {
|
||||
$('#TextBox1' ) . unbind ( ) ;
|
||||
$('#TextBox1' ) . datepicker ( ) ;
|
||||
}
|
||||
|
||||
function pageLoad ( ) {
|
||||
var webclass=[
|
||||
{ 'student' :
|
||||
{ 'id': '1', 'name': 'Linda Jones', 'legacySkill': 'Access, VB 5.0' }
|
||||
} ,
|
||||
{ 'student':
|
||||
{'id':'2','name':'Adam Davidson','legacySkill':'Cobol,MainFrame'}
|
||||
} ,
|
||||
{ 'student':
|
||||
{ 'id':'3','name':'Charles Boyer' ,'legacySkill':'HTML, XML'}
|
||||
}
|
||||
];
|
||||
|
||||
$create(Sys.UI.DataView,{data:webclass},null,null,$get('SList'));
|
||||
|
||||
}
|
||||
|
||||
$( document ).ready(function(){
|
||||
alert('hello');
|
||||
} ) ;
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
|
||||
var a; var c, b; var $d
|
||||
var $e
|
||||
var f
|
||||
a++; b++;
|
||||
|
||||
function f() {
|
||||
for (i = 0; i < 10; i++) {
|
||||
k = abc + 123 ^ d;
|
||||
a = XYZ[m(a[b[c][d]])];
|
||||
break;
|
||||
|
||||
switch (variable) {
|
||||
case 1: abc += 425;
|
||||
break;
|
||||
case 404: a[x-- / 2] %= 3;
|
||||
break;
|
||||
case vari: v[--x] *= ++y * (m + n / k[z]);
|
||||
for (a in b) {
|
||||
for (a = 0; a < 10; ++a) {
|
||||
a++; --a;
|
||||
if (a == b) {
|
||||
a++; b--;
|
||||
}
|
||||
else
|
||||
if (a == c) {
|
||||
++a;
|
||||
(--c) += d;
|
||||
$c = $a + --$b;
|
||||
}
|
||||
if (a == b)
|
||||
if (a != b) {
|
||||
if (a !== b)
|
||||
if (a === b)
|
||||
--a;
|
||||
else
|
||||
--a;
|
||||
else {
|
||||
a--; ++b;
|
||||
a++
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x in y) {
|
||||
m -= m;
|
||||
k = 1 + 2 + 3 + 4;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
var a = { b: function() { } };
|
||||
return { a: 1, b: 2 }
|
||||
}
|
||||
|
||||
var z = 1;
|
||||
for (i = 0; i < 10; i++)
|
||||
for (j = 0; j < 10; j++)
|
||||
for (k = 0; k < 10; ++k) {
|
||||
z++;
|
||||
}
|
||||
|
||||
for (k = 0; k < 10; k += 2) {
|
||||
z++;
|
||||
}
|
||||
|
||||
$(document).ready();
|
||||
|
||||
|
||||
function pageLoad() {
|
||||
$('#TextBox1').unbind();
|
||||
$('#TextBox1').datepicker();
|
||||
}
|
||||
|
||||
function pageLoad() {
|
||||
var webclass = [
|
||||
{
|
||||
'student':
|
||||
{ 'id': '1', 'name': 'Linda Jones', 'legacySkill': 'Access, VB 5.0' }
|
||||
},
|
||||
{
|
||||
'student':
|
||||
{ 'id': '2', 'name': 'Adam Davidson', 'legacySkill': 'Cobol,MainFrame' }
|
||||
},
|
||||
{
|
||||
'student':
|
||||
{ 'id': '3', 'name': 'Charles Boyer', 'legacySkill': 'HTML, XML' }
|
||||
}
|
||||
];
|
||||
|
||||
$create(Sys.UI.DataView, { data: webclass }, null, null, $get('SList'));
|
||||
|
||||
}
|
||||
|
||||
$(document).ready(function() {
|
||||
alert('hello');
|
||||
});
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
module Foo {
|
||||
export module A . B . C { }
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
module Foo {
|
||||
export module A.B.C { }
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
module mod1 {
|
||||
export class b {
|
||||
}
|
||||
class d {
|
||||
}
|
||||
|
||||
|
||||
export interface ib {
|
||||
}
|
||||
}
|
||||
|
||||
module m2 {
|
||||
|
||||
export module m3 {
|
||||
export class c extends mod1.b {
|
||||
}
|
||||
export class ib2 implements mod1.ib {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class c extends mod1.b {
|
||||
}
|
||||
|
||||
class ib2 implements mod1.ib {
|
||||
}
|
||||
|
||||
declare export module "m4" {
|
||||
export class d {
|
||||
} ;
|
||||
var x : d ;
|
||||
export function foo ( ) : d ;
|
||||
}
|
||||
|
||||
import m4 = module ( "m4" ) ;
|
||||
export var x4 = m4.x ;
|
||||
export var d4 = m4.d ;
|
||||
export var f4 = m4.foo ( ) ;
|
||||
|
||||
export module m1 {
|
||||
declare export module "m2" {
|
||||
export class d {
|
||||
} ;
|
||||
var x: d ;
|
||||
export function foo ( ) : d ;
|
||||
}
|
||||
import m2 = module ( "m2" ) ;
|
||||
import m3 = module ( "m4" ) ;
|
||||
|
||||
export var x2 = m2.x ;
|
||||
export var d2 = m2.d ;
|
||||
export var f2 = m2.foo ( ) ;
|
||||
|
||||
export var x3 = m3.x ;
|
||||
export var d3 = m3.d ;
|
||||
export var f3 = m3.foo ( ) ;
|
||||
}
|
||||
|
||||
export var x2 = m1.m2.x ;
|
||||
export var d2 = m1.m2.d ;
|
||||
export var f2 = m1.m2.foo ( ) ;
|
||||
|
||||
export var x3 = m1.m3.x ;
|
||||
export var d3 = m1.m3.d ;
|
||||
export var f3 = m1.m3.foo ( ) ;
|
||||
|
||||
export module m5 {
|
||||
export var x2 = m1.m2.x ;
|
||||
export var d2 = m1.m2.d ;
|
||||
export var f2 = m1.m2.foo ( ) ;
|
||||
|
||||
export var x3 = m1.m3.x ;
|
||||
export var d3 = m1.m3.d ;
|
||||
export var f3 = m1.m3.foo ( ) ;
|
||||
}
|
||||
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
module mod1 {
|
||||
export class b {
|
||||
}
|
||||
class d {
|
||||
}
|
||||
|
||||
|
||||
export interface ib {
|
||||
}
|
||||
}
|
||||
|
||||
module m2 {
|
||||
|
||||
export module m3 {
|
||||
export class c extends mod1.b {
|
||||
}
|
||||
export class ib2 implements mod1.ib {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class c extends mod1.b {
|
||||
}
|
||||
|
||||
class ib2 implements mod1.ib {
|
||||
}
|
||||
|
||||
declare export module "m4" {
|
||||
export class d {
|
||||
};
|
||||
var x: d;
|
||||
export function foo(): d;
|
||||
}
|
||||
|
||||
import m4 = module("m4");
|
||||
export var x4 = m4.x;
|
||||
export var d4 = m4.d;
|
||||
export var f4 = m4.foo();
|
||||
|
||||
export module m1 {
|
||||
declare export module "m2" {
|
||||
export class d {
|
||||
};
|
||||
var x: d;
|
||||
export function foo(): d;
|
||||
}
|
||||
import m2 = module("m2");
|
||||
import m3 = module("m4");
|
||||
|
||||
export var x2 = m2.x;
|
||||
export var d2 = m2.d;
|
||||
export var f2 = m2.foo();
|
||||
|
||||
export var x3 = m3.x;
|
||||
export var d3 = m3.d;
|
||||
export var f3 = m3.foo();
|
||||
}
|
||||
|
||||
export var x2 = m1.m2.x;
|
||||
export var d2 = m1.m2.d;
|
||||
export var f2 = m1.m2.foo();
|
||||
|
||||
export var x3 = m1.m3.x;
|
||||
export var d3 = m1.m3.d;
|
||||
export var f3 = m1.m3.foo();
|
||||
|
||||
export module m5 {
|
||||
export var x2 = m1.m2.x;
|
||||
export var d2 = m1.m2.d;
|
||||
export var f2 = m1.m2.foo();
|
||||
|
||||
export var x3 = m1.m3.x;
|
||||
export var d3 = m1.m3.d;
|
||||
export var f3 = m1.m3.foo();
|
||||
}
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
var x = {foo: 1,
|
||||
bar: "tt",
|
||||
boo: 1 + 5};
|
||||
|
||||
var x2 = {foo: 1,
|
||||
bar: "tt",boo:1+5};
|
||||
|
||||
function Foo() {
|
||||
var typeICalc = {
|
||||
clear: {
|
||||
"()": [1, 2, 3]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rule for object literal members for the "value" of the memebr to follow the indent
|
||||
// of the member, i.e. the relative position of the value is maintained when the member
|
||||
// is indented.
|
||||
var x2 = {
|
||||
foo:
|
||||
3,
|
||||
'bar':
|
||||
{ a: 1, b : 2}
|
||||
};
|
||||
|
||||
var x={ };
|
||||
var y = {};
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
var x = {
|
||||
foo: 1,
|
||||
bar: "tt",
|
||||
boo: 1 + 5
|
||||
};
|
||||
|
||||
var x2 = {
|
||||
foo: 1,
|
||||
bar: "tt", boo: 1 + 5
|
||||
};
|
||||
|
||||
function Foo() {
|
||||
var typeICalc = {
|
||||
clear: {
|
||||
"()": [1, 2, 3]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rule for object literal members for the "value" of the memebr to follow the indent
|
||||
// of the member, i.e. the relative position of the value is maintained when the member
|
||||
// is indented.
|
||||
var x2 = {
|
||||
foo:
|
||||
3,
|
||||
'bar':
|
||||
{ a: 1, b: 2 }
|
||||
};
|
||||
|
||||
var x = {};
|
||||
var y = {};
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
function f( ) {
|
||||
var x = 3;
|
||||
var z = 2 ;
|
||||
a = z ++ - 2 * x ;
|
||||
for ( ; ; ) {
|
||||
a+=(g +g)*a%t;
|
||||
b -- ;
|
||||
}
|
||||
|
||||
switch ( a )
|
||||
{
|
||||
case 1 : {
|
||||
a ++ ;
|
||||
b--;
|
||||
if(a===a)
|
||||
return;
|
||||
else
|
||||
{
|
||||
for(a in b)
|
||||
if(a!=a)
|
||||
{
|
||||
for(a in b)
|
||||
{
|
||||
a++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
function f() {
|
||||
var x = 3;
|
||||
var z = 2;
|
||||
a = z++ - 2 * x;
|
||||
for (; ;) {
|
||||
a += (g + g) * a % t;
|
||||
b--;
|
||||
}
|
||||
|
||||
switch (a) {
|
||||
case 1: {
|
||||
a++;
|
||||
b--;
|
||||
if (a === a)
|
||||
return;
|
||||
else {
|
||||
for (a in b)
|
||||
if (a != a) {
|
||||
for (a in b) {
|
||||
a++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user