Merge branch 'master' into literalTypes

# Conflicts:
#	src/compiler/checker.ts
This commit is contained in:
Anders Hejlsberg
2016-07-24 07:28:11 -07:00
306 changed files with 4481 additions and 3322 deletions

2
.gitignore vendored
View File

@@ -17,6 +17,7 @@ tests/baselines/reference/projectOutput/*
tests/baselines/local/projectOutput/*
tests/services/baselines/prototyping/local/*
tests/services/browser/typescriptServices.js
scripts/authors.js
scripts/configureNightly.js
scripts/processDiagnosticMessages.d.ts
scripts/processDiagnosticMessages.js
@@ -50,3 +51,4 @@ internal/
!**/.vscode/tasks.json
!tests/cases/projects/projectOption/**/node_modules
!tests/cases/projects/NodeModulesSearch/**/*
!tests/baselines/reference/project/nodeModules*/**/*

View File

@@ -125,6 +125,7 @@ Stan Thomas <stmsdn@norvil.net>
Stanislav Sysoev <d4rkr00t@gmail.com>
Steve Lucco <steveluc@users.noreply.github.com> steveluc <steveluc@microsoft.com>
Tarik <tarik@pushmote.com> # Tarik Ozket
Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> # Tetsuharu Ohzeki
Tien Nguyen <tihoanh@microsoft.com> tien <hoanhtien@users.noreply.github.com> unknown <tihoanh@microsoft.com> #Tien Hoanhtien
Tim Perry <pimterry@gmail.com>
Tim Viiding-Spader <viispade@users.noreply.github.com>

View File

@@ -6,3 +6,10 @@ node_js:
- '0.10'
sudo: false
os:
- linux
- osx
matrix:
fast_finish: true

View File

@@ -1,6 +1,4 @@
/// <reference path="scripts/types/ambient.d.ts" />
/// <reference types="q" />
import * as cp from "child_process";
import * as path from "path";
import * as fs from "fs";
@@ -13,16 +11,19 @@ import newer = require("gulp-newer");
import tsc = require("gulp-typescript");
declare module "gulp-typescript" {
interface Settings {
stripInternal?: boolean;
pretty?: boolean;
newLine?: string;
noImplicitThis?: boolean;
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
}
import * as insert from "gulp-insert";
import * as sourcemaps from "gulp-sourcemaps";
import Q = require("q");
declare global {
// This is silly. We include Q because orchestrator (a part of gulp) depends on it, but its not included.
// `del` further depends on `Promise` (and is also not included), so we just, patch the global scope's Promise to Q's
// `del` further depends on `Promise` (and is also not included), so we just, patch the global scope's Promise to Q's (which we already include in our deps because gulp depends on it)
type Promise<T> = Q.Promise<T>;
}
import del = require("del");
@@ -84,12 +85,9 @@ let host = cmdLineOptions["host"];
// Constants
const compilerDirectory = "src/compiler/";
const servicesDirectory = "src/services/";
const serverDirectory = "src/server/";
const harnessDirectory = "src/harness/";
const libraryDirectory = "src/lib/";
const scriptsDirectory = "scripts/";
const unittestsDirectory = "tests/cases/unittests/";
const docDirectory = "doc/";
const builtDirectory = "built/";
@@ -106,69 +104,6 @@ const nodeModulesPathPrefix = path.resolve("./node_modules/.bin/");
const isWin = /^win/.test(process.platform);
const mocha = path.join(nodeModulesPathPrefix, "mocha") + (isWin ? ".cmd" : "");
const compilerSources = require("./src/compiler/tsconfig.json").files.map((file) => path.join(compilerDirectory, file));
const servicesSources = require("./src/services/tsconfig.json").files.map((file) => path.join(servicesDirectory, file));
const serverCoreSources = require("./src/server/tsconfig.json").files.map((file) => path.join(serverDirectory, file));
const languageServiceLibrarySources = [
"editorServices.ts",
"protocol.d.ts",
"session.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}).concat(servicesSources);
const harnessCoreSources = [
"harness.ts",
"sourceMapRecorder.ts",
"harnessLanguageService.ts",
"fourslash.ts",
"runnerbase.ts",
"compilerRunner.ts",
"typeWriter.ts",
"fourslashRunner.ts",
"projectsRunner.ts",
"loggedIO.ts",
"rwcRunner.ts",
"test262Runner.ts",
"runner.ts"
].map(function (f) {
return path.join(harnessDirectory, f);
});
const harnessSources = harnessCoreSources.concat([
"incrementalParser.ts",
"jsDocParsing.ts",
"services/colorization.ts",
"services/documentRegistry.ts",
"services/preProcessFile.ts",
"services/patternMatcher.ts",
"session.ts",
"versionCache.ts",
"convertToBase64.ts",
"transpile.ts",
"reuseProgramStructure.ts",
"cachingInServerLSHost.ts",
"moduleResolution.ts",
"tsconfigParsing.ts",
"commandLineParsing.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts",
"tsserverProjectSystem.ts",
"matchFiles.ts",
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
"protocol.d.ts",
"session.ts",
"client.ts",
"editorServices.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}));
const es2015LibrarySources = [
"es2015.core.d.ts",
"es2015.collection.d.ts",
@@ -308,6 +243,11 @@ function needsUpdate(source: string | string[], dest: string | string[]): boolea
function getCompilerSettings(base: tsc.Settings, useBuiltCompiler?: boolean): tsc.Settings {
const copy: tsc.Settings = {};
copy.noEmitOnError = true;
copy.noImplicitAny = true;
copy.noImplicitThis = true;
copy.pretty = true;
copy.types = [];
for (const key in base) {
copy[key] = base[key];
}
@@ -494,21 +434,18 @@ const tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js")
const tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => {
const settings: tsc.Settings = getCompilerSettings({
declaration: true,
outFile: tsserverLibraryFile
}, /*useBuiltCompiler*/ true);
const {js, dts}: {js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream} = gulp.src(languageServiceLibrarySources)
const serverLibraryProject = tsc.createProject("src/server/tsconfig.library.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
const {js, dts}: {js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream} = serverLibraryProject.src()
.pipe(sourcemaps.init())
.pipe(newer(tsserverLibraryFile))
.pipe(tsc(settings));
.pipe(tsc(serverLibraryProject));
return merge2([
js.pipe(prependCopyright())
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(".")),
.pipe(gulp.dest(builtLocalDirectory)),
dts.pipe(prependCopyright())
.pipe(gulp.dest("."))
.pipe(gulp.dest(builtLocalDirectory))
]);
});
@@ -577,15 +514,13 @@ gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUse
// Task to build the tests infrastructure using the built compiler
const run = path.join(builtLocalDirectory, "run.js");
gulp.task(run, false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: run
}, /*useBuiltCompiler*/ true);
return gulp.src(harnessSources)
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
return testProject.src()
.pipe(newer(run))
.pipe(sourcemaps.init())
.pipe(tsc(settings))
.pipe(tsc(testProject))
.pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" }))
.pipe(gulp.dest("."));
.pipe(gulp.dest(builtLocalDirectory));
});
const internalTests = "internal/";
@@ -759,23 +694,50 @@ gulp.task(nodeServerOutFile, false, [servicesFile], () => {
.pipe(gulp.dest(path.dirname(nodeServerOutFile)));
});
import convertMap = require("convert-source-map");
import sorcery = require("sorcery");
declare module "convert-source-map" {
export function fromSource(source: string, largeSource?: boolean): SourceMapConverter;
}
gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile], (done) => {
const settings: tsc.Settings = getCompilerSettings({
outFile: "built/local/bundle.js"
}, /*useBuiltCompiler*/ true);
return gulp.src(harnessSources)
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({ outFile: "built/local/bundle.js" }, /*useBuiltCompiler*/ true));
return testProject.src()
.pipe(newer("built/local/bundle.js"))
.pipe(sourcemaps.init())
.pipe(tsc(settings))
.pipe(tsc(testProject))
.pipe(through2.obj((file, enc, next) => {
browserify(intoStream(file.contents))
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));
// 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";
browserify(intoStream(file.contents), { debug: true })
.bundle((err, res) => {
// assumes file.contents is a Buffer
file.contents = res;
const maps = JSON.parse(convertMap.fromSource(res.toString(), /*largeSource*/true).toJSON());
delete maps.sourceRoot;
maps.sources = maps.sources.map(s => path.resolve(s === "_stream_0.js" ? "built/local/_stream_0.js" : s));
// Strip browserify's inline comments away (could probably just let sorcery do this, but then we couldn't fix the paths)
file.contents = new Buffer(convertMap.removeComments(res.toString()));
const chain = sorcery.loadSync("built/local/bundle.js", {
content: {
"built/local/_stream_0.js": prebundledContent,
"built/local/bundle.js": file.contents.toString()
},
sourcemaps: {
"built/local/_stream_0.js": originalMap,
"built/local/bundle.js": maps,
}
});
const finalMap = chain.apply();
file.sourceMap = finalMap;
next(undefined, file);
});
}))
.pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" }))
.pipe(sourcemaps.write(".", { includeContent: false }))
.pipe(gulp.dest("."));
});
@@ -1007,36 +969,37 @@ function lintFile(options, path) {
return lintFileContents(options, path, contents);
}
const lintTargets = ["Gulpfile.ts"]
.concat(compilerSources)
.concat(harnessSources)
// Other harness sources
.concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f); }))
.concat(serverCoreSources)
.concat(tslintRulesFiles)
.concat(servicesSources);
const lintTargets = [
"Gulpfile.ts",
"src/compiler/**/*.ts",
"src/harness/**/*.ts",
"!src/harness/unittests/services/formatting/**/*.ts",
"src/server/**/*.ts",
"scripts/tslint/**/*.ts",
"src/services/**/*.ts",
];
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;
const fileMatcher = RegExp(cmdLineOptions["files"]);
const done = {};
for (const i in lintTargets) {
const target = lintTargets[i];
if (!done[target] && fileMatcher.test(target)) {
const result = lintFile(lintOptions, target);
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;
}
done[target] = true;
}
}
if (failed > 0) {
console.error("Linter errors.");
process.exit(1);
}
return contents; // TODO (weswig): Automatically apply fixes? :3
}))
.on("end", () => {
if (failed > 0) {
console.error("Linter errors.");
process.exit(1);
}
});
});

View File

@@ -14,7 +14,7 @@ var serverDirectory = "src/server/";
var harnessDirectory = "src/harness/";
var libraryDirectory = "src/lib/";
var scriptsDirectory = "scripts/";
var unittestsDirectory = "tests/cases/unittests/";
var unittestsDirectory = "src/harness/unittests/";
var docDirectory = "doc/";
var builtDirectory = "built/";
@@ -34,6 +34,7 @@ if (process.env.path !== undefined) {
var compilerSources = [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",
@@ -54,6 +55,7 @@ var compilerSources = [
var servicesSources = [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",
@@ -100,7 +102,6 @@ var servicesSources = [
}));
var serverCoreSources = [
"node.d.ts",
"editorServices.ts",
"protocol.d.ts",
"session.ts",
@@ -279,13 +280,18 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
* @param {boolean} opts.stripInternal: true if compiler should remove declarations marked as @internal
* @param {boolean} opts.noMapRoot: true if compiler omit mapRoot option
* @param {boolean} opts.inlineSourceMap: true if compiler should inline sourceMap
* @param {Array} opts.types: array of types to include in compilation
* @param callback: a function to execute after the compilation process ends
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) {
file(outFile, prereqs, function() {
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--noImplicitAny --noEmitOnError --types --pretty";
opts = opts || {};
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--noImplicitAny --noImplicitThis --noEmitOnError --types "
if (opts.types) {
options += opts.types.join(",");
}
options += " --pretty";
// Keep comments when specifically requested
// or when in debug mode.
if (!(opts.keepComments || useDebugMode)) {
@@ -462,15 +468,6 @@ task("publish-nightly", ["configure-nightly", "LKG", "clean", "setDebugMode", "r
exec(cmd);
});
var scriptsTsdJson = path.join(scriptsDirectory, "tsd.json");
file(scriptsTsdJson);
task("tsd-scripts", [scriptsTsdJson], function () {
var cmd = "tsd --config " + scriptsTsdJson + " install";
console.log(cmd);
exec(cmd);
}, { async: true });
var importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importDefinitelyTypedTests");
var importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js");
var importDefinitelyTypedTestsTs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.ts");
@@ -548,8 +545,7 @@ compileFile(
});
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { types: ["node"] });
var tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js");
var tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
compileFile(
@@ -652,7 +648,7 @@ compileFile(
/*prereqs*/ [builtLocalDirectory, tscFile].concat(libraryTargets).concat(harnessSources),
/*prefixes*/ [],
/*useBuiltCompiler:*/ true,
/*opts*/ { inlineSourceMap: true });
/*opts*/ { inlineSourceMap: true, types: ["node", "mocha", "chai"] });
var internalTests = "internal/";

View File

@@ -825,10 +825,17 @@ 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) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -1093,6 +1100,8 @@ 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; },
@@ -1224,7 +1233,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -1243,7 +1252,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -1263,6 +1272,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -1435,7 +1445,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -1485,7 +1495,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -1533,6 +1543,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -2282,8 +2293,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." },
@@ -4836,7 +4847,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -6344,25 +6355,24 @@ 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);
}
@@ -6785,6 +6795,8 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -6810,6 +6822,8 @@ 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;
@@ -7116,7 +7130,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -10892,6 +10908,9 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -15418,17 +15437,18 @@ 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) {
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 (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 (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@@ -21935,7 +21955,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@@ -23155,7 +23175,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -24051,6 +24071,7 @@ 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);
}
@@ -24066,6 +24087,9 @@ 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;
}
@@ -24094,9 +24118,14 @@ 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 (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -25173,7 +25202,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -29896,7 +29925,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();
@@ -33546,13 +33575,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -35796,7 +35825,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -35876,12 +35905,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -36537,6 +36561,22 @@ 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;
@@ -36612,7 +36652,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@@ -36836,8 +36876,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -37244,8 +37283,17 @@ 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(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
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) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -37262,6 +37310,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@@ -37362,12 +37411,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -37375,8 +37421,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 (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@@ -37695,12 +37741,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",
@@ -38479,10 +38525,18 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
var reportDiagnostic = reportDiagnosticSimply;
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);
}
function reportDiagnostics(diagnostics, host) {
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
reportDiagnostic(diagnostic, host);
}
}
@@ -38553,19 +38607,8 @@ 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) {
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);
ts.sys.write(ts.formatDiagnostics([diagnostic], host));
}
var redForegroundEscapeSequence = "\u001b[91m";
var yellowForegroundEscapeSequence = "\u001b[93m";
@@ -38590,7 +38633,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 = getRelativeFileName(file.fileName, host);
var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
@@ -38779,7 +38822,8 @@ var ts;
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName);
var cwd = ts.sys.getCurrentDirectory();
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd));
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, undefined);
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -38816,7 +38860,7 @@ var ts;
compilerHost.fileExists = cachedFileExists;
}
if (compilerOptions.pretty) {
reportDiagnostic = reportDiagnosticWithColorAndContext;
reportDiagnosticWorker = reportDiagnosticWithColorAndContext;
}
cachedExistingFiles = {};
var compileResult = compile(rootFileNames, compilerOptions, compilerHost);
@@ -38979,7 +39023,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 --out file.js file.ts" + ts.sys.newLine;
output += padding + "tsc --outFile 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;

View File

@@ -830,10 +830,17 @@ 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) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -1098,6 +1105,8 @@ 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; },
@@ -1229,7 +1238,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -1248,7 +1257,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -1268,6 +1277,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -1440,7 +1450,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -1490,7 +1500,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -1538,6 +1548,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -2287,8 +2298,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." },
@@ -3966,12 +3977,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",
@@ -5754,7 +5765,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7262,25 +7273,24 @@ 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);
}
@@ -7703,6 +7713,8 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -7728,6 +7740,8 @@ 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;
@@ -8034,7 +8048,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -11810,6 +11826,9 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -16336,17 +16355,18 @@ 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) {
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 (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 (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@@ -22853,7 +22873,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@@ -24073,7 +24093,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -24969,6 +24989,7 @@ 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);
}
@@ -24984,6 +25005,9 @@ 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;
}
@@ -25012,9 +25036,14 @@ 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 (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -26091,7 +26120,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -30814,7 +30843,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();
@@ -34464,13 +34493,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -36714,7 +36743,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -36794,12 +36823,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -37455,6 +37479,22 @@ 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;
@@ -37530,7 +37570,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@@ -37754,8 +37794,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -38162,8 +38201,17 @@ 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(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
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) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -38180,6 +38228,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@@ -38280,12 +38329,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -38293,8 +38339,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 (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@@ -39887,7 +39933,7 @@ var ts;
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
}
else {
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -40059,14 +40105,6 @@ 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)) {
@@ -41551,6 +41589,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244;
}
function shouldRescanSlashToken(container) {
return container.kind === 10;
}
@@ -41578,7 +41619,9 @@ var ts;
? 3
: shouldRescanJsxIdentifier(n)
? 4
: 0;
: shouldRescanJsxText(n)
? 5
: 0;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
return fixTokenKind(lastTokenInfo, n);
}
@@ -41606,6 +41649,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4;
}
else if (expectedScanAction === 5) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5;
}
else {
lastScanAction = 0;
}
@@ -43854,19 +43901,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
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);
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);
@@ -43901,14 +43949,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282, nodes.pos, nodes.end, 0, this);
var list = createNode(282, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -43993,6 +44041,73 @@ 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;
@@ -49673,6 +49788,8 @@ 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; },
@@ -50793,7 +50910,6 @@ 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));
@@ -52419,7 +52535,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
this.done = true;
walkFns.done = true;
}
}
};
@@ -53069,7 +53185,7 @@ var ts;
ioSession.listen();
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
var ts;
(function (ts) {
function logInternalError(logger, err) {
@@ -53197,7 +53313,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return this.shimHost.getDirectories(path);
return JSON.parse(this.shimHost.getDirectories(path));
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));

View File

@@ -405,7 +405,10 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Modifier extends Node {
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
}
interface Identifier extends PrimaryExpression {
text: string;
@@ -2050,7 +2053,6 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@@ -2156,6 +2158,8 @@ 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;
@@ -2193,6 +2197,8 @@ 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;
@@ -6456,13 +6462,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;
@@ -7143,8 +7149,6 @@ 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;
@@ -7225,6 +7229,12 @@ 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;
@@ -8388,7 +8398,6 @@ declare namespace ts.server {
class ScriptInfo {
private host;
fileName: string;
content: string;
isOpen: boolean;
svc: ScriptVersionCache;
children: ScriptInfo[];
@@ -8729,7 +8738,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;

View File

@@ -830,10 +830,17 @@ 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) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -1098,6 +1105,8 @@ 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; },
@@ -1229,7 +1238,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -1248,7 +1257,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -1268,6 +1277,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -1440,7 +1450,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -1490,7 +1500,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -1538,6 +1548,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -2287,8 +2298,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." },
@@ -3966,12 +3977,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",
@@ -5754,7 +5765,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7262,25 +7273,24 @@ 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);
}
@@ -7703,6 +7713,8 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -7728,6 +7740,8 @@ 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;
@@ -8034,7 +8048,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -11810,6 +11826,9 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -16336,17 +16355,18 @@ 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) {
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 (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 (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@@ -22853,7 +22873,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@@ -24073,7 +24093,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -24969,6 +24989,7 @@ 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);
}
@@ -24984,6 +25005,9 @@ 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;
}
@@ -25012,9 +25036,14 @@ 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 (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -26091,7 +26120,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -30814,7 +30843,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();
@@ -34464,13 +34493,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -36714,7 +36743,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -36794,12 +36823,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -37455,6 +37479,22 @@ 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;
@@ -37530,7 +37570,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesJsDepth = 0;
var currentNodeModulesDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@@ -37754,8 +37794,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -38162,8 +38201,17 @@ 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(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
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) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -38180,6 +38228,7 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@@ -38280,12 +38329,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -38293,8 +38339,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 (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@@ -39887,7 +39933,7 @@ var ts;
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
}
else {
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -40059,14 +40105,6 @@ 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)) {
@@ -41551,6 +41589,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244;
}
function shouldRescanSlashToken(container) {
return container.kind === 10;
}
@@ -41578,7 +41619,9 @@ var ts;
? 3
: shouldRescanJsxIdentifier(n)
? 4
: 0;
: shouldRescanJsxText(n)
? 5
: 0;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
return fixTokenKind(lastTokenInfo, n);
}
@@ -41606,6 +41649,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4;
}
else if (expectedScanAction === 5) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5;
}
else {
lastScanAction = 0;
}
@@ -43854,19 +43901,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
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);
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);
@@ -43901,14 +43949,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282, nodes.pos, nodes.end, 0, this);
var list = createNode(282, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -43993,6 +44041,73 @@ 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;
@@ -49673,6 +49788,8 @@ 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; },
@@ -50793,7 +50910,6 @@ 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));
@@ -52419,7 +52535,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
this.done = true;
walkFns.done = true;
}
}
};
@@ -52835,7 +52951,7 @@ var ts;
server.LineLeaf = LineLeaf;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
var ts;
(function (ts) {
function logInternalError(logger, err) {
@@ -52963,7 +53079,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return this.shimHost.getDirectories(path);
return JSON.parse(this.shimHost.getDirectories(path));
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));

14
lib/typescript.d.ts vendored
View File

@@ -409,7 +409,10 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Modifier extends Node {
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
}
interface Identifier extends PrimaryExpression {
text: string;
@@ -1696,7 +1699,6 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@@ -1842,8 +1844,6 @@ 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,6 +1868,12 @@ 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

View File

@@ -1756,10 +1756,19 @@ 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) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -2070,6 +2079,8 @@ 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; },
@@ -2216,7 +2227,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -2235,7 +2246,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -2255,6 +2266,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -2444,7 +2456,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -2500,7 +2512,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -2548,6 +2560,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -3304,8 +3317,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." },
@@ -6153,7 +6166,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 moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7916,15 +7929,6 @@ 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"/>
@@ -7932,11 +7936,19 @@ 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);
}
@@ -8386,6 +8398,8 @@ 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;
@@ -8485,6 +8499,8 @@ 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;
@@ -8855,7 +8871,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -13524,6 +13542,9 @@ var ts;
case 55 /* AtToken */:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -18991,22 +19012,24 @@ 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 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);
}
// 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); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
@@ -26761,7 +26784,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@@ -28202,7 +28225,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -29341,6 +29364,7 @@ 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);
}
@@ -29356,6 +29380,9 @@ 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 /* _ */;
}
@@ -29384,9 +29411,16 @@ 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 (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -30719,7 +30753,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -35983,7 +36017,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
@@ -37880,7 +37914,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
* we we emit variable statement 'var' should be dropped.
* when we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
if (!node || !isCurrentFileSystemExternalModule()) {
@@ -40347,13 +40381,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -40372,7 +40406,9 @@ var ts;
//
// We'll emit:
//
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@@ -42936,7 +42972,7 @@ var ts;
/* @internal */ ts.ioReadTime = 0;
/* @internal */ ts.ioWriteTime = 0;
/** The version of the TypeScript compiler release */
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -43025,12 +43061,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(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;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -43797,6 +43828,22 @@ 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;
@@ -43889,11 +43936,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 currentNodeModulesJsDepth = 0;
var 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.
var modulesWithElidedImports = {};
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
host = host || createCompilerHost(options);
@@ -44150,8 +44197,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -44603,9 +44649,19 @@ 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);
}
// 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) {
// 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) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -44623,6 +44679,7 @@ 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
@@ -44737,12 +44794,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -44751,8 +44805,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 (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@@ -45090,12 +45144,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",
@@ -47087,7 +47141,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:*/ startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -47353,14 +47407,6 @@ 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++) {
@@ -49205,6 +49251,7 @@ 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);
@@ -49296,6 +49343,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
@@ -49326,7 +49376,9 @@ var ts;
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: 0 /* Scan */;
: shouldRescanJsxText(n)
? 5 /* RescanJsxText */
: 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'
@@ -49361,6 +49413,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else if (expectedScanAction === 5 /* RescanJsxText */) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5 /* RescanJsxText */;
}
else {
lastScanAction = 0 /* Scan */;
}
@@ -52033,19 +52089,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
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);
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);
@@ -52080,14 +52137,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -52173,6 +52230,74 @@ 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;
@@ -58937,6 +59062,8 @@ 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; },
@@ -59562,7 +59689,7 @@ var ts;
//
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
@@ -59701,7 +59828,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return this.shimHost.getDirectories(path);
return JSON.parse(this.shimHost.getDirectories(path));
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));

View File

@@ -409,7 +409,10 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Modifier extends Node {
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
}
interface Identifier extends PrimaryExpression {
text: string;
@@ -1696,7 +1699,6 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@@ -1842,8 +1844,6 @@ 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,6 +1868,12 @@ 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

View File

@@ -1756,10 +1756,19 @@ 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) {
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -2070,6 +2079,8 @@ 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; },
@@ -2216,7 +2227,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
var wscriptSystem = {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -2235,7 +2246,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -2255,6 +2266,7 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -2444,7 +2456,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
}
return {
var nodeSystem = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -2500,7 +2512,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -2548,6 +2560,7 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -3304,8 +3317,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." },
@@ -6153,7 +6166,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 moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7916,15 +7929,6 @@ 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"/>
@@ -7932,11 +7936,19 @@ 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);
}
@@ -8386,6 +8398,8 @@ 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;
@@ -8485,6 +8499,8 @@ 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;
@@ -8855,7 +8871,9 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -13524,6 +13542,9 @@ var ts;
case 55 /* AtToken */:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -18991,22 +19012,24 @@ 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 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);
}
// 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); }));
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
@@ -26761,7 +26784,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@@ -28202,7 +28225,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (!node.body) {
if (noUnusedIdentifiers && !node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -29341,6 +29364,7 @@ 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);
}
@@ -29356,6 +29380,9 @@ 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 /* _ */;
}
@@ -29384,9 +29411,16 @@ 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 (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -30719,7 +30753,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -35983,7 +36017,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# sourceMappingURL=" + sourceMappingURL);
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
@@ -37880,7 +37914,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
* we we emit variable statement 'var' should be dropped.
* when we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
if (!node || !isCurrentFileSystemExternalModule()) {
@@ -40347,13 +40381,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("" + decoratedClassAlias);
write("let " + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -40372,7 +40406,9 @@ var ts;
//
// We'll emit:
//
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@@ -42936,7 +42972,7 @@ var ts;
/* @internal */ ts.ioReadTime = 0;
/* @internal */ ts.ioWriteTime = 0;
/** The version of the TypeScript compiler release */
ts.version = "2.0.0";
ts.version = "2.1.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -43025,12 +43061,7 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(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;
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -43797,6 +43828,22 @@ 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;
@@ -43889,11 +43936,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 currentNodeModulesJsDepth = 0;
var 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.
var modulesWithElidedImports = {};
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
host = host || createCompilerHost(options);
@@ -44150,8 +44197,7 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -44603,9 +44649,19 @@ 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);
}
// 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) {
// 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) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -44623,6 +44679,7 @@ 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
@@ -44737,12 +44794,9 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
currentNodeModulesDepth++;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -44751,8 +44805,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 (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@@ -45090,12 +45144,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",
@@ -47087,7 +47141,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:*/ startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -47353,14 +47407,6 @@ 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++) {
@@ -49205,6 +49251,7 @@ 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);
@@ -49296,6 +49343,9 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
@@ -49326,7 +49376,9 @@ var ts;
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: 0 /* Scan */;
: shouldRescanJsxText(n)
? 5 /* RescanJsxText */
: 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'
@@ -49361,6 +49413,10 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else if (expectedScanAction === 5 /* RescanJsxText */) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5 /* RescanJsxText */;
}
else {
lastScanAction = 0 /* Scan */;
}
@@ -52033,19 +52089,20 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
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);
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);
@@ -52080,14 +52137,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, 0, this));
nodes.push(createNode(token, pos, textPos, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -52173,6 +52230,74 @@ 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;
@@ -58937,6 +59062,8 @@ 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; },
@@ -59562,7 +59689,7 @@ var ts;
//
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = this;
var debugObjectHost = new Function("return this")();
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
@@ -59701,7 +59828,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return this.shimHost.getDirectories(path);
return JSON.parse(this.shimHost.getDirectories(path));
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));

View File

@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "2.0.0",
"version": "2.1.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@@ -30,6 +30,8 @@
},
"devDependencies": {
"@types/browserify": "latest",
"@types/convert-source-map": "latest",
"@types/chai": "latest",
"@types/del": "latest",
"@types/glob": "latest",
"@types/gulp": "latest",
@@ -42,12 +44,14 @@
"@types/minimatch": "latest",
"@types/minimist": "latest",
"@types/mkdirp": "latest",
"@types/mocha": "latest",
"@types/node": "latest",
"@types/q": "latest",
"@types/run-sequence": "latest",
"@types/through2": "latest",
"browserify": "latest",
"chai": "latest",
"convert-source-map": "latest",
"del": "latest",
"gulp": "latest",
"gulp-clone": "latest",
@@ -66,9 +70,9 @@
"mocha": "latest",
"mocha-fivemat-progress-reporter": "latest",
"run-sequence": "latest",
"sorcery": "latest",
"through2": "latest",
"ts-node": "latest",
"tsd": "latest",
"tslint": "next",
"typescript": "next"
},

View File

@@ -1,12 +0,0 @@
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "master",
"path": "typings",
"bundle": "typings/tsd.d.ts",
"installed": {
"node/node.d.ts": {
"commit": "5f480287834a2615274eea31574b713e64decf17"
}
}
}

View File

@@ -19,4 +19,6 @@ declare module "into-stream" {
export function obj(content: any): NodeJS.ReadableStream
}
export = IntoStream;
}
}
declare module "sorcery";

View File

@@ -3,8 +3,6 @@
/* @internal */
namespace ts {
export let bindTime = 0;
export const enum ModuleInstanceState {
NonInstantiated = 0,
Instantiated = 1,
@@ -91,9 +89,9 @@ namespace ts {
const binder = createBinder();
export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
const start = new Date().getTime();
const start = performance.mark();
binder(file, options);
bindTime += new Date().getTime() - start;
performance.measure("Bind", start);
}
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {

View File

@@ -15,8 +15,6 @@ namespace ts {
return node.id;
}
export let checkTime = 0;
export function getSymbolId(symbol: Symbol): number {
if (!symbol.id) {
symbol.id = nextSymbolId;
@@ -1000,7 +998,7 @@ namespace ts {
Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined");
if (!isBlockScopedNameDeclaredBeforeUse(<Declaration>getAncestor(declaration, SyntaxKind.VariableDeclaration), errorLocation)) {
if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(<Declaration>getAncestor(declaration, SyntaxKind.VariableDeclaration), errorLocation)) {
error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name));
}
}
@@ -3228,26 +3226,29 @@ namespace ts {
if (declaration.kind === SyntaxKind.ExportAssignment) {
return links.type = checkExpression((<ExportAssignment>declaration).expression);
}
if (declaration.flags & NodeFlags.JavaScriptFile && declaration.kind === SyntaxKind.JSDocPropertyTag && (<JSDocPropertyTag>declaration).typeExpression) {
return links.type = getTypeFromTypeNode((<JSDocPropertyTag>declaration).typeExpression.type);
}
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) {
return unknownType;
}
let type: Type = undefined;
// Handle module.exports = expr or this.p = expr
if (declaration.kind === SyntaxKind.BinaryExpression) {
type = getUnionType(map(symbol.declarations, (decl: BinaryExpression) => checkExpressionCached(decl.right)), /*subtypeReduction*/ true);
let type: Type;
// 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 === SyntaxKind.BinaryExpression ||
declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) {
const declaredTypes = map(symbol.declarations,
decl => decl.kind === SyntaxKind.BinaryExpression ?
checkExpressionCached((<BinaryExpression>decl).right) :
checkExpressionCached((<BinaryExpression>decl.parent).right));
type = getUnionType(declaredTypes, /*subtypeReduction*/ true);
}
else if (declaration.kind === SyntaxKind.PropertyAccessExpression) {
// Declarations only exist for property access expressions for certain
// special assignment kinds
if (declaration.parent.kind === SyntaxKind.BinaryExpression) {
// Handle exports.p = expr or className.prototype.method = expr
type = checkExpressionCached((<BinaryExpression>declaration.parent).right);
}
}
if (type === undefined) {
else {
type = getWidenedTypeForVariableLikeDeclaration(<VariableLikeDeclaration>declaration, /*reportErrors*/ true);
}
@@ -11954,7 +11955,7 @@ namespace ts {
function getInferredClassType(symbol: Symbol) {
const links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@@ -13609,7 +13610,7 @@ namespace ts {
checkAsyncFunctionReturnType(<FunctionLikeDeclaration>node);
}
}
if (!(<FunctionDeclaration>node).body) {
if (noUnusedIdentifiers && !(<FunctionDeclaration>node).body) {
checkUnusedTypeParameters(node);
}
}
@@ -14901,6 +14902,7 @@ namespace ts {
const parameter = <ParameterDeclaration>local.valueDeclaration;
if (compilerOptions.noUnusedParameters &&
!isParameterPropertyDeclaration(parameter) &&
!parameterIsThisKeyword(parameter) &&
!parameterNameStartsWithUnderscore(parameter)) {
error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name);
}
@@ -14914,6 +14916,10 @@ namespace ts {
}
}
function parameterIsThisKeyword(parameter: ParameterDeclaration) {
return parameter.name && (<Identifier>parameter.name).originalKeywordKind === SyntaxKind.ThisKeyword;
}
function parameterNameStartsWithUnderscore(parameter: ParameterDeclaration) {
return parameter.name && parameter.name.kind === SyntaxKind.Identifier && (<Identifier>parameter.name).text.charCodeAt(0) === CharacterCodes._;
}
@@ -14942,8 +14948,15 @@ namespace ts {
function checkUnusedTypeParameters(node: ClassDeclaration | ClassExpression | FunctionDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction | ConstructorDeclaration | SignatureDeclaration | InterfaceDeclaration) {
if (compilerOptions.noUnusedLocals && !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.
const symbol = getSymbolOfNode(node);
const lastDeclaration = symbol && symbol.declarations && lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (const typeParameter of node.typeParameters) {
if (!typeParameter.symbol.isReferenced) {
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
error(typeParameter.name, Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -16452,7 +16465,7 @@ namespace ts {
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
checkUnusedTypeParameters(node);
registerForUnusedIdentifiersCheck(node);
}
}
@@ -17349,11 +17362,11 @@ namespace ts {
}
function checkSourceFile(node: SourceFile) {
const start = new Date().getTime();
const start = performance.mark();
checkSourceFileWorker(node);
checkTime += new Date().getTime() - start;
performance.measure("Check", start);
}
// Fully type check a source file and collect the relevant diagnostics.

View File

@@ -27,6 +27,10 @@ namespace ts {
name: "diagnostics",
type: "boolean",
},
{
name: "extendedDiagnostics",
type: "boolean",
},
{
name: "emitBOM",
type: "boolean"
@@ -135,12 +139,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",
@@ -689,9 +693,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
@@ -1003,10 +1004,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

View File

@@ -1,4 +1,6 @@
/// <reference path="types.ts"/>
/// <reference path="performance.ts" />
/* @internal */
namespace ts {
@@ -902,10 +904,19 @@ namespace ts {
return true;
}
/* @internal */
export function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
/* @internal */
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
export function fileExtensionIs(path: string, extension: string): boolean {
const pathLen = path.length;
const extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsAny(path: string, extensions: string[]): boolean {
@@ -918,18 +929,35 @@ namespace ts {
return false;
}
// Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
// It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
// proof.
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) {
@@ -950,13 +978,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;
}
@@ -970,6 +998,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;
}
@@ -995,8 +1037,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 {
@@ -1234,26 +1284,28 @@ namespace ts {
export 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;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
}
function Symbol(flags: SymbolFlags, name: string) {
function Symbol(this: Symbol, flags: SymbolFlags, name: string) {
this.flags = flags;
this.name = name;
this.declarations = undefined;
}
function Type(checker: TypeChecker, flags: TypeFlags) {
function Type(this: Type, checker: TypeChecker, flags: TypeFlags) {
this.flags = flags;
}
function Signature(checker: TypeChecker) {
}
function Node(kind: SyntaxKind, pos: number, end: number) {
function Node(this: Node, kind: SyntaxKind, pos: number, end: number) {
this.kind = kind;
this.pos = pos;
this.end = end;
@@ -1263,6 +1315,8 @@ namespace ts {
export let objectAllocator: ObjectAllocator = {
getNodeConstructor: () => <any>Node,
getTokenConstructor: () => <any>Node,
getIdentifierConstructor: () => <any>Node,
getSourceFileConstructor: () => <any>Node,
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,

View File

@@ -2340,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
@@ -2804,11 +2808,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
},

View File

@@ -614,7 +614,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
const sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write(`//# sourceMappingURL=${sourceMappingURL}`);
write(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Sometimes tools can sometimes see this line as a source mapping url comment
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
@@ -2749,7 +2749,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
* 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
* we we emit variable statement 'var' should be dropped.
* when we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node: Node, isExported: boolean): boolean {
if (!node || !isCurrentFileSystemExternalModule()) {
@@ -4571,14 +4571,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function emitRestParameter(node: FunctionLikeDeclaration) {
if (languageVersion < ScriptTarget.ES6 && hasDeclaredRestParameter(node)) {
const restIndex = node.parameters.length - 1;
const restParam = node.parameters[restIndex];
const restParam = node.parameters[node.parameters.length - 1];
// A rest parameter cannot have a binding pattern, so let's just ignore it if it does.
if (isBindingPattern(restParam.name)) {
return;
}
const skipThisCount = node.parameters.length && (<Identifier>node.parameters[0].name).originalKeywordKind === SyntaxKind.ThisKeyword ? 1 : 0;
const restIndex = node.parameters.length - 1 - skipThisCount;
const tempName = createTempVariable(TempFlags._i).text;
writeLine();
emitLeadingComments(restParam);
@@ -4726,7 +4727,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write("(");
if (node) {
const parameters = node.parameters;
const skipCount = node.parameters.length && (<Identifier>node.parameters[0].name).text === "this" ? 1 : 0;
const skipCount = node.parameters.length && (<Identifier>node.parameters[0].name).originalKeywordKind === SyntaxKind.ThisKeyword ? 1 : 0;
const omitCount = languageVersion < ScriptTarget.ES6 && hasDeclaredRestParameter(node) ? 1 : 0;
emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false);
}
@@ -5503,16 +5504,15 @@ const _super = (function (geti, seti) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write(`${decoratedClassAlias}`);
write(`let ${decoratedClassAlias}`);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
}
else if (isES6ExportedDeclaration(node)) {
@@ -5530,7 +5530,9 @@ const _super = (function (geti, seti) {
//
// We'll emit:
//
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@@ -6155,10 +6157,11 @@ const _super = (function (geti, seti) {
if (valueDeclaration) {
const parameters = valueDeclaration.parameters;
const skipThisCount = parameters.length && (<Identifier>parameters[0].name).originalKeywordKind === SyntaxKind.ThisKeyword ? 1 : 0;
const parameterCount = parameters.length;
if (parameterCount > 0) {
for (let i = 0; i < parameterCount; i++) {
if (i > 0) {
if (parameterCount > skipThisCount) {
for (let i = skipThisCount; i < parameterCount; i++) {
if (i > skipThisCount) {
write(", ");
}

View File

@@ -2,15 +2,21 @@
/// <reference path="scanner.ts"/>
namespace ts {
/* @internal */ export let parseTime = 0;
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
export function createNode(kind: SyntaxKind, pos?: number, end?: number): Node {
if (kind === SyntaxKind.SourceFile) {
return new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === SyntaxKind.Identifier) {
return new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < SyntaxKind.FirstNode) {
return new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@@ -415,10 +421,10 @@ namespace ts {
}
export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false, scriptKind?: ScriptKind): SourceFile {
const start = new Date().getTime();
const start = performance.mark();
const result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
parseTime += new Date().getTime() - start;
performance.measure("Parse", start);
return result;
}
@@ -468,6 +474,8 @@ namespace ts {
// capture constructors in 'initializeState' to avoid null checks
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let sourceFile: SourceFile;
@@ -578,6 +586,8 @@ namespace ts {
function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, scriptKind: ScriptKind) {
NodeConstructor = objectAllocator.getNodeConstructor();
TokenConstructor = objectAllocator.getTokenConstructor();
IdentifierConstructor = objectAllocator.getIdentifierConstructor();
SourceFileConstructor = objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
@@ -1030,13 +1040,15 @@ namespace ts {
}
// note: this function creates only node
function createNode(kind: SyntaxKind, pos?: number): Node {
function createNode(kind: SyntaxKind, pos?: number): Node | Token | Identifier {
nodeCount++;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new NodeConstructor(kind, pos, pos);
return kind >= SyntaxKind.FirstNode ? new NodeConstructor(kind, pos, pos) :
kind === SyntaxKind.Identifier ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
}
function finishNode<T extends Node>(node: T, end?: number): T {
@@ -5125,7 +5137,7 @@ namespace ts {
}
flags |= modifierToFlag(modifierKind);
modifiers.push(finishNode(createNode(modifierKind, modifierStart)));
modifiers.push(finishNode(<Modifier>createNode(modifierKind, modifierStart)));
}
if (modifiers) {
modifiers.flags = flags;
@@ -5144,7 +5156,7 @@ namespace ts {
modifiers = <ModifiersArray>[];
modifiers.pos = modifierStart;
flags |= modifierToFlag(modifierKind);
modifiers.push(finishNode(createNode(modifierKind, modifierStart)));
modifiers.push(finishNode(<Modifier>createNode(modifierKind, modifierStart)));
modifiers.flags = flags;
modifiers.end = scanner.getStartPos();
}
@@ -6403,6 +6415,9 @@ namespace ts {
case SyntaxKind.AtToken:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;

109
src/compiler/performance.ts Normal file
View File

@@ -0,0 +1,109 @@
/*@internal*/
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());
}
/*@internal*/
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>;
let measures: Map<number>;
/**
* Emit a performance event if ts-profiler is connected. This is primarily used
* to generate heap snapshots.
*
* @param eventName A name for the event.
*/
export function emit(eventName: string) {
if (profilerEvent) {
profilerEvent(eventName);
}
}
/**
* 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.
*/
export function measure(measureName: string, marker: number) {
if (measures) {
measures[measureName] = (getProperty(measures, measureName) || 0) + (timestamp() - marker);
}
}
/**
* 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) {
return forEachKey(measures, key => cb(key, measures[key]));
}
/**
* Gets the total duration of all measurements with the supplied name.
*
* @param measureName The name of the measure whose durations should be accumulated.
*/
export function getDuration(measureName: string) {
return measures && getProperty(measures, measureName) || 0;
}
/** 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;
}
/** Disables (and clears) performance measurements for the compiler. */
export function disable() {
counters = undefined;
measures = undefined;
profilerEvent = undefined;
}
}

View File

@@ -3,13 +3,8 @@
/// <reference path="core.ts" />
namespace ts {
/* @internal */ export let programTime = 0;
/* @internal */ export let emitTime = 0;
/* @internal */ export let ioReadTime = 0;
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
export const version = "2.0.0";
export const version = "2.1.0";
const emptyArray: any[] = [];
@@ -112,13 +107,7 @@ namespace ts {
}
function moduleHasNonRelativeName(moduleName: string): boolean {
if (isRootedDiskPath(moduleName)) {
return false;
}
const i = moduleName.lastIndexOf("./", 1);
const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot);
return !startsWithDotSlashOrDotDotSlash;
return !(isRootedDiskPath(moduleName) || isExternalModuleNameRelative(moduleName));
}
interface ModuleResolutionState {
@@ -871,9 +860,9 @@ namespace ts {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
let text: string;
try {
const start = new Date().getTime();
const start = performance.mark();
text = sys.readFile(fileName, options.charset);
ioReadTime += new Date().getTime() - start;
performance.measure("I/O Read", start);
}
catch (e) {
if (onError) {
@@ -940,7 +929,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
const start = new Date().getTime();
const start = performance.mark();
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
if (isWatchSet(options) && sys.createHash && sys.getModifiedTime) {
@@ -950,7 +939,7 @@ namespace ts {
sys.writeFile(fileName, data, writeByteOrderMark);
}
ioWriteTime += new Date().getTime() - start;
performance.measure("I/O Write", start);
}
catch (e) {
if (onError) {
@@ -997,6 +986,29 @@ namespace ts {
return sortAndDeduplicateDiagnostics(diagnostics);
}
export interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
export function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string {
let output = "";
for (const diagnostic of diagnostics) {
if (diagnostic.file) {
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const fileName = diagnostic.file.fileName;
const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName));
output += `${ relativeFileName }(${ line + 1 },${ character + 1 }): `;
}
const category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) }${ host.getNewLine() }`;
}
return output;
}
export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string {
if (typeof messageText === "string") {
return messageText;
@@ -1095,16 +1107,16 @@ namespace 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.
const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
let currentNodeModulesJsDepth = 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> = {};
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
const sourceFilesFoundSearchingNodeModules: Map<boolean> = {};
const start = new Date().getTime();
const start = performance.mark();
host = host || createCompilerHost(options);
@@ -1203,7 +1215,7 @@ namespace ts {
verifyCompilerOptions();
programTime += new Date().getTime() - start;
performance.measure("Program", start);
return program;
@@ -1399,7 +1411,7 @@ namespace ts {
}
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult {
return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken));
return runWithCancellationToken(() => emitWorker(program, sourceFile, writeFileCallback, cancellationToken));
}
function isEmitBlocked(emitFileName: string): boolean {
@@ -1446,14 +1458,14 @@ namespace ts {
// checked is to not pass the file to getEmitResolver.
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
const start = new Date().getTime();
const start = performance.mark();
const emitResult = emitFiles(
emitResolver,
getEmitHost(writeFileCallback),
sourceFile);
emitTime += new Date().getTime() - start;
performance.measure("Emit", start);
return emitResult;
}
@@ -1918,9 +1930,21 @@ namespace ts {
reportFileNamesDifferOnlyInCasingError(fileName, file.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 && lookUp(sourceFilesFoundSearchingNodeModules, file.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file.path] = false;
if (!options.noResolve) {
processReferencedFiles(file, getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file);
}
modulesWithElidedImports[file.path] = false;
processImportedModules(file, getDirectoryPath(fileName));
}
// See if we need to reprocess the imports due to prior skipped imports
if (file && lookUp(modulesWithElidedImports, file.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
else if (file && lookUp(modulesWithElidedImports, file.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file.path] = false;
processImportedModules(file, getDirectoryPath(fileName));
}
@@ -1942,6 +1966,7 @@ namespace ts {
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
@@ -2075,13 +2100,10 @@ namespace ts {
const isJsFileFromNodeModules = isFromNodeModulesSearch && hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
currentNodeModulesDepth++;
}
const elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
const shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
@@ -2096,8 +2118,8 @@ namespace ts {
file.imports[i].end);
}
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
}
}
}
@@ -2178,6 +2200,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") {
@@ -2230,7 +2255,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));
@@ -2242,10 +2267,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
@@ -2253,9 +2278,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"));
}
}

View File

@@ -240,6 +240,8 @@ namespace ts {
return;
}
const start = performance.mark();
const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
// Convert the location to be one-based.
@@ -279,6 +281,8 @@ namespace ts {
}
updateLastEncodedAndRecordedSpans();
performance.measure("Source Map", start);
}
function getStartPos(range: TextRange) {

View File

@@ -182,7 +182,7 @@ namespace ts {
return matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
return {
const wscriptSystem: System = {
args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -201,7 +201,7 @@ namespace ts {
return fso.FolderExists(path);
},
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
if (!wscriptSystem.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -221,6 +221,7 @@ namespace ts {
}
}
};
return wscriptSystem;
}
function getNodeSystem(): System {
@@ -439,7 +440,7 @@ namespace ts {
return filter<string>(_fs.readdirSync(path), p => fileSystemEntryExists(combinePaths(path, p), FileSystemEntryKind.Directory));
}
return {
const nodeSystem: System = {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -501,7 +502,7 @@ namespace ts {
fileExists,
directoryExists,
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
if (!nodeSystem.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -549,6 +550,7 @@ namespace ts {
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem(): System {

View File

@@ -6,9 +6,19 @@ namespace ts {
fileWatcher?: FileWatcher;
}
let reportDiagnostic = reportDiagnosticSimply;
const defaultFormatDiagnosticsHost: FormatDiagnosticsHost = {
getCurrentDirectory: () => sys.getCurrentDirectory(),
getNewLine: () => sys.newLine,
getCanonicalFileName: createGetCanonicalFileName(sys.useCaseSensitiveFileNames)
};
function reportDiagnostics(diagnostics: Diagnostic[], host: CompilerHost): void {
let reportDiagnosticWorker = reportDiagnosticSimply;
function reportDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost) {
reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost);
}
function reportDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): void {
for (const diagnostic of diagnostics) {
reportDiagnostic(diagnostic, host);
}
@@ -101,23 +111,8 @@ namespace ts {
return <string>diagnostic.messageText;
}
function getRelativeFileName(fileName: string, host: CompilerHost): string {
return host ? convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : fileName;
}
function reportDiagnosticSimply(diagnostic: Diagnostic, host: CompilerHost): void {
let output = "";
if (diagnostic.file) {
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
const relativeFileName = getRelativeFileName(diagnostic.file.fileName, host);
output += `${ relativeFileName }(${ line + 1 },${ character + 1 }): `;
}
const category = DiagnosticCategory[diagnostic.category].toLowerCase();
output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`;
sys.write(output);
function reportDiagnosticSimply(diagnostic: Diagnostic, host: FormatDiagnosticsHost): void {
sys.write(ts.formatDiagnostics([diagnostic], host));
}
const redForegroundEscapeSequence = "\u001b[91m";
@@ -137,7 +132,7 @@ namespace ts {
return formatStyle + text + resetEscapeSequence;
}
function reportDiagnosticWithColorAndContext(diagnostic: Diagnostic, host: CompilerHost): void {
function reportDiagnosticWithColorAndContext(diagnostic: Diagnostic, host: FormatDiagnosticsHost): void {
let output = "";
if (diagnostic.file) {
@@ -145,7 +140,7 @@ namespace ts {
const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start);
const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length);
const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line;
const relativeFileName = getRelativeFileName(file.fileName, host);
const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName;
const hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
let gutterWidth = (lastLine + 1 + "").length;
@@ -272,7 +267,7 @@ namespace ts {
if (commandLine.options.locale) {
if (!isJSONSupported()) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors);
@@ -303,11 +298,11 @@ namespace ts {
if (commandLine.options.project) {
if (!isJSONSupported()) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (commandLine.fileNames.length !== 0) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
@@ -315,14 +310,14 @@ namespace ts {
if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) {
configFileName = combinePaths(fileOrDirectory, "tsconfig.json");
if (!sys.fileExists(configFileName)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
}
else {
configFileName = fileOrDirectory;
if (!sys.fileExists(configFileName)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
}
@@ -340,7 +335,7 @@ namespace ts {
if (isWatchSet(commandLine.options)) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* host */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (configFileName) {
@@ -385,7 +380,8 @@ namespace ts {
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options, configFileName);
const cwd = sys.getCurrentDirectory();
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), commandLine.options, getNormalizedAbsolutePath(configFileName, cwd));
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -393,7 +389,7 @@ namespace ts {
}
if (isWatchSet(configParseResult.options)) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* host */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
@@ -432,7 +428,7 @@ namespace ts {
}
if (compilerOptions.pretty) {
reportDiagnostic = reportDiagnosticWithColorAndContext;
reportDiagnosticWorker = reportDiagnosticWithColorAndContext;
}
// reset the cache of existing files
@@ -554,12 +550,8 @@ namespace ts {
}
function compile(fileNames: string[], compilerOptions: CompilerOptions, compilerHost: CompilerHost) {
ioReadTime = 0;
ioWriteTime = 0;
programTime = 0;
bindTime = 0;
checkTime = 0;
emitTime = 0;
const hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics;
if (hasDiagnostics) performance.enable();
const program = createProgram(fileNames, compilerOptions, compilerHost);
const exitStatus = compileProgram();
@@ -570,7 +562,7 @@ namespace ts {
});
}
if (compilerOptions.diagnostics) {
if (hasDiagnostics) {
const memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1;
reportCountStatistic("Files", program.getSourceFiles().length);
reportCountStatistic("Lines", countLines(program));
@@ -583,17 +575,28 @@ namespace ts {
reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K");
}
// Individual component times.
// Note: To match the behavior of previous versions of the compiler, the reported parse time includes
// I/O read time and processing time for triple-slash references and module imports, and the reported
// emit time includes I/O write time. We preserve this behavior so we can accurately compare times.
reportTimeStatistic("I/O read", ioReadTime);
reportTimeStatistic("I/O write", ioWriteTime);
reportTimeStatistic("Parse time", programTime);
reportTimeStatistic("Bind time", bindTime);
reportTimeStatistic("Check time", checkTime);
reportTimeStatistic("Emit time", emitTime);
const programTime = performance.getDuration("Program");
const bindTime = performance.getDuration("Bind");
const checkTime = performance.getDuration("Check");
const emitTime = performance.getDuration("Emit");
if (compilerOptions.extendedDiagnostics) {
performance.forEachMeasure((name, duration) => reportTimeStatistic(`${name} time`, duration));
}
else {
// Individual component times.
// Note: To match the behavior of previous versions of the compiler, the reported parse time includes
// I/O read time and processing time for triple-slash references and module imports, and the reported
// emit time includes I/O write time. We preserve this behavior so we can accurately compare times.
reportTimeStatistic("I/O read", performance.getDuration("I/O Read"));
reportTimeStatistic("I/O write", performance.getDuration("I/O Write"));
reportTimeStatistic("Parse time", programTime);
reportTimeStatistic("Bind time", bindTime);
reportTimeStatistic("Check time", checkTime);
reportTimeStatistic("Emit time", emitTime);
}
reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime);
performance.disable();
}
return { program, exitStatus };
@@ -657,7 +660,7 @@ namespace ts {
// Build up the list of examples.
const padding = makePadding(marginLength);
output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine;
output += padding + "tsc --out file.js file.ts" + sys.newLine;
output += padding + "tsc --outFile file.js file.ts" + sys.newLine;
output += padding + "tsc @args.txt" + sys.newLine;
output += sys.newLine;
@@ -757,7 +760,7 @@ namespace ts {
const currentDirectory = sys.getCurrentDirectory();
const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json"));
if (sys.fileExists(file)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* host */ undefined);
}
else {
const compilerOptions = extend(options, defaultInitCompilerOptions);
@@ -777,7 +780,7 @@ namespace ts {
}
sys.writeFile(file, JSON.stringify(configurations, undefined, 4));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* compilerHost */ undefined);
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* host */ undefined);
}
return;

View File

@@ -1,8 +1,10 @@
{
"compilerOptions": {
"noImplicitAny": true,
"noImplicitThis": true,
"removeComments": true,
"preserveConstEnums": true,
"pretty": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true,
"declaration": true,
@@ -10,6 +12,7 @@
},
"files": [
"core.ts",
"performance.ts",
"sys.ts",
"types.ts",
"scanner.ts",

View File

@@ -472,6 +472,10 @@ namespace ts {
flags: NodeFlags;
}
export interface Token extends Node {
__tokenTag: any;
}
// @kind(SyntaxKind.AbstractKeyword)
// @kind(SyntaxKind.AsyncKeyword)
// @kind(SyntaxKind.ConstKeyword)
@@ -482,7 +486,7 @@ namespace ts {
// @kind(SyntaxKind.PrivateKeyword)
// @kind(SyntaxKind.ProtectedKeyword)
// @kind(SyntaxKind.StaticKeyword)
export interface Modifier extends Node { }
export interface Modifier extends Token { }
// @kind(SyntaxKind.Identifier)
export interface Identifier extends PrimaryExpression {
@@ -2558,6 +2562,7 @@ namespace ts {
declaration?: boolean;
declarationDir?: string;
/* @internal */ diagnostics?: boolean;
/* @internal */ extendedDiagnostics?: boolean;
disableSizeLimit?: boolean;
emitBOM?: boolean;
emitDecoratorMetadata?: boolean;
@@ -2931,7 +2936,6 @@ namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];

View File

@@ -1218,7 +1218,7 @@ namespace ts {
export function isExternalModuleNameRelative(moduleName: string): boolean {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
return /^\.\.?($|[\\/])/.test(moduleName);
}
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
@@ -3113,13 +3113,4 @@ namespace ts {
export function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean {
return node.flags & NodeFlags.ParameterPropertyModifier && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent);
}
export function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
}

View File

@@ -50,7 +50,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
private makeUnitName(name: string, root: string) {
return ts.isRootedDiskPath(name) ? name : ts.combinePaths(root, name);
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, "/");
};
public checkTestCodeOutput(fileName: string) {

View File

@@ -1,179 +0,0 @@
// Type definitions for chai 1.7.2
// Project: http://chaijs.com/
// Definitions by: Jed Hunsaker <https://github.com/jedhunsaker/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
declare module chai {
function expect(target: any, message?: string): Expect;
// Provides a way to extend the internals of Chai
function use(fn: (chai: any, utils: any) => void): any;
interface ExpectStatic {
(target: any): Expect;
}
interface Assertions {
attr(name: string, value?: string): any;
css(name: string, value?: string): any;
data(name: string, value?: string): any;
class(className: string): any;
id(id: string): any;
html(html: string): any;
text(text: string): any;
value(value: string): any;
visible: any;
hidden: any;
selected: any;
checked: any;
disabled: any;
empty: any;
exist: any;
}
interface Expect extends LanguageChains, NumericComparison, TypeComparison, Assertions {
not: Expect;
deep: Deep;
a: TypeComparison;
an: TypeComparison;
include: Include;
contain: Include;
ok: Expect;
true: Expect;
false: Expect;
null: Expect;
undefined: Expect;
exist: Expect;
empty: Expect;
arguments: Expect;
Arguments: Expect;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
length: Length;
lengthOf: Length;
match(RegularExpression: RegExp, message?: string): Expect;
string(string: string, message?: string): Expect;
keys: Keys;
key(string: string): Expect;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo(method: string, message?: string): Expect;
itself: Expect;
satisfy(matcher: Function, message?: string): Expect;
closeTo(expected: number, delta: number, message?: string): Expect;
members: Members;
}
interface LanguageChains {
to: Expect;
be: Expect;
been: Expect;
is: Expect;
that: Expect;
and: Expect;
have: Expect;
with: Expect;
at: Expect;
of: Expect;
same: Expect;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Expect;
}
interface NumberComparer {
(value: number, message?: string): Expect;
}
interface TypeComparison {
(type: string, message?: string): Expect;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Expect;
}
interface Deep {
equal: Equal;
property: Property;
}
interface Equal {
(value: any, message?: string): Expect;
}
interface Property {
(name: string, value?: any, message?: string): Expect;
}
interface OwnProperty {
(name: string, message?: string): Expect;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Expect;
}
interface Include {
(value: Object, message?: string): Expect;
(value: string, message?: string): Expect;
(value: number, message?: string): Expect;
keys: Keys;
members: Members;
}
interface Keys {
(...keys: string[]): Expect;
(keys: any[]): Expect;
}
interface Members {
(set: any[], message?: string): Expect;
}
interface Throw {
(): Expect;
(expected: string, message?: string): Expect;
(expected: RegExp, message?: string): Expect;
(constructor: Error, expected?: string, message?: string): Expect;
(constructor: Error, expected?: RegExp, message?: string): Expect;
(constructor: Function, expected?: string, message?: string): Expect;
(constructor: Function, expected?: RegExp, message?: string): Expect;
}
function assert(expression: any, message?: string): void;
module assert {
function equal(actual: any, expected: any, message?: string): void;
function notEqual(actual: any, expected: any, message?: string): void;
function deepEqual<T>(actual: T, expected: T, message?: string): void;
function notDeepEqual<T>(actual: T, expected: T, message?: string): void;
function lengthOf(object: any[], length: number, message?: string): void;
function isTrue(value: any, message?: string): void;
function isFalse(value: any, message?: string): void;
function isOk(actual: any, message?: string): void;
function isUndefined(value: any, message?: string): void;
function isDefined(value: any, message?: string): void;
}
}

View File

@@ -1,45 +0,0 @@
// Type definitions for mocha 1.9.0
// Project: http://visionmedia.github.io/mocha/
// Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
declare var describe : {
(description: string, spec: () => void): void;
only(description: string, spec: () => void): void;
skip(description: string, spec: () => void): void;
timeout(ms: number): void;
}
declare var it: {
(expectation: string, assertion?: () => void): void;
(expectation: string, assertion?: (done: () => void) => void): void;
only(expectation: string, assertion?: () => void): void;
only(expectation: string, assertion?: (done: () => void) => void): void;
skip(expectation: string, assertion?: () => void): void;
skip(expectation: string, assertion?: (done: () => void) => void): void;
timeout(ms: number): void;
};
/** Runs once before any 'it' blocks in the current 'describe' are run */
declare function before(action: () => void): void;
/** Runs once before any 'it' blocks in the current 'describe' are run */
declare function before(action: (done: () => void) => void): void;
/** Runs once after all 'it' blocks in the current 'describe' are run */
declare function after(action: () => void): void;
/** Runs once after all 'it' blocks in the current 'describe' are run */
declare function after(action: (done: () => void) => void): void;
/** Runs before each individual 'it' block in the current 'describe' is run */
declare function beforeEach(action: () => void): void;
/** Runs before each individual 'it' block in the current 'describe' is run */
declare function beforeEach(action: (done: () => void) => void): void;
/** Runs after each individual 'it' block in the current 'describe' is run */
declare function afterEach(action: () => void): void;
/** Runs after each individual 'it' block in the current 'describe' is run */
declare function afterEach(action: (done: () => void) => void): void;

File diff suppressed because it is too large Load Diff

View File

@@ -18,12 +18,13 @@
/// <reference path="..\services\shims.ts" />
/// <reference path="..\server\session.ts" />
/// <reference path="..\server\client.ts" />
/// <reference path="..\server\node.d.ts" />
/// <reference path="external\mocha.d.ts"/>
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
/// <reference path="virtualFileSystem.ts" />
/// <reference types="node" />
/// <reference types="mocha" />
/// <reference types="chai" />
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
@@ -32,7 +33,13 @@
var _chai: typeof chai = require("chai");
var assert: typeof _chai.assert = _chai.assert;
declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(undefined);
var global: NodeJS.Global = <any>Function("return this").call(undefined);
declare namespace NodeJS {
export interface Global {
WScript: typeof WScript;
ActiveXObject: typeof ActiveXObject;
}
}
/* tslint:enable:no-var-keyword */
namespace Utils {
@@ -57,7 +64,7 @@ namespace Utils {
export let currentExecutionEnvironment = getExecutionEnvironment();
const Buffer: BufferConstructor = currentExecutionEnvironment !== ExecutionEnvironment.Browser
const Buffer: typeof global.Buffer = currentExecutionEnvironment !== ExecutionEnvironment.Browser
? require("buffer").Buffer
: undefined;
@@ -127,7 +134,7 @@ namespace Utils {
export function memoize<T extends Function>(f: T): T {
const cache: { [idx: string]: any } = {};
return <any>(function() {
return <any>(function(this: any) {
const key = Array.prototype.join.call(arguments);
const cachedResult = cache[key];
if (cachedResult) {
@@ -1370,31 +1377,27 @@ namespace Harness {
writeByteOrderMark: boolean;
}
function stringEndsWith(str: string, end: string) {
return str.substr(str.length - end.length) === end;
}
export function isTS(fileName: string) {
return stringEndsWith(fileName, ".ts");
return ts.endsWith(fileName, ".ts");
}
export function isTSX(fileName: string) {
return stringEndsWith(fileName, ".tsx");
return ts.endsWith(fileName, ".tsx");
}
export function isDTS(fileName: string) {
return stringEndsWith(fileName, ".d.ts");
return ts.endsWith(fileName, ".d.ts");
}
export function isJS(fileName: string) {
return stringEndsWith(fileName, ".js");
return ts.endsWith(fileName, ".js");
}
export function isJSX(fileName: string) {
return stringEndsWith(fileName, ".jsx");
return ts.endsWith(fileName, ".jsx");
}
export function isJSMap(fileName: string) {
return stringEndsWith(fileName, ".js.map") || stringEndsWith(fileName, ".jsx.map");
return ts.endsWith(fileName, ".js.map") || ts.endsWith(fileName, ".jsx.map");
}
/** Contains the code and errors of a compilation and some helper methods to check its status. */

View File

@@ -274,7 +274,7 @@ namespace Harness.LanguageService {
getCompilationSettings(): string { return JSON.stringify(this.nativeHost.getCompilationSettings()); }
getCancellationToken(): ts.HostCancellationToken { return this.nativeHost.getCancellationToken(); }
getCurrentDirectory(): string { return this.nativeHost.getCurrentDirectory(); }
getDirectories(path: string) { return this.nativeHost.getDirectories(path); }
getDirectories(path: string): string { return JSON.stringify(this.nativeHost.getDirectories(path)); }
getDefaultLibFileName(): string { return this.nativeHost.getDefaultLibFileName(); }
getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); }
getScriptSnapshot(fileName: string): ts.ScriptSnapshotShim {

View File

@@ -328,7 +328,7 @@ class ProjectRunner extends RunnerBase {
if (Harness.Compiler.isJS(fileName)) {
// Make sure if there is URl we have it cleaned up
const indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
const indexOfSourceMapUrl = data.lastIndexOf(`//# ${"sourceMappingURL"}=`); // This line can be seen as a sourceMappingURL comment
if (indexOfSourceMapUrl !== -1) {
data = data.substring(0, indexOfSourceMapUrl + 21) + cleanProjectUrl(data.substring(indexOfSourceMapUrl + 21));
}
@@ -479,17 +479,27 @@ class ProjectRunner extends RunnerBase {
it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (testCase.baselineCheck) {
const errs: Error[] = [];
ts.forEach(compilerResult.outputFiles, outputFile => {
Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return Harness.IO.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
}
});
// 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, () => {
try {
return Harness.IO.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
}
});
}
catch (e) {
errs.push(e);
}
});
if (errs.length) {
throw Error(errs.join("\n "));
}
}
});

View File

@@ -193,7 +193,7 @@ if (taskConfigsFolder) {
for (let i = 0; i < workerCount; i++) {
const startPos = i * chunkSize;
const len = Math.min(chunkSize, files.length - startPos);
if (len !== 0) {
if (len > 0) {
workerConfigs[i].tasks.push({
runner: runner.kind(),
files: files.slice(startPos, startPos + len)
@@ -214,5 +214,5 @@ else {
}
if (!runUnitTests) {
// patch `describe` to skip unit tests
describe = <any>describe.skip;
}
describe = <any>(function () { });
}

94
src/harness/tsconfig.json Normal file
View File

@@ -0,0 +1,94 @@
{
"compilerOptions": {
"noImplicitAny": true,
"pretty": true,
"removeComments": false,
"preserveConstEnums": true,
"outFile": "../../built/local/run.js",
"sourceMap": true,
"declaration": false,
"stripInternal": true,
"types": [
"node", "mocha", "chai"
]
},
"files": [
"../compiler/core.ts",
"../compiler/performance.ts",
"../compiler/sys.ts",
"../compiler/types.ts",
"../compiler/scanner.ts",
"../compiler/parser.ts",
"../compiler/utilities.ts",
"../compiler/binder.ts",
"../compiler/checker.ts",
"../compiler/sourcemap.ts",
"../compiler/declarationEmitter.ts",
"../compiler/emitter.ts",
"../compiler/program.ts",
"../compiler/commandLineParser.ts",
"../compiler/diagnosticInformationMap.generated.ts",
"../services/breakpoints.ts",
"../services/navigateTo.ts",
"../services/navigationBar.ts",
"../services/outliningElementsCollector.ts",
"../services/patternMatcher.ts",
"../services/services.ts",
"../services/shims.ts",
"../services/signatureHelp.ts",
"../services/utilities.ts",
"../services/jsTyping.ts",
"../services/formatting/formatting.ts",
"../services/formatting/formattingContext.ts",
"../services/formatting/formattingRequestKind.ts",
"../services/formatting/formattingScanner.ts",
"../services/formatting/references.ts",
"../services/formatting/rule.ts",
"../services/formatting/ruleAction.ts",
"../services/formatting/ruleDescriptor.ts",
"../services/formatting/ruleFlag.ts",
"../services/formatting/ruleOperation.ts",
"../services/formatting/ruleOperationContext.ts",
"../services/formatting/rules.ts",
"../services/formatting/rulesMap.ts",
"../services/formatting/rulesProvider.ts",
"../services/formatting/smartIndenter.ts",
"../services/formatting/tokenRange.ts",
"harness.ts",
"sourceMapRecorder.ts",
"harnessLanguageService.ts",
"fourslash.ts",
"runnerbase.ts",
"compilerRunner.ts",
"typeWriter.ts",
"fourslashRunner.ts",
"projectsRunner.ts",
"loggedIO.ts",
"rwcRunner.ts",
"test262Runner.ts",
"runner.ts",
"../server/protocol.d.ts",
"../server/session.ts",
"../server/client.ts",
"../server/editorServices.ts",
"./unittests/incrementalParser.ts",
"./unittests/jsDocParsing.ts",
"./unittests/services/colorization.ts",
"./unittests/services/documentRegistry.ts",
"./unittests/services/preProcessFile.ts",
"./unittests/services/patternMatcher.ts",
"./unittests/session.ts",
"./unittests/versionCache.ts",
"./unittests/convertToBase64.ts",
"./unittests/transpile.ts",
"./unittests/reuseProgramStructure.ts",
"./unittests/cachingInServerLSHost.ts",
"./unittests/moduleResolution.ts",
"./unittests/tsconfigParsing.ts",
"./unittests/commandLineParsing.ts",
"./unittests/convertCompilerOptionsFromJson.ts",
"./unittests/convertTypingOptionsFromJson.ts",
"./unittests/tsserverProjectSystem.ts",
"./unittests/matchFiles.ts"
]
}

View File

@@ -1,4 +1,4 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
interface File {
@@ -108,6 +108,8 @@ namespace ts {
let diags = project.compilerService.languageService.getSemanticDiagnostics(imported.name);
assert.equal(diags.length, 1);
let content = rootScriptInfo.getText();
const originalFileExists = serverHost.fileExists;
{
// patch fileExists to make sure that disk is not touched
@@ -118,7 +120,8 @@ namespace ts {
const newContent = `import {x} from "f1"
var x: string = 1;`;
rootScriptInfo.editContent(0, rootScriptInfo.content.length, newContent);
rootScriptInfo.editContent(0, content.length, newContent);
content = newContent;
// trigger synchronization to make sure that import will be fetched from the cache
diags = project.compilerService.languageService.getSemanticDiagnostics(imported.name);
// ensure file has correct number of errors after edit
@@ -135,7 +138,8 @@ namespace ts {
return originalFileExists.call(serverHost, fileName);
};
const newContent = `import {x} from "f2"`;
rootScriptInfo.editContent(0, rootScriptInfo.content.length, newContent);
rootScriptInfo.editContent(0, content.length, newContent);
content = newContent;
try {
// trigger synchronization to make sure that LSHost will try to find 'f2' module on disk
@@ -160,7 +164,8 @@ namespace ts {
};
const newContent = `import {x} from "f1"`;
rootScriptInfo.editContent(0, rootScriptInfo.content.length, newContent);
rootScriptInfo.editContent(0, content.length, newContent);
content = newContent;
project.compilerService.languageService.getSemanticDiagnostics(imported.name);
assert.isTrue(fileExistsCalled);
@@ -205,7 +210,7 @@ namespace ts {
};
const { project, rootScriptInfo } = createProject(root.name, serverHost);
const content = rootScriptInfo.getText();
let diags = project.compilerService.languageService.getSemanticDiagnostics(root.name);
assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called");
assert.isTrue(diags.length === 1, "one diagnostic expected");
@@ -214,7 +219,7 @@ namespace ts {
// assert that import will success once file appear on disk
fileMap[imported.name] = imported;
fileExistsCalledForBar = false;
rootScriptInfo.editContent(0, rootScriptInfo.content.length, `import {y} from "bar"`);
rootScriptInfo.editContent(0, content.length, `import {y} from "bar"`);
diags = project.compilerService.languageService.getSemanticDiagnostics(root.name);
assert.isTrue(fileExistsCalledForBar, "'fileExists' should be called");

View File

@@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\compiler\commandLineParser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("parseCommandLine", () => {

View File

@@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\compiler\commandLineParser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("convertCompilerOptionsFromJson", () => {

View File

@@ -1,4 +1,4 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
describe("convertToBase64", () => {

View File

@@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\compiler\commandLineParser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("convertTypingOptionsFromJson", () => {

View File

@@ -1,5 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\src\compiler\parser.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\parser.ts" />
namespace ts {
ts.disableIncrementalParsing = false;

View File

@@ -1,7 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\src\harness\external\chai.d.ts" />
/// <reference path="..\..\..\src\compiler\parser.ts" />
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\compiler\parser.ts" />
/// <reference path="..\harness.ts" />
namespace ts {
describe("JSDocParsing", () => {
@@ -986,7 +984,7 @@ namespace ts {
});
describe("DocComments", () => {
function parsesCorrectly(content: string, expected: string) {
function parsesCorrectly(content: string, expected: string | {}) {
const comment = parseIsolatedJSDocComment(content);
if (!comment) {
Debug.fail("Comment failed to parse entirely");
@@ -995,30 +993,46 @@ namespace ts {
Debug.fail("Comment has at least one diagnostic: " + comment.diagnostics[0].messageText);
}
const result = JSON.stringify(comment.jsDocComment, (k, v) => {
return v && v.pos !== undefined
? JSON.parse(Utils.sourceFileToJSON(v))
: v;
}, 4);
const result = toJsonString(comment.jsDocComment);
if (result !== expected) {
const expectedString = typeof expected === "string"
? expected
: toJsonString(expected);
if (result !== expectedString) {
// Turn on a human-readable diff
if (typeof require !== "undefined") {
const chai = require("chai");
chai.config.showDiff = true;
chai.expect(JSON.parse(result)).equal(JSON.parse(expected));
// Use deep equal to compare key value data instead of the two objects
chai.expect(JSON.parse(result)).deep.equal(JSON.parse(expectedString));
}
else {
assert.equal(result, expected);
assert.equal(result, expectedString);
}
}
}
function toJsonString(obj: {}) {
return JSON.stringify(obj, (k, v) => {
return v && v.pos !== undefined
? JSON.parse(Utils.sourceFileToJSON(v))
: v;
}, 4);
}
function parsesIncorrectly(content: string) {
const type = parseIsolatedJSDocComment(content);
assert.isTrue(!type || type.diagnostics.length > 0);
}
function reIndentJSDocComment(jsdocComment: string) {
const result = jsdocComment
.replace(/[\t ]*\/\*\*/, "/**")
.replace(/[\t ]*\*\s?@/g, " * @")
.replace(/[\t ]*\*\s?\//, " */");
return result;
}
describe("parsesIncorrectly", () => {
it("emptyComment", () => {
parsesIncorrectly("/***/");
@@ -2216,6 +2230,152 @@ namespace ts {
}
}`);
});
it("typedefTagWithChildrenTags", () => {
const content =
`/**
* @typedef People
* @type {Object}
* @property {number} age
* @property {string} name
*/`;
const expected = {
"end": 102,
"kind": "JSDocComment",
"pos": 0,
"tags": {
"0": {
"atToken": {
"end": 9,
"kind": "AtToken",
"pos": 8
},
"end": 97,
"jsDocTypeLiteral": {
"end": 97,
"jsDocPropertyTags": [
{
"atToken": {
"end": 48,
"kind": "AtToken",
"pos": 46
},
"end": 69,
"kind": "JSDocPropertyTag",
"name": {
"end": 69,
"kind": "Identifier",
"pos": 66,
"text": "age"
},
"pos": 46,
"tagName": {
"end": 56,
"kind": "Identifier",
"pos": 48,
"text": "property"
},
"typeExpression": {
"end": 65,
"kind": "JSDocTypeExpression",
"pos": 57,
"type": {
"end": 64,
"kind": "NumberKeyword",
"pos": 58
}
}
},
{
"atToken": {
"end": 75,
"kind": "AtToken",
"pos": 73
},
"end": 97,
"kind": "JSDocPropertyTag",
"name": {
"end": 97,
"kind": "Identifier",
"pos": 93,
"text": "name"
},
"pos": 73,
"tagName": {
"end": 83,
"kind": "Identifier",
"pos": 75,
"text": "property"
},
"typeExpression": {
"end": 92,
"kind": "JSDocTypeExpression",
"pos": 84,
"type": {
"end": 91,
"kind": "StringKeyword",
"pos": 85
}
}
}
],
"jsDocTypeTag": {
"atToken": {
"end": 29,
"kind": "AtToken",
"pos": 27
},
"end": 42,
"kind": "JSDocTypeTag",
"pos": 27,
"tagName": {
"end": 33,
"kind": "Identifier",
"pos": 29,
"text": "type"
},
"typeExpression": {
"end": 42,
"kind": "JSDocTypeExpression",
"pos": 34,
"type": {
"end": 41,
"kind": "JSDocTypeReference",
"name": {
"end": 41,
"kind": "Identifier",
"pos": 35,
"text": "Object"
},
"pos": 35
}
}
},
"kind": "JSDocTypeLiteral",
"pos": 23
},
"kind": "JSDocTypedefTag",
"name": {
"end": 23,
"kind": "Identifier",
"pos": 17,
"text": "People"
},
"pos": 8,
"tagName": {
"end": 16,
"kind": "Identifier",
"pos": 9,
"text": "typedef"
}
},
"end": 97,
"length": 1,
"pos": 8
}
};
parsesCorrectly(reIndentJSDocComment(content), expected);
});
});
});
});

View File

@@ -1,6 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\src\harness\harness.ts" />
/// <reference path="..\..\..\src\harness\virtualFileSystem.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\virtualFileSystem.ts" />
namespace ts {
const caseInsensitiveBasePath = "c:/dev/";
@@ -24,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"
]);
@@ -76,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", () => {
@@ -727,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: [
@@ -952,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 = {
@@ -1146,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);
});
});
});
});
}

View File

@@ -1,11 +1,4 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path='..\..\..\src\harness\harness.ts' />
declare namespace chai.assert {
/* tslint:disable no-unused-variable */
function deepEqual(actual: any, expected: any): void;
/* tslint:enable no-unused-variable */
}
/// <reference path="..\harness.ts" />
namespace ts {
function diagnosticToString(diagnostic: Diagnostic) {

View File

@@ -1,6 +1,5 @@
/// <reference path="..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path='..\..\..\src\harness\harness.ts' />
/// <reference path="..\..\..\src\harness\harnessLanguageService.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\harness\harnessLanguageService.ts" />
namespace ts {

View File

@@ -1,5 +1,4 @@
/// <reference path="..\..\..\..\src\harness\external\mocha.d.ts" />
/// <reference path="..\..\..\..\src\harness\harnessLanguageService.ts" />
/// <reference path="..\..\harnessLanguageService.ts" />
interface ClassificationEntry {
value: any;

View File

@@ -1,4 +1,4 @@
///<reference path='..\..\..\..\src\harness\harness.ts' />
/// <reference path="..\..\harness.ts" />
describe("DocumentRegistry", () => {
it("documents are shared between projects", () => {

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