Merge branch 'master' into walk_symbol

This commit is contained in:
Andy Hanson
2016-09-09 12:45:50 -07:00
2312 changed files with 117575 additions and 44248 deletions
+2
View File
@@ -9,12 +9,14 @@ test-args.txt
\#*\#
.\#*
tests/baselines/local/*
tests/baselines/local.old/*
tests/services/baselines/local/*
tests/baselines/prototyping/local/*
tests/baselines/rwc/*
tests/baselines/test262/*
tests/baselines/reference/projectOutput/*
tests/baselines/local/projectOutput/*
tests/baselines/reference/testresults.tap
tests/services/baselines/prototyping/local/*
tests/services/browser/typescriptServices.js
scripts/authors.js
+1 -1
View File
@@ -23,7 +23,7 @@ matrix:
branches:
only:
- master
- transforms
- release.2.0
install:
- npm uninstall typescript
+3
View File
@@ -39,6 +39,8 @@ const gulp = helpMaker(originalGulp);
const mochaParallel = require("./scripts/mocha-parallel.js");
const {runTestsInParallel} = mochaParallel;
Error.stackTraceLimit = 1000;
const cmdLineOptions = minimist(process.argv.slice(2), {
boolean: ["debug", "light", "colors", "lint", "soft"],
string: ["browser", "tests", "host", "reporter"],
@@ -727,6 +729,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo
sourcemaps: {
"built/local/_stream_0.js": originalMap,
"built/local/bundle.js": maps,
"node_modules/source-map-support/source-map-support.js": undefined,
}
});
const finalMap = chain.apply();
+74 -19
View File
@@ -64,7 +64,20 @@ var compilerSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
"factory.ts",
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/module/es6.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/generators.ts",
"transformers/es6.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -85,7 +98,20 @@ var servicesSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
"factory.ts",
"visitor.ts",
"transformers/destructuring.ts",
"transformers/ts.ts",
"transformers/module/es6.ts",
"transformers/module/system.ts",
"transformers/module/module.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/generators.ts",
"transformers/es6.ts",
"transformer.ts",
"sourcemap.ts",
"comments.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -94,15 +120,27 @@ var servicesSources = [
].map(function (f) {
return path.join(compilerDirectory, f);
}).concat([
"types.ts",
"utilities.ts",
"breakpoints.ts",
"classifier.ts",
"completions.ts",
"documentHighlights.ts",
"findAllReferences.ts",
"goToDefinition.ts",
"jsDoc.ts",
"jsTyping.ts",
"navigateTo.ts",
"navigationBar.ts",
"outliningElementsCollector.ts",
"patternMatcher.ts",
"preProcess.ts",
"rename.ts",
"services.ts",
"shims.ts",
"signatureHelp.ts",
"utilities.ts",
"symbolDisplay.ts",
"transpile.ts",
"formatting/formatting.ts",
"formatting/formattingContext.ts",
"formatting/formattingRequestKind.ts",
@@ -307,7 +345,10 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
* @param callback: a function to execute after the compilation process ends
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) {
file(outFile, prereqs, function () {
file(outFile, prereqs, function() {
if (process.env.USE_TRANSFORMS === "false") {
useBuiltCompiler = false;
}
var startCompileTime = mark();
opts = opts || {};
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
@@ -745,8 +786,14 @@ function cleanTestDirs() {
}
// used to pass data from jake command line directly to run.js
function writeTestConfigFile(tests, light, taskConfigsFolder, workerCount) {
var testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light: light, workerCount: workerCount, taskConfigsFolder: taskConfigsFolder });
function writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit) {
var testConfigContents = JSON.stringify({
test: tests ? [tests] : undefined,
light: light,
workerCount: workerCount,
taskConfigsFolder: taskConfigsFolder,
stackTraceLimit: stackTraceLimit
});
fs.writeFileSync('test.config', testConfigContents);
}
@@ -757,10 +804,15 @@ function deleteTemporaryProjectOutput() {
}
function runConsoleTests(defaultReporter, runInParallel) {
cleanTestDirs();
var dirty = process.env.dirty;
if (!dirty) {
cleanTestDirs();
}
var debug = process.env.debug || process.env.d;
tests = process.env.test || process.env.tests || process.env.t;
var light = process.env.light || false;
var stackTraceLimit = process.env.stackTraceLimit;
var testConfigFile = 'test.config';
if (fs.existsSync(testConfigFile)) {
fs.unlinkSync(testConfigFile);
@@ -780,7 +832,7 @@ function runConsoleTests(defaultReporter, runInParallel) {
}
if (tests || light || taskConfigsFolder) {
writeTestConfigFile(tests, light, taskConfigsFolder, workerCount);
writeTestConfigFile(tests, light, taskConfigsFolder, workerCount, stackTraceLimit);
}
if (tests && tests.toLocaleLowerCase() === "rwc") {
@@ -849,7 +901,7 @@ function runConsoleTests(defaultReporter, runInParallel) {
}
}
function runLinter() {
if (!lintFlag) {
if (!lintFlag || dirty) {
return;
}
var lint = jake.Task['lint'];
@@ -866,8 +918,8 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio
runConsoleTests('min', /*runInParallel*/ true);
}, { async: true });
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false lint=true bail=false.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function () {
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false lint=true bail=false dirty=false.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function() {
runConsoleTests('mocha-fivemat-progress-reporter', /*runInParallel*/ false);
}, { async: true });
@@ -884,8 +936,8 @@ var nodeServerInFile = "tests/webTestServer.ts";
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true });
desc("Runs browserify on run.js to produce a file suitable for running tests in the browser");
task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function () {
var cmd = 'browserify built/local/run.js -d -o built/local/bundle.js';
task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() {
var cmd = 'browserify built/local/run.js -t ./scripts/browserify-optional -d -o built/local/bundle.js';
exec(cmd);
}, { async: true });
@@ -951,15 +1003,18 @@ function acceptBaseline(containerFolder) {
var deleteEnding = '.delete';
for (var i in files) {
var filename = files[i];
if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) {
filename = filename.substr(0, filename.length - deleteEnding.length);
fs.unlinkSync(path.join(targetFolder, filename));
} else {
var target = path.join(targetFolder, filename);
if (fs.existsSync(target)) {
fs.unlinkSync(target);
var fullLocalPath = path.join(sourceFolder, filename);
if (fs.statSync(fullLocalPath).isFile()) {
if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) {
filename = filename.substr(0, filename.length - deleteEnding.length);
fs.unlinkSync(path.join(targetFolder, filename));
} else {
var target = path.join(targetFolder, filename);
if (fs.existsSync(target)) {
fs.unlinkSync(target);
}
fs.renameSync(path.join(sourceFolder, filename), target);
}
fs.renameSync(path.join(sourceFolder, filename), target);
}
}
}
+76 -120
View File
@@ -825,17 +825,10 @@ var ts;
return true;
}
ts.containsPath = containsPath;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
return path.length > extension.length && endsWith(path, extension);
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -1100,8 +1093,6 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@@ -1233,7 +1224,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
var wscriptSystem = {
return {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -1252,7 +1243,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!wscriptSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -1272,7 +1263,6 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -1445,7 +1435,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
var nodeSystem = {
return {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -1495,7 +1485,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -1543,7 +1533,6 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -2293,8 +2282,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@@ -4847,7 +4836,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return /^\.\.?($|[\\/])/.test(moduleName);
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -6355,24 +6344,25 @@ var ts;
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@@ -6795,8 +6785,6 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -6822,8 +6810,6 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@@ -7130,9 +7116,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -10908,9 +10892,6 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -15437,18 +15418,17 @@ var ts;
if (declaration.kind === 235) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
var type = undefined;
if (declaration.kind === 187 ||
declaration.kind === 172 && declaration.parent.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
if (declaration.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172) {
if (declaration.parent.kind === 187) {
type = checkExpressionCached(declaration.parent.right);
}
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@@ -21955,7 +21935,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@@ -23175,7 +23155,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (noUnusedIdentifiers && !node.body) {
if (!node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -24071,7 +24051,6 @@ var ts;
var parameter = local_1.valueDeclaration;
if (compilerOptions.noUnusedParameters &&
!ts.isParameterPropertyDeclaration(parameter) &&
!parameterIsThisKeyword(parameter) &&
!parameterNameStartsWithUnderscore(parameter)) {
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
}
@@ -24087,9 +24066,6 @@ var ts;
}
}
}
function parameterIsThisKeyword(parameter) {
return parameter.name && parameter.name.originalKeywordKind === 97;
}
function parameterNameStartsWithUnderscore(parameter) {
return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95;
}
@@ -24118,14 +24094,9 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
if (!typeParameter.symbol.isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -25202,7 +25173,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
registerForUnusedIdentifiersCheck(node);
checkUnusedTypeParameters(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -29925,7 +29896,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
write("//# sourceMappingURL=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
sourceMap.reset();
@@ -33575,13 +33546,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("let " + decoratedClassAlias);
write("" + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -35825,7 +35796,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.1.0";
ts.version = "2.0.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -35905,7 +35876,12 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -36561,22 +36537,6 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@@ -36652,7 +36612,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesDepth = 0;
var currentNodeModulesJsDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@@ -36876,7 +36836,8 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -37283,17 +37244,8 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -37310,7 +37262,6 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@@ -37411,9 +37362,12 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
currentNodeModulesDepth++;
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -37421,8 +37375,8 @@ var ts;
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
}
}
}
@@ -37741,12 +37695,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_locals
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_parameters
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
},
{
name: "noLib",
@@ -38525,18 +38479,10 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
var defaultFormatDiagnosticsHost = {
getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
getNewLine: function () { return ts.sys.newLine; },
getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
};
var reportDiagnosticWorker = reportDiagnosticSimply;
function reportDiagnostic(diagnostic, host) {
reportDiagnosticWorker(diagnostic, host || defaultFormatDiagnosticsHost);
}
var reportDiagnostic = reportDiagnosticSimply;
function reportDiagnostics(diagnostics, host) {
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
reportDiagnostic(diagnostic, host);
}
}
@@ -38607,8 +38553,19 @@ var ts;
var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
return diagnostic.messageText;
}
function getRelativeFileName(fileName, host) {
return host ? ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : fileName;
}
function reportDiagnosticSimply(diagnostic, host) {
ts.sys.write(ts.formatDiagnostics([diagnostic], host));
var output = "";
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var relativeFileName = getRelativeFileName(diagnostic.file.fileName, host);
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine;
ts.sys.write(output);
}
var redForegroundEscapeSequence = "\u001b[91m";
var yellowForegroundEscapeSequence = "\u001b[93m";
@@ -38633,7 +38590,7 @@ var ts;
var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character;
var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
var relativeFileName = getRelativeFileName(file.fileName, host);
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
@@ -38822,8 +38779,7 @@ var ts;
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
var cwd = ts.sys.getCurrentDirectory();
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd));
var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), ts.sys.getCurrentDirectory()), commandLine.options, configFileName);
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, undefined);
ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
@@ -38860,7 +38816,7 @@ var ts;
compilerHost.fileExists = cachedFileExists;
}
if (compilerOptions.pretty) {
reportDiagnosticWorker = reportDiagnosticWithColorAndContext;
reportDiagnostic = reportDiagnosticWithColorAndContext;
}
cachedExistingFiles = {};
var compileResult = compile(rootFileNames, compilerOptions, compilerHost);
@@ -39023,7 +38979,7 @@ var ts;
output += ts.sys.newLine + ts.sys.newLine;
var padding = makePadding(marginLength);
output += getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine;
output += padding + "tsc --outFile file.js file.ts" + ts.sys.newLine;
output += padding + "tsc --out file.js file.ts" + ts.sys.newLine;
output += padding + "tsc @args.txt" + ts.sys.newLine;
output += ts.sys.newLine;
output += getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine;
+77 -193
View File
@@ -830,17 +830,10 @@ var ts;
return true;
}
ts.containsPath = containsPath;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
return path.length > extension.length && endsWith(path, extension);
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -1105,8 +1098,6 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@@ -1238,7 +1229,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
var wscriptSystem = {
return {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -1257,7 +1248,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!wscriptSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -1277,7 +1268,6 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -1450,7 +1440,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
var nodeSystem = {
return {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -1500,7 +1490,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -1548,7 +1538,6 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -2298,8 +2287,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@@ -3977,12 +3966,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_locals
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_parameters
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
},
{
name: "noLib",
@@ -5765,7 +5754,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return /^\.\.?($|[\\/])/.test(moduleName);
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7273,24 +7262,25 @@ var ts;
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@@ -7713,8 +7703,6 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -7740,8 +7728,6 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@@ -8048,9 +8034,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -11826,9 +11810,6 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -16355,18 +16336,17 @@ var ts;
if (declaration.kind === 235) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
var type = undefined;
if (declaration.kind === 187 ||
declaration.kind === 172 && declaration.parent.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
if (declaration.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172) {
if (declaration.parent.kind === 187) {
type = checkExpressionCached(declaration.parent.right);
}
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@@ -22873,7 +22853,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@@ -24093,7 +24073,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (noUnusedIdentifiers && !node.body) {
if (!node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -24989,7 +24969,6 @@ var ts;
var parameter = local_1.valueDeclaration;
if (compilerOptions.noUnusedParameters &&
!ts.isParameterPropertyDeclaration(parameter) &&
!parameterIsThisKeyword(parameter) &&
!parameterNameStartsWithUnderscore(parameter)) {
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
}
@@ -25005,9 +24984,6 @@ var ts;
}
}
}
function parameterIsThisKeyword(parameter) {
return parameter.name && parameter.name.originalKeywordKind === 97;
}
function parameterNameStartsWithUnderscore(parameter) {
return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95;
}
@@ -25036,14 +25012,9 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
if (!typeParameter.symbol.isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -26120,7 +26091,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
registerForUnusedIdentifiersCheck(node);
checkUnusedTypeParameters(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -30843,7 +30814,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
write("//# sourceMappingURL=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
sourceMap.reset();
@@ -34493,13 +34464,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("let " + decoratedClassAlias);
write("" + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -36743,7 +36714,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.1.0";
ts.version = "2.0.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -36823,7 +36794,12 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -37479,22 +37455,6 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@@ -37570,7 +37530,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesDepth = 0;
var currentNodeModulesJsDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@@ -37794,7 +37754,8 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -38201,17 +38162,8 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -38228,7 +38180,6 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@@ -38329,9 +38280,12 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
currentNodeModulesDepth++;
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -38339,8 +38293,8 @@ var ts;
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
}
}
}
@@ -39933,7 +39887,7 @@ var ts;
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
}
else {
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -40105,6 +40059,14 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
if (startsWithIgnoringCase(string, value, i)) {
@@ -41589,9 +41551,6 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244;
}
function shouldRescanSlashToken(container) {
return container.kind === 10;
}
@@ -41619,9 +41578,7 @@ var ts;
? 3
: shouldRescanJsxIdentifier(n)
? 4
: shouldRescanJsxText(n)
? 5
: 0;
: 0;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
return fixTokenKind(lastTokenInfo, n);
}
@@ -41649,10 +41606,6 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4;
}
else if (expectedScanAction === 5) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5;
}
else {
lastScanAction = 0;
}
@@ -43901,20 +43854,19 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 ? new NodeObject(kind, pos, end) :
kind === 69 ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -43949,14 +43901,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, this));
nodes.push(createNode(token, pos, textPos, 0, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282, nodes.pos, nodes.end, this);
var list = createNode(282, nodes.pos, nodes.end, 0, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -44041,73 +43993,6 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@@ -49788,8 +49673,6 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@@ -50910,6 +50793,7 @@ var ts;
if (isOpen === void 0) { isOpen = false; }
this.host = host;
this.fileName = fileName;
this.content = content;
this.isOpen = isOpen;
this.children = [];
this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
@@ -52535,7 +52419,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
walkFns.done = true;
this.done = true;
}
}
};
@@ -53185,7 +53069,7 @@ var ts;
ioSession.listen();
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
var debugObjectHost = new Function("return this")();
var debugObjectHost = this;
var ts;
(function (ts) {
function logInternalError(logger, err) {
@@ -53313,7 +53197,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return JSON.parse(this.shimHost.getDirectories(path));
return this.shimHost.getDirectories(path);
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
+8 -17
View File
@@ -405,10 +405,7 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
interface Modifier extends Node {
}
interface Identifier extends PrimaryExpression {
text: string;
@@ -2053,6 +2050,7 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@@ -2158,8 +2156,6 @@ declare namespace ts {
function ensureTrailingDirectorySeparator(path: string): string;
function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
function fileExtensionIs(path: string, extension: string): boolean;
function fileExtensionIsAny(path: string, extensions: string[]): boolean;
function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string;
@@ -2197,8 +2193,6 @@ declare namespace ts {
function changeExtension<T extends string | Path>(path: T, newExtension: string): T;
interface ObjectAllocator {
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token;
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
@@ -6462,13 +6456,13 @@ declare namespace ts {
key: string;
message: string;
};
Report_errors_on_unused_locals: {
Report_Errors_on_Unused_Locals: {
code: number;
category: DiagnosticCategory;
key: string;
message: string;
};
Report_errors_on_unused_parameters: {
Report_Errors_on_Unused_Parameters: {
code: number;
category: DiagnosticCategory;
key: string;
@@ -7149,6 +7143,8 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
let parseTime: number;
@@ -7229,12 +7225,6 @@ declare namespace ts {
const defaultInitCompilerOptions: CompilerOptions;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[];
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
@@ -8398,6 +8388,7 @@ declare namespace ts.server {
class ScriptInfo {
private host;
fileName: string;
content: string;
isOpen: boolean;
svc: ScriptVersionCache;
children: ScriptInfo[];
@@ -8738,7 +8729,7 @@ declare namespace ts {
getLocalizedDiagnosticMessages(): string;
getCancellationToken(): HostCancellationToken;
getCurrentDirectory(): string;
getDirectories(path: string): string;
getDirectories(path: string): string[];
getDefaultLibFileName(options: string): string;
getNewLine?(): string;
getProjectVersion?(): string;
+77 -193
View File
@@ -830,17 +830,10 @@ var ts;
return true;
}
ts.containsPath = containsPath;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
return path.length > extension.length && endsWith(path, extension);
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -1105,8 +1098,6 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@@ -1238,7 +1229,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
var wscriptSystem = {
return {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -1257,7 +1248,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!wscriptSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -1277,7 +1268,6 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -1450,7 +1440,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); });
}
var nodeSystem = {
return {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -1500,7 +1490,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -1548,7 +1538,6 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -2298,8 +2287,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@@ -3977,12 +3966,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_locals
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_parameters
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
},
{
name: "noLib",
@@ -5765,7 +5754,7 @@ var ts;
}
ts.isExpression = isExpression;
function isExternalModuleNameRelative(moduleName) {
return /^\.\.?($|[\\/])/.test(moduleName);
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7273,24 +7262,25 @@ var ts;
return node.flags & 92 && node.parent.kind === 148 && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@@ -7713,8 +7703,6 @@ var ts;
var scanner = ts.createScanner(2, true);
var disallowInAndDecoratorContext = 4194304 | 16777216;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -7740,8 +7728,6 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@@ -8048,9 +8034,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return kind >= 139 ? new NodeConstructor(kind, pos, pos) :
kind === 69 ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -11826,9 +11810,6 @@ var ts;
case 55:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -16355,18 +16336,17 @@ var ts;
if (declaration.kind === 235) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 && declaration.kind === 280 && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
if (!pushTypeResolution(symbol, 0)) {
return unknownType;
}
var type = undefined;
if (declaration.kind === 187 ||
declaration.kind === 172 && declaration.parent.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
if (declaration.kind === 187) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172) {
if (declaration.parent.kind === 187) {
type = checkExpressionCached(declaration.parent.right);
}
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, true);
@@ -22873,7 +22853,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined);
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, undefined, undefined);
}
return links.inferredClassType;
}
@@ -24093,7 +24073,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (noUnusedIdentifiers && !node.body) {
if (!node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -24989,7 +24969,6 @@ var ts;
var parameter = local_1.valueDeclaration;
if (compilerOptions.noUnusedParameters &&
!ts.isParameterPropertyDeclaration(parameter) &&
!parameterIsThisKeyword(parameter) &&
!parameterNameStartsWithUnderscore(parameter)) {
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
}
@@ -25005,9 +24984,6 @@ var ts;
}
}
}
function parameterIsThisKeyword(parameter) {
return parameter.name && parameter.name.originalKeywordKind === 97;
}
function parameterNameStartsWithUnderscore(parameter) {
return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95;
}
@@ -25036,14 +25012,9 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
if (!typeParameter.symbol.isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -26120,7 +26091,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
registerForUnusedIdentifiersCheck(node);
checkUnusedTypeParameters(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -30843,7 +30814,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL);
write("//# sourceMappingURL=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, compilerOptions.emitBOM, sourceFiles);
sourceMap.reset();
@@ -34493,13 +34464,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("let " + decoratedClassAlias);
write("" + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -36743,7 +36714,7 @@ var ts;
ts.emitTime = 0;
ts.ioReadTime = 0;
ts.ioWriteTime = 0;
ts.version = "2.1.0";
ts.version = "2.0.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -36823,7 +36794,12 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46);
return !startsWithDotSlashOrDotDotSlash;
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -37479,22 +37455,6 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@@ -37570,7 +37530,7 @@ var ts;
var resolvedTypeReferenceDirectives = {};
var fileProcessingDiagnostics = ts.createDiagnosticCollection();
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesDepth = 0;
var currentNodeModulesJsDepth = 0;
var modulesWithElidedImports = {};
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
@@ -37794,7 +37754,8 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -38201,17 +38162,8 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -38228,7 +38180,6 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
var existingFile = filesByNameIgnoreCase.get(path);
@@ -38329,9 +38280,12 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
currentNodeModulesDepth++;
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -38339,8 +38293,8 @@ var ts;
else if (shouldAddFile) {
findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
}
}
}
@@ -39933,7 +39887,7 @@ var ts;
return createPatternMatch(PatternMatchKind.exact, punctuationStripped, candidate === chunk.text);
}
else {
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, ts.startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -40105,6 +40059,14 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
if (startsWithIgnoringCase(string, value, i)) {
@@ -41589,9 +41551,6 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244;
}
function shouldRescanSlashToken(container) {
return container.kind === 10;
}
@@ -41619,9 +41578,7 @@ var ts;
? 3
: shouldRescanJsxIdentifier(n)
? 4
: shouldRescanJsxText(n)
? 5
: 0;
: 0;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
return fixTokenKind(lastTokenInfo, n);
}
@@ -41649,10 +41606,6 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4;
}
else if (expectedScanAction === 5) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5;
}
else {
lastScanAction = 0;
}
@@ -43901,20 +43854,19 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 ? new NodeObject(kind, pos, end) :
kind === 69 ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -43949,14 +43901,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, this));
nodes.push(createNode(token, pos, textPos, 0, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282, nodes.pos, nodes.end, this);
var list = createNode(282, nodes.pos, nodes.end, 0, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -44041,73 +43993,6 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
this.pos = pos;
this.end = end;
this.flags = 0;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@@ -49788,8 +49673,6 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@@ -50910,6 +50793,7 @@ var ts;
if (isOpen === void 0) { isOpen = false; }
this.host = host;
this.fileName = fileName;
this.content = content;
this.isOpen = isOpen;
this.children = [];
this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
@@ -52535,7 +52419,7 @@ var ts;
done: false,
leaf: function (relativeStart, relativeLength, ll) {
if (!f(ll, relativeStart, relativeLength)) {
walkFns.done = true;
this.done = true;
}
}
};
@@ -52951,7 +52835,7 @@ var ts;
server.LineLeaf = LineLeaf;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
var debugObjectHost = new Function("return this")();
var debugObjectHost = this;
var ts;
(function (ts) {
function logInternalError(logger, err) {
@@ -53079,7 +52963,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return JSON.parse(this.shimHost.getDirectories(path));
return this.shimHost.getDirectories(path);
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
+4 -10
View File
@@ -409,10 +409,7 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
interface Modifier extends Node {
}
interface Identifier extends PrimaryExpression {
text: string;
@@ -1699,6 +1696,7 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@@ -1844,6 +1842,8 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
@@ -1868,12 +1868,6 @@ declare namespace ts {
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
/**
* Given a set of options and a set of root files, returns the set of type directive names
+83 -210
View File
@@ -1756,19 +1756,10 @@ var ts;
return true;
}
ts.containsPath = containsPath;
/* @internal */
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
/* @internal */
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
return path.length > extension.length && endsWith(path, extension);
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -2079,8 +2070,6 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@@ -2227,7 +2216,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
var wscriptSystem = {
return {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -2246,7 +2235,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!wscriptSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -2266,7 +2255,6 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -2456,7 +2444,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
}
var nodeSystem = {
return {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -2512,7 +2500,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -2560,7 +2548,6 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -3317,8 +3304,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@@ -6166,7 +6153,7 @@ var ts;
function isExternalModuleNameRelative(moduleName) {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return /^\.\.?($|[\\/])/.test(moduleName);
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7929,6 +7916,15 @@ var ts;
return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
/// <reference path="utilities.ts"/>
/// <reference path="scanner.ts"/>
@@ -7936,19 +7932,11 @@ var ts;
(function (ts) {
/* @internal */ ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139 /* FirstNode */) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@@ -8398,8 +8386,6 @@ var ts;
var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -8499,8 +8485,6 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@@ -8871,9 +8855,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -13542,9 +13524,6 @@ var ts;
case 55 /* AtToken */:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -19012,24 +18991,22 @@ var ts;
if (declaration.kind === 235 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
return unknownType;
}
var type = undefined;
// Handle certain special assignment kinds, which happen to union across multiple declarations:
// * module.exports = expr
// * exports.p = expr
// * this.p = expr
// * className.prototype.method = expr
if (declaration.kind === 187 /* BinaryExpression */ ||
declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
// Handle module.exports = expr or this.p = expr
if (declaration.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172 /* PropertyAccessExpression */) {
// Declarations only exist for property access expressions for certain
// special assignment kinds
if (declaration.parent.kind === 187 /* BinaryExpression */) {
// Handle exports.p = expr or className.prototype.method = expr
type = checkExpressionCached(declaration.parent.right);
}
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
@@ -26784,7 +26761,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@@ -28225,7 +28202,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (noUnusedIdentifiers && !node.body) {
if (!node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -29364,7 +29341,6 @@ var ts;
var parameter = local_1.valueDeclaration;
if (compilerOptions.noUnusedParameters &&
!ts.isParameterPropertyDeclaration(parameter) &&
!parameterIsThisKeyword(parameter) &&
!parameterNameStartsWithUnderscore(parameter)) {
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
}
@@ -29380,9 +29356,6 @@ var ts;
}
}
}
function parameterIsThisKeyword(parameter) {
return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */;
}
function parameterNameStartsWithUnderscore(parameter) {
return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */;
}
@@ -29411,16 +29384,9 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
if (!typeParameter.symbol.isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -30753,7 +30719,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
registerForUnusedIdentifiersCheck(node);
checkUnusedTypeParameters(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -36017,7 +35983,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
write("//# sourceMappingURL=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
@@ -37914,7 +37880,7 @@ var ts;
* if we should also export the value after its it changed
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* when we emit variable statement 'var' should be dropped.
* we we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
if (!node || !isCurrentFileSystemExternalModule()) {
@@ -40381,13 +40347,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("let " + decoratedClassAlias);
write("" + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -40406,9 +40372,7 @@ var ts;
//
// We'll emit:
//
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@@ -42972,7 +42936,7 @@ var ts;
/* @internal */ ts.ioReadTime = 0;
/* @internal */ ts.ioWriteTime = 0;
/** The version of the TypeScript compiler release */
ts.version = "2.1.0";
ts.version = "2.0.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -43061,7 +43025,12 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */);
return !startsWithDotSlashOrDotDotSlash;
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -43828,22 +43797,6 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@@ -43936,11 +43889,11 @@ var ts;
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesDepth = 0;
var currentNodeModulesJsDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
var modulesWithElidedImports = {};
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
host = host || createCompilerHost(options);
@@ -44197,7 +44150,8 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -44649,19 +44603,9 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
// See if we need to reprocess the imports due to prior skipped imports
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -44679,7 +44623,6 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
@@ -44794,9 +44737,12 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
currentNodeModulesDepth++;
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -44805,8 +44751,8 @@ var ts;
findSourceFile(resolution.resolvedFileName, resolvedPath,
/*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
}
}
}
@@ -45144,12 +45090,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_locals
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_parameters
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
},
{
name: "noLib",
@@ -47141,7 +47087,7 @@ var ts;
else {
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -47407,6 +47353,14 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
@@ -49251,7 +49205,6 @@ var ts;
ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
})(ScanAction || (ScanAction = {}));
function getFormattingScanner(sourceFile, startPos, endPos) {
ts.Debug.assert(scanner === undefined);
@@ -49343,9 +49296,6 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
@@ -49376,9 +49326,7 @@ var ts;
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: shouldRescanJsxText(n)
? 5 /* RescanJsxText */
: 0 /* Scan */;
: 0 /* Scan */;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
// readTokenInfo was called before with the same expected scan action.
// No need to re-scan text, return existing 'lastTokenInfo'
@@ -49413,10 +49361,6 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else if (expectedScanAction === 5 /* RescanJsxText */) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5 /* RescanJsxText */;
}
else {
lastScanAction = 0 /* Scan */;
}
@@ -52089,20 +52033,19 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) :
kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -52137,14 +52080,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, this));
nodes.push(createNode(token, pos, textPos, 0, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -52230,74 +52173,6 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
// Set properties in same order as NodeObject
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69 /* Identifier */;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@@ -59062,8 +58937,6 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@@ -59689,7 +59562,7 @@ var ts;
//
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = new Function("return this")();
var debugObjectHost = this;
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
@@ -59828,7 +59701,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return JSON.parse(this.shimHost.getDirectories(path));
return this.shimHost.getDirectories(path);
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
+4 -10
View File
@@ -409,10 +409,7 @@ declare namespace ts {
interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
interface Token extends Node {
__tokenTag: any;
}
interface Modifier extends Token {
interface Modifier extends Node {
}
interface Identifier extends PrimaryExpression {
text: string;
@@ -1699,6 +1696,7 @@ declare namespace ts {
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
@@ -1844,6 +1842,8 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
@@ -1868,12 +1868,6 @@ declare namespace ts {
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
/**
* Given a set of options and a set of root files, returns the set of type directive names
+83 -210
View File
@@ -1756,19 +1756,10 @@ var ts;
return true;
}
ts.containsPath = containsPath;
/* @internal */
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
/* @internal */
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
function fileExtensionIs(path, extension) {
return path.length > extension.length && endsWith(path, extension);
var pathLen = path.length;
var extLen = extension.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
ts.fileExtensionIs = fileExtensionIs;
function fileExtensionIsAny(path, extensions) {
@@ -2079,8 +2070,6 @@ var ts;
}
ts.objectAllocator = {
getNodeConstructor: function () { return Node; },
getTokenConstructor: function () { return Node; },
getIdentifierConstructor: function () { return Node; },
getSourceFileConstructor: function () { return Node; },
getSymbolConstructor: function () { return Symbol; },
getTypeConstructor: function () { return Type; },
@@ -2227,7 +2216,7 @@ var ts;
function readDirectory(path, extensions, excludes, includes) {
return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries);
}
var wscriptSystem = {
return {
args: args,
newLine: "\r\n",
useCaseSensitiveFileNames: false,
@@ -2246,7 +2235,7 @@ var ts;
return fso.FolderExists(path);
},
createDirectory: function (directoryName) {
if (!wscriptSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
fso.CreateFolder(directoryName);
}
},
@@ -2266,7 +2255,6 @@ var ts;
}
}
};
return wscriptSystem;
}
function getNodeSystem() {
var _fs = require("fs");
@@ -2456,7 +2444,7 @@ var ts;
function getDirectories(path) {
return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); });
}
var nodeSystem = {
return {
args: process.argv.slice(2),
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
@@ -2512,7 +2500,7 @@ var ts;
fileExists: fileExists,
directoryExists: directoryExists,
createDirectory: function (directoryName) {
if (!nodeSystem.directoryExists(directoryName)) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
}
},
@@ -2560,7 +2548,6 @@ var ts;
return _fs.realpathSync(path);
}
};
return nodeSystem;
}
function getChakraSystem() {
var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); });
@@ -3317,8 +3304,8 @@ var ts;
Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." },
File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it" },
_0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." },
Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." },
Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." },
Report_Errors_on_Unused_Locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Locals_6134", message: "Report Errors on Unused Locals." },
Report_Errors_on_Unused_Parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_Errors_on_Unused_Parameters_6135", message: "Report Errors on Unused Parameters." },
The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" },
No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." },
@@ -6166,7 +6153,7 @@ var ts;
function isExternalModuleNameRelative(moduleName) {
// TypeScript 1.0 spec (April 2014): 11.2.1
// An external module name is "relative" if the first term is "." or "..".
return /^\.\.?($|[\\/])/.test(moduleName);
return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\";
}
ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
function isInstantiatedModule(node, preserveConstEnums) {
@@ -7929,6 +7916,15 @@ var ts;
return node.flags & 92 /* ParameterPropertyModifier */ && node.parent.kind === 148 /* Constructor */ && ts.isClassLike(node.parent.parent);
}
ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
function startsWith(str, prefix) {
return str.lastIndexOf(prefix, 0) === 0;
}
ts.startsWith = startsWith;
function endsWith(str, suffix) {
var expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
ts.endsWith = endsWith;
})(ts || (ts = {}));
/// <reference path="utilities.ts"/>
/// <reference path="scanner.ts"/>
@@ -7936,19 +7932,11 @@ var ts;
(function (ts) {
/* @internal */ ts.parseTime = 0;
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
if (kind === 256 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 69 /* Identifier */) {
return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
}
else if (kind < 139 /* FirstNode */) {
return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
}
@@ -8398,8 +8386,6 @@ var ts;
var disallowInAndDecoratorContext = 4194304 /* DisallowInContext */ | 16777216 /* DecoratorContext */;
// capture constructors in 'initializeState' to avoid null checks
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
var SourceFileConstructor;
var sourceFile;
var parseDiagnostics;
@@ -8499,8 +8485,6 @@ var ts;
}
function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind) {
NodeConstructor = ts.objectAllocator.getNodeConstructor();
TokenConstructor = ts.objectAllocator.getTokenConstructor();
IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@@ -8871,9 +8855,7 @@ var ts;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return kind >= 139 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) :
kind === 69 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) :
new TokenConstructor(kind, pos, pos);
return new NodeConstructor(kind, pos, pos);
}
function finishNode(node, end) {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -13542,9 +13524,6 @@ var ts;
case 55 /* AtToken */:
if (canParseTag) {
parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral);
if (!parentTagTerminated) {
resumePos = scanner.getStartPos();
}
}
seenAsterisk = false;
break;
@@ -19012,24 +18991,22 @@ var ts;
if (declaration.kind === 235 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
if (declaration.flags & 134217728 /* JavaScriptFile */ && declaration.kind === 280 /* JSDocPropertyTag */ && declaration.typeExpression) {
return links.type = getTypeFromTypeNode(declaration.typeExpression.type);
}
// Handle variable, parameter or property
if (!pushTypeResolution(symbol, 0 /* Type */)) {
return unknownType;
}
var type = undefined;
// Handle certain special assignment kinds, which happen to union across multiple declarations:
// * module.exports = expr
// * exports.p = expr
// * this.p = expr
// * className.prototype.method = expr
if (declaration.kind === 187 /* BinaryExpression */ ||
declaration.kind === 172 /* PropertyAccessExpression */ && declaration.parent.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return decl.kind === 187 /* BinaryExpression */ ?
checkExpressionCached(decl.right) :
checkExpressionCached(decl.parent.right); }));
// Handle module.exports = expr or this.p = expr
if (declaration.kind === 187 /* BinaryExpression */) {
type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); }));
}
else if (declaration.kind === 172 /* PropertyAccessExpression */) {
// Declarations only exist for property access expressions for certain
// special assignment kinds
if (declaration.parent.kind === 187 /* BinaryExpression */) {
// Handle exports.p = expr or className.prototype.method = expr
type = checkExpressionCached(declaration.parent.right);
}
}
if (type === undefined) {
type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true);
@@ -26784,7 +26761,7 @@ var ts;
function getInferredClassType(symbol) {
var links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@@ -28225,7 +28202,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
if (noUnusedIdentifiers && !node.body) {
if (!node.body) {
checkUnusedTypeParameters(node);
}
}
@@ -29364,7 +29341,6 @@ var ts;
var parameter = local_1.valueDeclaration;
if (compilerOptions.noUnusedParameters &&
!ts.isParameterPropertyDeclaration(parameter) &&
!parameterIsThisKeyword(parameter) &&
!parameterNameStartsWithUnderscore(parameter)) {
error(local_1.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local_1.name);
}
@@ -29380,9 +29356,6 @@ var ts;
}
}
}
function parameterIsThisKeyword(parameter) {
return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */;
}
function parameterNameStartsWithUnderscore(parameter) {
return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */;
}
@@ -29411,16 +29384,9 @@ var ts;
function checkUnusedTypeParameters(node) {
if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) {
if (node.typeParameters) {
// Only report errors on the last declaration for the type parameter container;
// this ensures that all uses have been accounted for.
var symbol = getSymbolOfNode(node);
var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations);
if (lastDeclaration !== node) {
return;
}
for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
var typeParameter = _a[_i];
if (!getMergedSymbol(typeParameter.symbol).isReferenced) {
if (!typeParameter.symbol.isReferenced) {
error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name);
}
}
@@ -30753,7 +30719,7 @@ var ts;
ts.forEach(node.members, checkSourceElement);
if (produceDiagnostics) {
checkTypeForDuplicateIndexSignatures(node);
registerForUnusedIdentifiersCheck(node);
checkUnusedTypeParameters(node);
}
}
function checkTypeAliasDeclaration(node) {
@@ -36017,7 +35983,7 @@ var ts;
writeLine();
var sourceMappingURL = sourceMap.getSourceMappingURL();
if (sourceMappingURL) {
write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment
write("//# sourceMappingURL=" + sourceMappingURL);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
@@ -37914,7 +37880,7 @@ var ts;
* if we should also export the value after its it changed
* - check if node is a source level declaration to emit it differently,
* i.e non-exported variable statement 'var x = 1' is hoisted so
* when we emit variable statement 'var' should be dropped.
* we we emit variable statement 'var' should be dropped.
*/
function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) {
if (!node || !isCurrentFileSystemExternalModule()) {
@@ -40381,13 +40347,13 @@ var ts;
if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */) && decoratedClassAlias === undefined) {
write("export ");
}
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
if (decoratedClassAlias !== undefined) {
write("let " + decoratedClassAlias);
write("" + decoratedClassAlias);
}
else {
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
}
write(" = ");
@@ -40406,9 +40372,7 @@ var ts;
//
// We'll emit:
//
// let C_1 = class C{};
// C_1.a = 1;
// C_1.b = 2; // so forth and so on
// (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp)
//
// This keeps the expression as an expression, while ensuring that the static parts
// of it have been initialized by the time it is used.
@@ -42972,7 +42936,7 @@ var ts;
/* @internal */ ts.ioReadTime = 0;
/* @internal */ ts.ioWriteTime = 0;
/** The version of the TypeScript compiler release */
ts.version = "2.1.0";
ts.version = "2.0.0";
var emptyArray = [];
var defaultTypeRoots = ["node_modules/@types"];
function findConfigFile(searchPath, fileExists) {
@@ -43061,7 +43025,12 @@ var ts;
return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
if (ts.isRootedDiskPath(moduleName)) {
return false;
}
var i = moduleName.lastIndexOf("./", 1);
var startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === 46 /* dot */);
return !startsWithDotSlashOrDotDotSlash;
}
function tryReadTypesSection(packageJsonPath, baseDirectory, state) {
var jsonContent;
@@ -43828,22 +43797,6 @@ var ts;
return ts.sortAndDeduplicateDiagnostics(diagnostics);
}
ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
function formatDiagnostics(diagnostics, host) {
var output = "";
for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
var diagnostic = diagnostics_1[_i];
if (diagnostic.file) {
var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character;
var fileName = diagnostic.file.fileName;
var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
output += relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): ";
}
var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
output += category + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
}
return output;
}
ts.formatDiagnostics = formatDiagnostics;
function flattenDiagnosticMessageText(messageText, newLine) {
if (typeof messageText === "string") {
return messageText;
@@ -43936,11 +43889,11 @@ var ts;
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
var maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
var currentNodeModulesDepth = 0;
var currentNodeModulesJsDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
// this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
var modulesWithElidedImports = {};
// Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
// Track source files that are JavaScript files found by searching under node_modules, as these shouldn't be compiled.
var sourceFilesFoundSearchingNodeModules = {};
var start = new Date().getTime();
host = host || createCompilerHost(options);
@@ -44197,7 +44150,8 @@ var ts;
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile, writeFileCallback, cancellationToken) {
return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); });
var _this = this;
return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); });
}
function isEmitBlocked(emitFileName) {
return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName));
@@ -44649,19 +44603,9 @@ var ts;
if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
if (file_1 && ts.lookUp(sourceFilesFoundSearchingNodeModules, file_1.path) && currentNodeModulesDepth == 0) {
sourceFilesFoundSearchingNodeModules[file_1.path] = false;
if (!options.noResolve) {
processReferencedFiles(file_1, ts.getDirectoryPath(fileName), isDefaultLib);
processTypeReferenceDirectives(file_1);
}
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
else if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesDepth < maxNodeModulesJsDepth) {
// See if we need to reprocess the imports due to prior skipped imports
if (file_1 && ts.lookUp(modulesWithElidedImports, file_1.path)) {
if (currentNodeModulesJsDepth < maxNodeModulesJsDepth) {
modulesWithElidedImports[file_1.path] = false;
processImportedModules(file_1, ts.getDirectoryPath(fileName));
}
@@ -44679,7 +44623,6 @@ var ts;
});
filesByName.set(path, file);
if (file) {
sourceFilesFoundSearchingNodeModules[path] = (currentNodeModulesDepth > 0);
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
@@ -44794,9 +44737,12 @@ var ts;
var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport;
var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName);
if (isFromNodeModulesSearch) {
currentNodeModulesDepth++;
sourceFilesFoundSearchingNodeModules[resolvedPath] = true;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModulesJsDepth;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth++;
}
var elideImport = isJsFileFromNodeModules && currentNodeModulesJsDepth > maxNodeModulesJsDepth;
var shouldAddFile = resolution && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
modulesWithElidedImports[file.path] = true;
@@ -44805,8 +44751,8 @@ var ts;
findSourceFile(resolution.resolvedFileName, resolvedPath,
/*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
if (isFromNodeModulesSearch) {
currentNodeModulesDepth--;
if (isJsFileFromNodeModules) {
currentNodeModulesJsDepth--;
}
}
}
@@ -45144,12 +45090,12 @@ var ts;
{
name: "noUnusedLocals",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_locals
description: ts.Diagnostics.Report_Errors_on_Unused_Locals
},
{
name: "noUnusedParameters",
type: "boolean",
description: ts.Diagnostics.Report_errors_on_unused_parameters
description: ts.Diagnostics.Report_Errors_on_Unused_Parameters
},
{
name: "noLib",
@@ -47141,7 +47087,7 @@ var ts;
else {
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text));
return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text));
}
}
var isLowercase = chunk.isLowerCase;
@@ -47407,6 +47353,14 @@ var ts;
var str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function startsWith(string, search) {
for (var i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
return false;
}
}
return true;
}
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(string, value) {
for (var i = 0, n = string.length - value.length; i <= n; i++) {
@@ -49251,7 +49205,6 @@ var ts;
ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken";
ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken";
ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier";
ScanAction[ScanAction["RescanJsxText"] = 5] = "RescanJsxText";
})(ScanAction || (ScanAction = {}));
function getFormattingScanner(sourceFile, startPos, endPos) {
ts.Debug.assert(scanner === undefined);
@@ -49343,9 +49296,6 @@ var ts;
}
return false;
}
function shouldRescanJsxText(node) {
return node && node.kind === 244 /* JsxText */;
}
function shouldRescanSlashToken(container) {
return container.kind === 10 /* RegularExpressionLiteral */;
}
@@ -49376,9 +49326,7 @@ var ts;
? 3 /* RescanTemplateToken */
: shouldRescanJsxIdentifier(n)
? 4 /* RescanJsxIdentifier */
: shouldRescanJsxText(n)
? 5 /* RescanJsxText */
: 0 /* Scan */;
: 0 /* Scan */;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
// readTokenInfo was called before with the same expected scan action.
// No need to re-scan text, return existing 'lastTokenInfo'
@@ -49413,10 +49361,6 @@ var ts;
currentToken = scanner.scanJsxIdentifier();
lastScanAction = 4 /* RescanJsxIdentifier */;
}
else if (expectedScanAction === 5 /* RescanJsxText */) {
currentToken = scanner.reScanJsxToken();
lastScanAction = 5 /* RescanJsxText */;
}
else {
lastScanAction = 0 /* Scan */;
}
@@ -52089,20 +52033,19 @@ var ts;
"version"
];
var jsDocCompletionEntries;
function createNode(kind, pos, end, parent) {
var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) :
kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) :
new TokenObject(kind, pos, end);
function createNode(kind, pos, end, flags, parent) {
var node = new NodeObject(kind, pos, end);
node.flags = flags;
node.parent = parent;
return node;
}
var NodeObject = (function () {
function NodeObject(kind, pos, end) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
this.kind = kind;
}
NodeObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
@@ -52137,14 +52080,14 @@ var ts;
var token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
var textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, this));
nodes.push(createNode(token, pos, textPos, 0, this));
}
pos = textPos;
}
return pos;
};
NodeObject.prototype.createSyntaxList = function (nodes) {
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, this);
var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
@@ -52230,74 +52173,6 @@ var ts;
};
return NodeObject;
}());
var TokenOrIdentifierObject = (function () {
function TokenOrIdentifierObject(pos, end) {
// Set properties in same order as NodeObject
this.pos = pos;
this.end = end;
this.flags = 0 /* None */;
this.parent = undefined;
}
TokenOrIdentifierObject.prototype.getSourceFile = function () {
return ts.getSourceFileOfNode(this);
};
TokenOrIdentifierObject.prototype.getStart = function (sourceFile, includeJsDocComment) {
return ts.getTokenPosOfNode(this, sourceFile, includeJsDocComment);
};
TokenOrIdentifierObject.prototype.getFullStart = function () {
return this.pos;
};
TokenOrIdentifierObject.prototype.getEnd = function () {
return this.end;
};
TokenOrIdentifierObject.prototype.getWidth = function (sourceFile) {
return this.getEnd() - this.getStart(sourceFile);
};
TokenOrIdentifierObject.prototype.getFullWidth = function () {
return this.end - this.pos;
};
TokenOrIdentifierObject.prototype.getLeadingTriviaWidth = function (sourceFile) {
return this.getStart(sourceFile) - this.pos;
};
TokenOrIdentifierObject.prototype.getFullText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end);
};
TokenOrIdentifierObject.prototype.getText = function (sourceFile) {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
};
TokenOrIdentifierObject.prototype.getChildCount = function (sourceFile) {
return 0;
};
TokenOrIdentifierObject.prototype.getChildAt = function (index, sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getChildren = function (sourceFile) {
return emptyArray;
};
TokenOrIdentifierObject.prototype.getFirstToken = function (sourceFile) {
return undefined;
};
TokenOrIdentifierObject.prototype.getLastToken = function (sourceFile) {
return undefined;
};
return TokenOrIdentifierObject;
}());
var TokenObject = (function (_super) {
__extends(TokenObject, _super);
function TokenObject(kind, pos, end) {
_super.call(this, pos, end);
this.kind = kind;
}
return TokenObject;
}(TokenOrIdentifierObject));
var IdentifierObject = (function (_super) {
__extends(IdentifierObject, _super);
function IdentifierObject(kind, pos, end) {
_super.call(this, pos, end);
}
return IdentifierObject;
}(TokenOrIdentifierObject));
IdentifierObject.prototype.kind = 69 /* Identifier */;
var SymbolObject = (function () {
function SymbolObject(flags, name) {
this.flags = flags;
@@ -59062,8 +58937,6 @@ var ts;
function initializeServices() {
ts.objectAllocator = {
getNodeConstructor: function () { return NodeObject; },
getTokenConstructor: function () { return TokenObject; },
getIdentifierConstructor: function () { return IdentifierObject; },
getSourceFileConstructor: function () { return SourceFileObject; },
getSymbolConstructor: function () { return SymbolObject; },
getTypeConstructor: function () { return TypeObject; },
@@ -59689,7 +59562,7 @@ var ts;
//
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = new Function("return this")();
var debugObjectHost = this;
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
@@ -59828,7 +59701,7 @@ var ts;
return this.shimHost.getCurrentDirectory();
};
LanguageServiceShimHostAdapter.prototype.getDirectories = function (path) {
return JSON.parse(this.shimHost.getDirectories(path));
return this.shimHost.getDirectories(path);
};
LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
+1
View File
@@ -75,6 +75,7 @@
"through2": "latest",
"travis-fold": "latest",
"ts-node": "latest",
"tsd": "latest",
"tslint": "next",
"typescript": "next"
},
+24
View File
@@ -0,0 +1,24 @@
// simple script to optionally elide source-map-support (or other optional modules) when running browserify.
var stream = require("stream"),
Transform = stream.Transform,
resolve = require("browser-resolve");
var requirePattern = /require\s*\(\s*['"](source-map-support)['"]\s*\)/;
module.exports = function (file) {
return new Transform({
transform: function (data, encoding, cb) {
var text = encoding === "buffer" ? data.toString("utf8") : data;
this.push(new Buffer(text.replace(requirePattern, function (originalText, moduleName) {
try {
resolve.sync(moduleName, { filename: file });
return originalText;
}
catch (e) {
return "(function () { throw new Error(\"module '" + moduleName + "' not found.\"); })()";
}
}), "utf8"));
cb();
}
});
};
+13 -38
View File
@@ -9,44 +9,12 @@ export class Rule extends Lint.Rules.AbstractRule {
}
}
function isBindingPattern(node: ts.Node): node is ts.BindingPattern {
return !!node && (node.kind === ts.SyntaxKind.ArrayBindingPattern || node.kind === ts.SyntaxKind.ObjectBindingPattern);
}
function walkUpBindingElementsAndPatterns(node: ts.Node): ts.Node {
while (node && (node.kind === ts.SyntaxKind.BindingElement || isBindingPattern(node))) {
node = node.parent;
}
return node;
}
function getCombinedNodeFlags(node: ts.Node): ts.NodeFlags {
node = walkUpBindingElementsAndPatterns(node);
let flags = node.flags;
if (node.kind === ts.SyntaxKind.VariableDeclaration) {
node = node.parent;
}
if (node && node.kind === ts.SyntaxKind.VariableDeclarationList) {
flags |= node.flags;
node = node.parent;
}
if (node && node.kind === ts.SyntaxKind.VariableStatement) {
flags |= node.flags;
}
return flags;
}
function isLet(node: ts.Node) {
return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Let);
return !!(ts.getCombinedNodeFlags(node) & ts.NodeFlags.Let);
}
function isExported(node: ts.Node) {
return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Export);
return !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export);
}
function isAssignmentOperator(token: ts.SyntaxKind): boolean {
@@ -125,11 +93,16 @@ class PreferConstWalker extends Lint.RuleWalker {
private visitBindingPatternIdentifiers(pattern: ts.BindingPattern) {
for (const element of pattern.elements) {
if (element.name.kind === ts.SyntaxKind.Identifier) {
this.markAssignment(element.name as ts.Identifier);
if (element.kind !== ts.SyntaxKind.BindingElement) {
continue;
}
const name = (<ts.BindingElement>element).name;
if (name.kind === ts.SyntaxKind.Identifier) {
this.markAssignment(name as ts.Identifier);
}
else {
this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern);
this.visitBindingPatternIdentifiers(name as ts.BindingPattern);
}
}
}
@@ -223,7 +196,9 @@ class PreferConstWalker extends Lint.RuleWalker {
private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.MapLike<DeclarationUsages>) {
for (const element of pattern.elements) {
this.collectNameIdentifiers(value, element.name, table);
if (element.kind === ts.SyntaxKind.BindingElement) {
this.collectNameIdentifiers(value, (<ts.BindingElement>element).name, table);
}
}
}
}
+798 -13
View File
@@ -27,7 +27,7 @@ namespace ts {
return ModuleInstanceState.ConstEnumOnly;
}
// 3. non-exported import declarations
else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && !(node.flags & NodeFlags.Export)) {
else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && !(hasModifier(node, ModifierFlags.Export))) {
return ModuleInstanceState.NonInstantiated;
}
// 4. other uninstantiated module declarations.
@@ -131,6 +131,10 @@ namespace ts {
const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
const reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
// state used to aggregate transform flags during bind.
let subtreeTransformFlags: TransformFlags = TransformFlags.None;
let skipTransformFlagAggregation: boolean;
function bindSourceFile(f: SourceFile, opts: CompilerOptions) {
file = f;
options = opts;
@@ -138,6 +142,7 @@ namespace ts {
inStrictMode = !!file.externalModuleIndicator;
classifiableNames = createMap<string>();
symbolCount = 0;
skipTransformFlagAggregation = isDeclarationFile(file);
Symbol = objectAllocator.getSymbolConstructor();
@@ -164,6 +169,7 @@ namespace ts {
activeLabels = undefined;
hasExplicitReturn = false;
emitFlags = NodeFlags.None;
subtreeTransformFlags = TransformFlags.None;
}
return bindSourceFile;
@@ -253,7 +259,7 @@ namespace ts {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
return node.flags & NodeFlags.Default ? "default" : undefined;
return hasModifier(node, ModifierFlags.Default) ? "default" : undefined;
case SyntaxKind.JSDocFunctionType:
return isJSDocConstructSignature(node) ? "__new" : "__call";
case SyntaxKind.Parameter:
@@ -293,7 +299,7 @@ namespace ts {
function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol {
Debug.assert(!hasDynamicName(node));
const isDefaultExport = node.flags & NodeFlags.Default;
const isDefaultExport = hasModifier(node, ModifierFlags.Default);
// The exported symbol for an export default function/class node is always named "default"
const name = isDefaultExport && parent ? "default" : getDeclarationName(node);
@@ -350,7 +356,7 @@ namespace ts {
: Diagnostics.Duplicate_identifier_0;
forEach(symbol.declarations, declaration => {
if (declaration.flags & NodeFlags.Default) {
if (hasModifier(declaration, ModifierFlags.Default)) {
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
}
});
@@ -372,7 +378,7 @@ namespace ts {
}
function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol {
const hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export;
const hasExportModifier = getCombinedModifierFlags(node) & ModifierFlags.Export;
if (symbolFlags & SymbolFlags.Alias) {
if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
@@ -513,6 +519,23 @@ namespace ts {
}
function bindChildren(node: Node): void {
if (skipTransformFlagAggregation) {
bindChildrenWorker(node);
}
else if (node.transformFlags & TransformFlags.HasComputedFlags) {
skipTransformFlagAggregation = true;
bindChildrenWorker(node);
skipTransformFlagAggregation = false;
}
else {
const savedSubtreeTransformFlags = subtreeTransformFlags;
subtreeTransformFlags = 0;
bindChildrenWorker(node);
subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
}
}
function bindChildrenWorker(node: Node): void {
// Binding of JsDocComment should be done before the current block scope container changes.
// because the scope of JsDocComment should not be affected by whether the current node is a
// container or not.
@@ -1127,8 +1150,8 @@ namespace ts {
currentFlow = finishFlowLabel(postExpressionLabel);
}
function bindInitializedVariableFlow(node: VariableDeclaration | BindingElement) {
const name = node.name;
function bindInitializedVariableFlow(node: VariableDeclaration | ArrayBindingElement) {
const name = !isOmittedExpression(node) ? node.name : undefined;
if (isBindingPattern(name)) {
for (const child of name.elements) {
bindInitializedVariableFlow(child);
@@ -1308,7 +1331,7 @@ namespace ts {
}
function declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
return node.flags & NodeFlags.Static
return hasModifier(node, ModifierFlags.Static)
? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
: declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
}
@@ -1345,7 +1368,7 @@ namespace ts {
function bindModuleDeclaration(node: ModuleDeclaration) {
setExportContextFlag(node);
if (isAmbientModule(node)) {
if (node.flags & NodeFlags.Export) {
if (hasModifier(node, ModifierFlags.Export)) {
errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
if (isExternalModuleAugmentation(node)) {
@@ -1612,7 +1635,7 @@ namespace ts {
}
}
function checkStrictModeNumericLiteral(node: LiteralExpression) {
function checkStrictModeNumericLiteral(node: NumericLiteral) {
if (inStrictMode && node.isOctalLiteral) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
}
@@ -1687,6 +1710,9 @@ namespace ts {
}
parent = saveParent;
}
else if (!skipTransformFlagAggregation && (node.transformFlags & TransformFlags.HasComputedFlags) === 0) {
subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
}
inStrictMode = saveInStrictMode;
}
@@ -1757,7 +1783,7 @@ namespace ts {
case SyntaxKind.DeleteExpression:
return checkStrictModeDeleteExpression(<DeleteExpression>node);
case SyntaxKind.NumericLiteral:
return checkStrictModeNumericLiteral(<LiteralExpression>node);
return checkStrictModeNumericLiteral(<NumericLiteral>node);
case SyntaxKind.PostfixUnaryExpression:
return checkStrictModePostfixUnaryExpression(<PostfixUnaryExpression>node);
case SyntaxKind.PrefixUnaryExpression:
@@ -1789,7 +1815,7 @@ namespace ts {
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
case SyntaxKind.JsxSpreadAttribute:
emitFlags |= NodeFlags.HasJsxSpreadAttribute;
emitFlags |= NodeFlags.HasJsxSpreadAttributes;
return;
case SyntaxKind.CallSignature:
@@ -2204,7 +2230,7 @@ namespace ts {
if (currentFlow === unreachableFlow) {
const reportError =
// report error on all statements except empty ones
(isStatement(node) && node.kind !== SyntaxKind.EmptyStatement) ||
(isStatementButNotDeclaration(node) && node.kind !== SyntaxKind.EmptyStatement) ||
// report error on class declarations
node.kind === SyntaxKind.ClassDeclaration ||
// report error on instantiated modules or const-enums only modules if preserveConstEnums is set
@@ -2241,4 +2267,763 @@ namespace ts {
return true;
}
}
/**
* Computes the transform flags for a node, given the transform flags of its subtree
*
* @param node The node to analyze
* @param subtreeFlags Transform flags computed for this node's subtree
*/
export function computeTransformFlagsForNode(node: Node, subtreeFlags: TransformFlags): TransformFlags {
const kind = node.kind;
switch (kind) {
case SyntaxKind.CallExpression:
return computeCallExpression(<CallExpression>node, subtreeFlags);
case SyntaxKind.ModuleDeclaration:
return computeModuleDeclaration(<ModuleDeclaration>node, subtreeFlags);
case SyntaxKind.ParenthesizedExpression:
return computeParenthesizedExpression(<ParenthesizedExpression>node, subtreeFlags);
case SyntaxKind.BinaryExpression:
return computeBinaryExpression(<BinaryExpression>node, subtreeFlags);
case SyntaxKind.ExpressionStatement:
return computeExpressionStatement(<ExpressionStatement>node, subtreeFlags);
case SyntaxKind.Parameter:
return computeParameter(<ParameterDeclaration>node, subtreeFlags);
case SyntaxKind.ArrowFunction:
return computeArrowFunction(<ArrowFunction>node, subtreeFlags);
case SyntaxKind.FunctionExpression:
return computeFunctionExpression(<FunctionExpression>node, subtreeFlags);
case SyntaxKind.FunctionDeclaration:
return computeFunctionDeclaration(<FunctionDeclaration>node, subtreeFlags);
case SyntaxKind.VariableDeclaration:
return computeVariableDeclaration(<VariableDeclaration>node, subtreeFlags);
case SyntaxKind.VariableDeclarationList:
return computeVariableDeclarationList(<VariableDeclarationList>node, subtreeFlags);
case SyntaxKind.VariableStatement:
return computeVariableStatement(<VariableStatement>node, subtreeFlags);
case SyntaxKind.LabeledStatement:
return computeLabeledStatement(<LabeledStatement>node, subtreeFlags);
case SyntaxKind.ClassDeclaration:
return computeClassDeclaration(<ClassDeclaration>node, subtreeFlags);
case SyntaxKind.ClassExpression:
return computeClassExpression(<ClassExpression>node, subtreeFlags);
case SyntaxKind.HeritageClause:
return computeHeritageClause(<HeritageClause>node, subtreeFlags);
case SyntaxKind.ExpressionWithTypeArguments:
return computeExpressionWithTypeArguments(<ExpressionWithTypeArguments>node, subtreeFlags);
case SyntaxKind.Constructor:
return computeConstructor(<ConstructorDeclaration>node, subtreeFlags);
case SyntaxKind.PropertyDeclaration:
return computePropertyDeclaration(<PropertyDeclaration>node, subtreeFlags);
case SyntaxKind.MethodDeclaration:
return computeMethod(<MethodDeclaration>node, subtreeFlags);
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return computeAccessor(<AccessorDeclaration>node, subtreeFlags);
case SyntaxKind.ImportEqualsDeclaration:
return computeImportEquals(<ImportEqualsDeclaration>node, subtreeFlags);
case SyntaxKind.PropertyAccessExpression:
return computePropertyAccess(<PropertyAccessExpression>node, subtreeFlags);
default:
return computeOther(node, kind, subtreeFlags);
}
}
function computeCallExpression(node: CallExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const expression = node.expression;
const expressionKind = expression.kind;
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression
|| isSuperOrSuperProperty(expression, expressionKind)) {
// If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES6;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes;
}
function isSuperOrSuperProperty(node: Node, kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.SuperKeyword:
return true;
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ElementAccessExpression:
const expression = (<PropertyAccessExpression | ElementAccessExpression>node).expression;
const expressionKind = expression.kind;
return expressionKind === SyntaxKind.SuperKeyword;
}
return false;
}
function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const operatorTokenKind = node.operatorToken.kind;
const leftKind = node.left.kind;
if (operatorTokenKind === SyntaxKind.EqualsToken
&& (leftKind === SyntaxKind.ObjectLiteralExpression
|| leftKind === SyntaxKind.ArrayLiteralExpression)) {
// Destructuring assignments are ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.DestructuringAssignment;
}
else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken
|| operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) {
// Exponentiation is ES7 syntax.
transformFlags |= TransformFlags.AssertES7;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeParameter(node: ParameterDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const name = node.name;
const initializer = node.initializer;
const dotDotDotToken = node.dotDotDotToken;
// If the parameter has a question token, then it is TypeScript syntax.
if (node.questionToken) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If the parameter's name is 'this', then it is TypeScript syntax.
if (subtreeFlags & TransformFlags.ContainsDecorators
|| (name && isIdentifier(name) && name.originalKeywordKind === SyntaxKind.ThisKeyword)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If a parameter has an accessibility modifier, then it is TypeScript syntax.
if (modifierFlags & ModifierFlags.ParameterPropertyModifier) {
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments;
}
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsDefaultValueAssignments;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ParameterExcludes;
}
function computeParenthesizedExpression(node: ParenthesizedExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const expression = node.expression;
const expressionKind = expression.kind;
const expressionTransformFlags = expression.transformFlags;
// If the node is synthesized, it means the emitter put the parentheses there,
// not the user. If we didn't want them, the emitter would not have put them
// there.
if (expressionKind === SyntaxKind.AsExpression
|| expressionKind === SyntaxKind.TypeAssertionExpression) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If the expression of a ParenthesizedExpression is a destructuring assignment,
// then the ParenthesizedExpression is a destructuring assignment.
if (expressionTransformFlags & TransformFlags.DestructuringAssignment) {
transformFlags |= TransformFlags.DestructuringAssignment;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeClassDeclaration(node: ClassDeclaration, subtreeFlags: TransformFlags) {
let transformFlags: TransformFlags;
const modifierFlags = getModifierFlags(node);
if (modifierFlags & ModifierFlags.Ambient) {
// An ambient declaration is TypeScript syntax.
transformFlags = TransformFlags.AssertTypeScript;
}
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | TransformFlags.AssertES6;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax.
if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask)
|| (modifierFlags & ModifierFlags.Export)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
// A computed property name containing `this` might need to be rewritten,
// so propagate the ContainsLexicalThis flag upward.
transformFlags |= TransformFlags.ContainsLexicalThis;
}
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ClassExcludes;
}
function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) {
// A ClassExpression is ES6 syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
// A class with a parameter property assignment, property initializer, or decorator is
// TypeScript syntax.
if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
// A computed property name containing `this` might need to be rewritten,
// so propagate the ContainsLexicalThis flag upward.
transformFlags |= TransformFlags.ContainsLexicalThis;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ClassExcludes;
}
function computeHeritageClause(node: HeritageClause, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
switch (node.token) {
case SyntaxKind.ExtendsKeyword:
// An `extends` HeritageClause is ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
break;
case SyntaxKind.ImplementsKeyword:
// An `implements` HeritageClause is TypeScript syntax.
transformFlags |= TransformFlags.AssertTypeScript;
break;
default:
Debug.fail("Unexpected token for heritage clause");
break;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
// If an ExpressionWithTypeArguments contains type arguments, then it
// is TypeScript syntax.
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const body = node.body;
if (body === undefined) {
// An overload constructor is TypeScript syntax.
transformFlags |= TransformFlags.AssertTypeScript;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ConstructorExcludes;
}
function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) {
// A MethodDeclaration is ES6 syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
const modifierFlags = getModifierFlags(node);
const body = node.body;
const typeParameters = node.typeParameters;
const asteriskToken = node.asteriskToken;
// A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded,
// generic, or has a decorator.
if (!body
|| typeParameters
|| (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract))
|| (subtreeFlags & TransformFlags.ContainsDecorators)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// Currently, we only support generators that were originally async function bodies.
if (asteriskToken && node.emitFlags & NodeEmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.MethodOrAccessorExcludes;
}
function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const body = node.body;
// A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded,
// generic, or has a decorator.
if (!body
|| (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract))
|| (subtreeFlags & TransformFlags.ContainsDecorators)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.MethodOrAccessorExcludes;
}
function computePropertyDeclaration(node: PropertyDeclaration, subtreeFlags: TransformFlags) {
// A PropertyDeclaration is TypeScript syntax.
let transformFlags = subtreeFlags | TransformFlags.AssertTypeScript;
// If the PropertyDeclaration has an initializer, we need to inform its ancestor
// so that it handle the transformation.
if (node.initializer) {
transformFlags |= TransformFlags.ContainsPropertyInitializer;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeFunctionDeclaration(node: FunctionDeclaration, subtreeFlags: TransformFlags) {
let transformFlags: TransformFlags;
const modifierFlags = getModifierFlags(node);
const body = node.body;
const asteriskToken = node.asteriskToken;
if (!body || (modifierFlags & ModifierFlags.Ambient)) {
// An ambient declaration is TypeScript syntax.
// A FunctionDeclaration without a body is an overload and is TypeScript syntax.
transformFlags = TransformFlags.AssertTypeScript;
}
else {
transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion;
// If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax.
if (modifierFlags & ModifierFlags.Export) {
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6;
}
// If a FunctionDeclaration is async, then it is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If a FunctionDeclaration's subtree has marked the container as needing to capture the
// lexical this, or the function contains parameters with initializers, then this node is
// ES6 syntax.
if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES6;
}
// If a FunctionDeclaration is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
if (asteriskToken && node.emitFlags & NodeEmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.FunctionExcludes;
}
function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const modifierFlags = getModifierFlags(node);
const asteriskToken = node.asteriskToken;
// An async function expression is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If a FunctionExpression's subtree has marked the container as needing to capture the
// lexical this, or the function contains parameters with initializers, then this node is
// ES6 syntax.
if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) {
transformFlags |= TransformFlags.AssertES6;
}
// If a FunctionExpression is generator function and is the body of a
// transformed async function, then this node can be transformed to a
// down-level generator.
// Currently we do not support transforming any other generator fucntions
// down level.
if (asteriskToken && node.emitFlags & NodeEmitFlags.AsyncFunctionBody) {
transformFlags |= TransformFlags.AssertGenerator;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.FunctionExcludes;
}
function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) {
// An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
let transformFlags = subtreeFlags | TransformFlags.AssertES6;
const modifierFlags = getModifierFlags(node);
// An async arrow function is TypeScript syntax.
if (modifierFlags & ModifierFlags.Async) {
transformFlags |= TransformFlags.AssertTypeScript;
}
// If an ArrowFunction contains a lexical this, its container must capture the lexical this.
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ArrowFunctionExcludes;
}
function computePropertyAccess(node: PropertyAccessExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const expression = node.expression;
const expressionKind = expression.kind;
// If a PropertyAccessExpression starts with a super keyword, then it is
// ES6 syntax, and requires a lexical `this` binding.
if (expressionKind === SyntaxKind.SuperKeyword) {
transformFlags |= TransformFlags.ContainsLexicalThis;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const nameKind = node.name.kind;
// A VariableDeclaration with a binding pattern is ES6 syntax.
if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeVariableStatement(node: VariableStatement, subtreeFlags: TransformFlags) {
let transformFlags: TransformFlags;
const modifierFlags = getModifierFlags(node);
const declarationListTransformFlags = node.declarationList.transformFlags;
// An ambient declaration is TypeScript syntax.
if (modifierFlags & ModifierFlags.Ambient) {
transformFlags = TransformFlags.AssertTypeScript;
}
else {
transformFlags = subtreeFlags;
// If a VariableStatement is exported, then it is either ES6 or TypeScript syntax.
if (modifierFlags & ModifierFlags.Export) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript;
}
if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) {
transformFlags |= TransformFlags.AssertES6;
}
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeLabeledStatement(node: LabeledStatement, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
// A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding
&& isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
transformFlags |= TransformFlags.AssertES6;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeImportEquals(node: ImportEqualsDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
// An ImportEqualsDeclaration with a namespace reference is TypeScript.
if (!isExternalModuleImportEqualsDeclaration(node)) {
transformFlags |= TransformFlags.AssertTypeScript;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeExpressionStatement(node: ExpressionStatement, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
// If the expression of an expression statement is a destructuring assignment,
// then we treat the statement as ES6 so that we can indicate that we do not
// need to hold on to the right-hand side.
if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) {
transformFlags |= TransformFlags.AssertES6;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeModuleDeclaration(node: ModuleDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = TransformFlags.AssertTypeScript;
const modifierFlags = getModifierFlags(node);
if ((modifierFlags & ModifierFlags.Ambient) === 0) {
transformFlags |= subtreeFlags;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ModuleExcludes;
}
function computeVariableDeclarationList(node: VariableDeclarationList, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion;
if (subtreeFlags & TransformFlags.ContainsBindingPattern) {
transformFlags |= TransformFlags.AssertES6;
}
// If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
if (node.flags & NodeFlags.BlockScoped) {
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBlockScopedBinding;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.VariableDeclarationListExcludes;
}
function computeOther(node: Node, kind: SyntaxKind, subtreeFlags: TransformFlags) {
// Mark transformations needed for each node
let transformFlags = subtreeFlags;
let excludeFlags = TransformFlags.NodeExcludes;
switch (kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.AbstractKeyword:
case SyntaxKind.DeclareKeyword:
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.AwaitExpression:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.ReadonlyKeyword:
// These nodes are TypeScript syntax.
transformFlags |= TransformFlags.AssertTypeScript;
break;
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxText:
case SyntaxKind.JsxClosingElement:
case SyntaxKind.JsxAttribute:
case SyntaxKind.JsxSpreadAttribute:
case SyntaxKind.JsxExpression:
// These nodes are Jsx syntax.
transformFlags |= TransformFlags.AssertJsx;
break;
case SyntaxKind.ExportKeyword:
// This node is both ES6 and TypeScript syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript;
break;
case SyntaxKind.DefaultKeyword:
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.TemplateHead:
case SyntaxKind.TemplateMiddle:
case SyntaxKind.TemplateTail:
case SyntaxKind.TemplateExpression:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.ForOfStatement:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
break;
case SyntaxKind.YieldExpression:
// This node is ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsYield;
break;
case SyntaxKind.AnyKeyword:
case SyntaxKind.NumberKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.TypeParameter:
case SyntaxKind.PropertySignature:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
case SyntaxKind.TypePredicate:
case SyntaxKind.TypeReference:
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeLiteral:
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.ParenthesizedType:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ThisType:
case SyntaxKind.LiteralType:
// Types and signatures are TypeScript syntax, and exclude all other facts.
transformFlags = TransformFlags.AssertTypeScript;
excludeFlags = TransformFlags.TypeExcludes;
break;
case SyntaxKind.ComputedPropertyName:
// Even though computed property names are ES6, we don't treat them as such.
// This is so that they can flow through PropertyName transforms unaffected.
// Instead, we mark the container as ES6, so that it can properly handle the transform.
transformFlags |= TransformFlags.ContainsComputedPropertyName;
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
// A computed method name like `[this.getName()](x: string) { ... }` needs to
// distinguish itself from the normal case of a method body containing `this`:
// `this` inside a method doesn't need to be rewritten (the method provides `this`),
// whereas `this` inside a computed name *might* need to be rewritten if the class/object
// is inside an arrow function:
// `_this = this; () => class K { [_this.getName()]() { ... } }`
// To make this distinction, use ContainsLexicalThisInComputedPropertyName
// instead of ContainsLexicalThis for computed property names
transformFlags |= TransformFlags.ContainsLexicalThisInComputedPropertyName;
}
break;
case SyntaxKind.SpreadElementExpression:
// This node is ES6 syntax, but is handled by a containing node.
transformFlags |= TransformFlags.ContainsSpreadElementExpression;
break;
case SyntaxKind.SuperKeyword:
// This node is ES6 syntax.
transformFlags |= TransformFlags.AssertES6;
break;
case SyntaxKind.ThisKeyword:
// Mark this node and its ancestors as containing a lexical `this` keyword.
transformFlags |= TransformFlags.ContainsLexicalThis;
break;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
// These nodes are ES6 syntax.
transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern;
break;
case SyntaxKind.Decorator:
// This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsDecorators;
break;
case SyntaxKind.ObjectLiteralExpression:
excludeFlags = TransformFlags.ObjectLiteralExcludes;
if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) {
// If an ObjectLiteralExpression contains a ComputedPropertyName, then it
// is an ES6 node.
transformFlags |= TransformFlags.AssertES6;
}
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
// A computed property name containing `this` might need to be rewritten,
// so propagate the ContainsLexicalThis flag upward.
transformFlags |= TransformFlags.ContainsLexicalThis;
}
break;
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.NewExpression:
excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes;
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
// If the this node contains a SpreadElementExpression, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES6;
}
break;
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
// A loop containing a block scoped binding *may* need to be transformed from ES6.
if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) {
transformFlags |= TransformFlags.AssertES6;
}
break;
case SyntaxKind.SourceFile:
if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) {
transformFlags |= TransformFlags.AssertES6;
}
break;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ContinueStatement:
case SyntaxKind.BreakStatement:
transformFlags |= TransformFlags.ContainsHoistedDeclarationOrCompletion;
break;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~excludeFlags;
}
}
+535 -300
View File
File diff suppressed because it is too large Load Diff
+12 -7
View File
@@ -30,6 +30,7 @@ namespace ts {
{
name: "extendedDiagnostics",
type: "boolean",
experimental: true
},
{
name: "emitBOM",
@@ -433,6 +434,11 @@ namespace ts {
name: "strictNullChecks",
type: "boolean",
description: Diagnostics.Enable_strict_null_checks
},
{
name: "importHelpers",
type: "boolean",
description: Diagnostics.Import_emit_helpers_from_tslib
}
];
@@ -852,14 +858,13 @@ namespace ts {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
else {
// By default, exclude common package folders
// By default, exclude common package folders and the outDir
excludeSpecs = ["node_modules", "bower_components", "jspm_packages"];
}
// Always exclude the output directory unless explicitly included
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
excludeSpecs.push(outDir);
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
excludeSpecs.push(outDir);
}
}
if (fileNames === undefined && includeSpecs === undefined) {
@@ -885,7 +890,7 @@ namespace ts {
function convertCompilerOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions {
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {};
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {};
convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
+352
View File
@@ -0,0 +1,352 @@
/// <reference path="sourcemap.ts" />
/* @internal */
namespace ts {
export interface CommentWriter {
reset(): void;
setSourceFile(sourceFile: SourceFile): void;
emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void;
emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void;
emitTrailingCommentsOfPosition(pos: number): void;
}
export function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter {
const compilerOptions = host.getCompilerOptions();
const extendedDiagnostics = compilerOptions.extendedDiagnostics;
const newLine = host.getNewLine();
const { emitPos } = sourceMap;
let containerPos = -1;
let containerEnd = -1;
let declarationListContainerEnd = -1;
let currentSourceFile: SourceFile;
let currentText: string;
let currentLineMap: number[];
let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[];
let hasWrittenComment = false;
let disabled: boolean = compilerOptions.removeComments;
return {
reset,
setSourceFile,
emitNodeWithComments,
emitBodyWithDetachedComments,
emitTrailingCommentsOfPosition,
};
function emitNodeWithComments(node: Node, emitCallback: (node: Node) => void) {
if (disabled) {
emitCallback(node);
return;
}
if (node) {
const { pos, end } = node.commentRange || node;
const emitFlags = node.emitFlags;
if ((pos < 0 && end < 0) || (pos === end)) {
// Both pos and end are synthesized, so just emit the node without comments.
if (emitFlags & NodeEmitFlags.NoNestedComments) {
disableCommentsAndEmit(node, emitCallback);
}
else {
emitCallback(node);
}
}
else {
if (extendedDiagnostics) {
performance.mark("preEmitNodeWithComment");
}
const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement;
const skipLeadingComments = pos < 0 || (emitFlags & NodeEmitFlags.NoLeadingComments) !== 0;
const skipTrailingComments = end < 0 || (emitFlags & NodeEmitFlags.NoTrailingComments) !== 0;
// Emit leading comments if the position is not synthesized and the node
// has not opted out from emitting leading comments.
if (!skipLeadingComments) {
emitLeadingComments(pos, isEmittedNode);
}
// Save current container state on the stack.
const savedContainerPos = containerPos;
const savedContainerEnd = containerEnd;
const savedDeclarationListContainerEnd = declarationListContainerEnd;
if (!skipLeadingComments) {
containerPos = pos;
}
if (!skipTrailingComments) {
containerEnd = end;
// To avoid invalid comment emit in a down-level binding pattern, we
// keep track of the last declaration list container's end
if (node.kind === SyntaxKind.VariableDeclarationList) {
declarationListContainerEnd = end;
}
}
if (extendedDiagnostics) {
performance.measure("commentTime", "preEmitNodeWithComment");
}
if (emitFlags & NodeEmitFlags.NoNestedComments) {
disableCommentsAndEmit(node, emitCallback);
}
else {
emitCallback(node);
}
if (extendedDiagnostics) {
performance.mark("beginEmitNodeWithComment");
}
// Restore previous container state.
containerPos = savedContainerPos;
containerEnd = savedContainerEnd;
declarationListContainerEnd = savedDeclarationListContainerEnd;
// Emit trailing comments if the position is not synthesized and the node
// has not opted out from emitting leading comments and is an emitted node.
if (!skipTrailingComments && isEmittedNode) {
emitTrailingComments(end);
}
if (extendedDiagnostics) {
performance.measure("commentTime", "beginEmitNodeWithComment");
}
}
}
}
function emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void) {
if (extendedDiagnostics) {
performance.mark("preEmitBodyWithDetachedComments");
}
const { pos, end } = detachedRange;
const emitFlags = node.emitFlags;
const skipLeadingComments = pos < 0 || (emitFlags & NodeEmitFlags.NoLeadingComments) !== 0;
const skipTrailingComments = disabled || end < 0 || (emitFlags & NodeEmitFlags.NoTrailingComments) !== 0;
if (!skipLeadingComments) {
emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
}
if (extendedDiagnostics) {
performance.measure("commentTime", "preEmitBodyWithDetachedComments");
}
if (emitFlags & NodeEmitFlags.NoNestedComments) {
disableCommentsAndEmit(node, emitCallback);
}
else {
emitCallback(node);
}
if (extendedDiagnostics) {
performance.mark("beginEmitBodyWithDetachedCommetns");
}
if (!skipTrailingComments) {
emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
}
if (extendedDiagnostics) {
performance.measure("commentTime", "beginEmitBodyWithDetachedCommetns");
}
}
function emitLeadingComments(pos: number, isEmittedNode: boolean) {
hasWrittenComment = false;
if (isEmittedNode) {
forEachLeadingCommentToEmit(pos, emitLeadingComment);
}
else if (pos === 0) {
// If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
// unless it is a triple slash comment at the top of the file.
// For Example:
// /// <reference-path ...>
// declare var x;
// /// <reference-path ...>
// interface F {}
// The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
}
}
function emitTripleSlashLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
if (isTripleSlashComment(commentPos, commentEnd)) {
emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
}
}
function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) {
if (!hasWrittenComment) {
emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos);
hasWrittenComment = true;
}
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
emitPos(commentPos);
writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
emitPos(commentEnd);
if (hasTrailingNewLine) {
writer.writeLine();
}
else {
writer.write(" ");
}
}
function emitTrailingComments(pos: number) {
forEachTrailingCommentToEmit(pos, emitTrailingComment);
}
function emitTrailingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) {
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
if (!writer.isAtStartOfLine()) {
writer.write(" ");
}
emitPos(commentPos);
writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
emitPos(commentEnd);
if (hasTrailingNewLine) {
writer.writeLine();
}
}
function emitTrailingCommentsOfPosition(pos: number) {
if (disabled) {
return;
}
if (extendedDiagnostics) {
performance.mark("beforeEmitTrailingCommentsOfPosition");
}
forEachTrailingCommentToEmit(pos, emitTrailingCommentOfPosition);
if (extendedDiagnostics) {
performance.measure("commentTime", "beforeEmitTrailingCommentsOfPosition");
}
}
function emitTrailingCommentOfPosition(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) {
// trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
emitPos(commentPos);
writeCommentRange(currentText, currentLineMap, writer, commentPos, commentEnd, newLine);
emitPos(commentEnd);
if (hasTrailingNewLine) {
writer.writeLine();
}
else {
writer.write(" ");
}
}
function forEachLeadingCommentToEmit(pos: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) {
// Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
if (containerPos === -1 || pos !== containerPos) {
if (hasDetachedComments(pos)) {
forEachLeadingCommentWithoutDetachedComments(cb);
}
else {
forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos);
}
}
}
function forEachTrailingCommentToEmit(end: number, cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean) => void) {
// Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
if (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd)) {
forEachTrailingCommentRange(currentText, end, cb);
}
}
function reset() {
currentSourceFile = undefined;
currentText = undefined;
currentLineMap = undefined;
detachedCommentsInfo = undefined;
}
function setSourceFile(sourceFile: SourceFile) {
currentSourceFile = sourceFile;
currentText = currentSourceFile.text;
currentLineMap = getLineStarts(currentSourceFile);
detachedCommentsInfo = undefined;
}
function disableCommentsAndEmit(node: Node, emitCallback: (node: Node) => void): void {
if (disabled) {
emitCallback(node);
}
else {
disabled = true;
emitCallback(node);
disabled = false;
}
}
function hasDetachedComments(pos: number) {
return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos;
}
function forEachLeadingCommentWithoutDetachedComments(cb: (commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) => void) {
// get the leading comments from detachedPos
const pos = lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos;
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
else {
detachedCommentsInfo = undefined;
}
forEachLeadingCommentRange(currentText, pos, cb, /*state*/ pos);
}
function emitDetachedCommentsAndUpdateCommentsInfo(range: TextRange) {
const currentDetachedCommentInfo = emitDetachedComments(currentText, currentLineMap, writer, writeComment, range, newLine, disabled);
if (currentDetachedCommentInfo) {
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
}
else {
detachedCommentsInfo = [currentDetachedCommentInfo];
}
}
}
function writeComment(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) {
emitPos(commentPos);
writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
emitPos(commentEnd);
}
/**
* Determine if the given comment is a triple-slash
*
* @return true if the comment is a triple-slash comment else false
**/
function isTripleSlashComment(commentPos: number, commentEnd: number) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
if (currentText.charCodeAt(commentPos + 1) === CharacterCodes.slash &&
commentPos + 2 < commentEnd &&
currentText.charCodeAt(commentPos + 2) === CharacterCodes.slash) {
const textSubStr = currentText.substring(commentPos, commentEnd);
return textSubStr.match(fullTripleSlashReferencePathRegEx) ||
textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ?
true : false;
}
return false;
}
}
}
+315 -45
View File
@@ -113,6 +113,23 @@ namespace ts {
return undefined;
}
/**
* Iterates through `array` by index and performs the callback on each element of array until the callback
* returns a falsey value, then returns false.
* If no such value is found, the callback is applied to each element of array and `true` is returned.
*/
export function every<T>(array: T[], callback: (element: T, index: number) => boolean): boolean {
if (array) {
for (let i = 0, len = array.length; i < len; i++) {
if (!callback(array[i], i)) {
return false;
}
}
}
return true;
}
/** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */
export function find<T>(array: T[], predicate: (element: T, index: number) => boolean): T | undefined {
for (let i = 0, len = array.length; i < len; i++) {
@@ -169,11 +186,12 @@ namespace ts {
return -1;
}
export function countWhere<T>(array: T[], predicate: (x: T) => boolean): number {
export function countWhere<T>(array: T[], predicate: (x: T, i: number) => boolean): number {
let count = 0;
if (array) {
for (const v of array) {
if (predicate(v)) {
for (let i = 0; i < array.length; i++) {
const v = array[i];
if (predicate(v, i)) {
count++;
}
}
@@ -185,6 +203,8 @@ namespace ts {
* Filters an array by a predicate function. Returns the same array instance if the predicate is
* true for all elements, otherwise returns a new array instance containing the filtered subset.
*/
export function filter<T, U extends T>(array: T[], f: (x: T) => x is U): U[];
export function filter<T>(array: T[], f: (x: T) => boolean): T[]
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
if (array) {
const len = array.length;
@@ -232,22 +252,135 @@ namespace ts {
array.length = outIndex;
}
export function map<T, U>(array: T[], f: (x: T) => U): U[] {
export function map<T, U>(array: T[], f: (x: T, i: number) => U): U[] {
let result: U[];
if (array) {
result = [];
for (const v of array) {
result.push(f(v));
for (let i = 0; i < array.length; i++) {
const v = array[i];
result.push(f(v, i));
}
}
return result;
}
/**
* Flattens an array containing a mix of array or non-array elements.
*
* @param array The array to flatten.
*/
export function flatten<T>(array: (T | T[])[]): T[] {
let result: T[];
if (array) {
result = [];
for (const v of array) {
if (v) {
if (isArray(v)) {
addRange(result, v);
}
else {
result.push(v);
}
}
}
}
return result;
}
/**
* Maps an array. If the mapped value is an array, it is spread into the result.
*
* @param array The array to map.
* @param mapfn The callback used to map the result into one or more values.
*/
export function flatMap<T, U>(array: T[], mapfn: (x: T, i: number) => U | U[]): U[] {
let result: U[];
if (array) {
result = [];
for (let i = 0; i < array.length; i++) {
const v = mapfn(array[i], i);
if (v) {
if (isArray(v)) {
addRange(result, v);
}
else {
result.push(v);
}
}
}
}
return result;
}
/**
* Computes the first matching span of elements and returns a tuple of the first span
* and the remaining elements.
*/
export function span<T>(array: T[], f: (x: T, i: number) => boolean): [T[], T[]] {
if (array) {
for (let i = 0; i < array.length; i++) {
if (!f(array[i], i)) {
return [array.slice(0, i), array.slice(i)];
}
}
return [array.slice(0), []];
}
return undefined;
}
/**
* Maps contiguous spans of values with the same key.
*
* @param array The array to map.
* @param keyfn A callback used to select the key for an element.
* @param mapfn A callback used to map a contiguous chunk of values to a single value.
*/
export function spanMap<T, K, U>(array: T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] {
let result: U[];
if (array) {
result = [];
const len = array.length;
let previousKey: K;
let key: K;
let start = 0;
let pos = 0;
while (start < len) {
while (pos < len) {
const value = array[pos];
key = keyfn(value, pos);
if (pos === 0) {
previousKey = key;
}
else if (key !== previousKey) {
break;
}
pos++;
}
if (start < pos) {
const v = mapfn(array.slice(start, pos), previousKey, start, pos);
if (v) {
result.push(v);
}
start = pos;
}
previousKey = key;
pos++;
}
}
return result;
}
export function concatenate<T>(array1: T[], array2: T[]): T[] {
if (!array2 || !array2.length) return array1;
if (!array1 || !array1.length) return array2;
return array1.concat(array2);
return [...array1, ...array2];
}
export function deduplicate<T>(array: T[], areEqual?: (a: T, b: T) => boolean): T[] {
@@ -266,6 +399,27 @@ namespace ts {
return result;
}
/**
* Compacts an array, removing any falsey elements.
*/
export function compact<T>(array: T[]): T[] {
let result: T[];
if (array) {
for (let i = 0; i < array.length; i++) {
const v = array[i];
if (result || !v) {
if (!result) {
result = array.slice(0, i);
}
if (v) {
result.push(v);
}
}
}
}
return result || array;
}
export function sum(array: any[], prop: string): number {
let result = 0;
for (const v of array) {
@@ -277,7 +431,9 @@ namespace ts {
export function addRange<T>(to: T[], from: T[]): void {
if (to && from) {
for (const v of from) {
to.push(v);
if (v !== undefined) {
to.push(v);
}
}
}
}
@@ -292,15 +448,31 @@ namespace ts {
return true;
}
export function firstOrUndefined<T>(array: T[]): T {
return array && array.length > 0
? array[0]
: undefined;
}
export function singleOrUndefined<T>(array: T[]): T {
return array && array.length === 1
? array[0]
: undefined;
}
export function singleOrMany<T>(array: T[]): T | T[] {
return array && array.length === 1
? array[0]
: array;
}
/**
* Returns the last element of an array if non-empty, undefined otherwise.
*/
export function lastOrUndefined<T>(array: T[]): T {
if (array.length === 0) {
return undefined;
}
return array[array.length - 1];
return array && array.length > 0
? array[array.length - 1]
: undefined;
}
/**
@@ -332,14 +504,15 @@ namespace ts {
return ~low;
}
export function reduceLeft<T>(array: T[], f: (a: T, x: T) => T): T;
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
const count = array.length;
if (count > 0) {
let pos = 0;
let result: T | U;
export function reduceLeft<T, U>(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
export function reduceLeft<T>(array: T[], f: (memo: T, value: T, i: number) => T): T;
export function reduceLeft<T>(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T {
if (array && array.length > 0) {
const size = array.length;
if (size > 0) {
let pos = start === undefined || start < 0 ? 0 : start;
const end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
let result: T;
if (arguments.length <= 2) {
result = array[pos];
pos++;
@@ -347,23 +520,25 @@ namespace ts {
else {
result = initial;
}
while (pos < count) {
result = f(<U>result, array[pos]);
while (pos <= end) {
result = f(result, array[pos], pos);
pos++;
}
return <U>result;
return result;
}
}
return initial;
}
export function reduceRight<T>(array: T[], f: (a: T, x: T) => T): T;
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
export function reduceRight<T, U>(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U;
export function reduceRight<T>(array: T[], f: (memo: T, value: T, i: number) => T): T;
export function reduceRight<T>(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T {
if (array) {
let pos = array.length - 1;
if (pos >= 0) {
let result: T | U;
const size = array.length;
if (size > 0) {
let pos = start === undefined || start > size - 1 ? size - 1 : start;
const end = count === undefined || pos - count < 0 ? 0 : pos - count;
let result: T;
if (arguments.length <= 2) {
result = array[pos];
pos--;
@@ -371,11 +546,11 @@ namespace ts {
else {
result = initial;
}
while (pos >= 0) {
result = f(<U>result, array[pos]);
while (pos >= end) {
result = f(result, array[pos], pos);
pos--;
}
return <U>result;
return result;
}
}
return initial;
@@ -539,6 +714,15 @@ namespace ts {
return result;
}
export function isEmpty<T>(map: Map<T>) {
for (const id in map) {
if (hasProperty(map, id)) {
return false;
}
}
return true;
}
export function cloneMap<T>(map: Map<T>) {
const clone = createMap<T>();
copyProperties(map, clone);
@@ -566,6 +750,36 @@ namespace ts {
return result;
}
/**
* Adds the value to an array of values associated with the key, and returns the array.
* Creates the array if it does not already exist.
*/
export function multiMapAdd<V>(map: Map<V[]>, key: string, value: V): V[] {
const values = map[key];
if (values) {
values.push(value);
return values;
}
else {
return map[key] = [value];
}
}
/**
* Removes a value from an array of values associated with the key.
* Does not preserve the order of those values.
* Does nothing if `key` is not in `map`, or `value` is not in `map[key]`.
*/
export function multiMapRemove<V>(map: Map<V[]>, key: string, value: V): void {
const values = map[key];
if (values) {
unorderedRemoveItem(values, value);
if (!values.length) {
delete map[key];
}
}
}
/**
* Tests whether a value is an array.
*/
@@ -1453,11 +1667,16 @@ namespace ts {
}
function Node(this: Node, kind: SyntaxKind, pos: number, end: number) {
this.id = 0;
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = NodeFlags.None;
this.modifierFlagsCache = ModifierFlags.None;
this.transformFlags = TransformFlags.None;
this.parent = undefined;
this.original = undefined;
this.transformId = 0;
}
export let objectAllocator: ObjectAllocator = {
@@ -1478,10 +1697,13 @@ namespace ts {
}
export namespace Debug {
const currentAssertionLevel = AssertionLevel.None;
declare var process: any;
declare var require: any;
let currentAssertionLevel: AssertionLevel;
export function shouldAssert(level: AssertionLevel): boolean {
return currentAssertionLevel >= level;
return getCurrentAssertionLevel() >= level;
}
export function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void {
@@ -1498,22 +1720,70 @@ namespace ts {
export function fail(message?: string): void {
Debug.assert(/*expression*/ false, message);
}
function getCurrentAssertionLevel() {
if (currentAssertionLevel !== undefined) {
return currentAssertionLevel;
}
if (sys === undefined) {
return AssertionLevel.None;
}
const developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV"));
currentAssertionLevel = developmentMode
? AssertionLevel.Normal
: AssertionLevel.None;
return currentAssertionLevel;
}
}
export function copyListRemovingItem<T>(item: T, list: T[]) {
const copiedList: T[] = [];
for (const e of list) {
if (e !== item) {
copiedList.push(e);
export function getEnvironmentVariable(name: string, host?: CompilerHost) {
if (host && host.getEnvironmentVariable) {
return host.getEnvironmentVariable(name);
}
if (sys && sys.getEnvironmentVariable) {
return sys.getEnvironmentVariable(name);
}
return "";
}
/** Remove an item from an array, moving everything to its right one space left. */
export function orderedRemoveItemAt<T>(array: T[], index: number): void {
// This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
for (let i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
array.pop();
}
export function unorderedRemoveItemAt<T>(array: T[], index: number): void {
// Fill in the "hole" left at `index`.
array[index] = array[array.length - 1];
array.pop();
}
/** Remove the *first* occurrence of `item` from the array. */
export function unorderedRemoveItem<T>(array: T[], item: T): void {
unorderedRemoveFirstItemWhere(array, element => element === item);
}
/** Remove the *first* element satisfying `predicate`. */
function unorderedRemoveFirstItemWhere<T>(array: T[], predicate: (element: T) => boolean): void {
for (let i = 0; i < array.length; i++) {
if (predicate(array[i])) {
unorderedRemoveItemAt(array, i);
break;
}
}
return copiedList;
}
export function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string {
return useCaseSensitivefileNames
export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string {
return useCaseSensitiveFileNames
? ((fileName) => fileName)
: ((fileName) => fileName.toLowerCase());
}
}
+33 -30
View File
@@ -374,7 +374,7 @@ namespace ts {
const jsDocComments = getJsDocCommentsFromText(declaration, currentText);
emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange);
emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeCommentRange);
}
}
@@ -655,12 +655,13 @@ namespace ts {
function emitModuleElementDeclarationFlags(node: Node) {
// If the node is parented in the current source file we need to emit export declare or just export
if (node.parent.kind === SyntaxKind.SourceFile) {
const modifiers = getModifierFlags(node);
// If the node is exported
if (node.flags & NodeFlags.Export) {
if (modifiers & ModifierFlags.Export) {
write("export ");
}
if (node.flags & NodeFlags.Default) {
if (modifiers & ModifierFlags.Default) {
write("default ");
}
else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) {
@@ -669,21 +670,21 @@ namespace ts {
}
}
function emitClassMemberDeclarationFlags(flags: NodeFlags) {
if (flags & NodeFlags.Private) {
function emitClassMemberDeclarationFlags(flags: ModifierFlags) {
if (flags & ModifierFlags.Private) {
write("private ");
}
else if (flags & NodeFlags.Protected) {
else if (flags & ModifierFlags.Protected) {
write("protected ");
}
if (flags & NodeFlags.Static) {
if (flags & ModifierFlags.Static) {
write("static ");
}
if (flags & NodeFlags.Readonly) {
if (flags & ModifierFlags.Readonly) {
write("readonly ");
}
if (flags & NodeFlags.Abstract) {
if (flags & ModifierFlags.Abstract) {
write("abstract ");
}
}
@@ -692,7 +693,7 @@ namespace ts {
// note usage of writer. methods instead of aliases created, just to make sure we are using
// correct writer especially to handle asynchronous alias writing
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
if (hasModifier(node, ModifierFlags.Export)) {
write("export ");
}
write("import ");
@@ -731,7 +732,7 @@ namespace ts {
function writeImportDeclaration(node: ImportDeclaration) {
emitJsDocComments(node);
if (node.flags & NodeFlags.Export) {
if (hasModifier(node, ModifierFlags.Export)) {
write("export ");
}
write("import ");
@@ -926,7 +927,7 @@ namespace ts {
}
function isPrivateMethodTypeParameter(node: TypeParameterDeclaration) {
return node.parent.kind === SyntaxKind.MethodDeclaration && (node.parent.flags & NodeFlags.Private);
return node.parent.kind === SyntaxKind.MethodDeclaration && hasModifier(node.parent, ModifierFlags.Private);
}
function emitTypeParameters(typeParameters: TypeParameterDeclaration[]) {
@@ -976,7 +977,7 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.parent.flags & NodeFlags.Static) {
if (hasModifier(node.parent, ModifierFlags.Static)) {
diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
}
else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
@@ -1055,7 +1056,7 @@ namespace ts {
function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) {
if (constructorDeclaration) {
forEach(constructorDeclaration.parameters, param => {
if (param.flags & NodeFlags.ParameterPropertyModifier) {
if (hasModifier(param, ModifierFlags.ParameterPropertyModifier)) {
emitPropertyDeclaration(param);
}
});
@@ -1064,7 +1065,7 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (node.flags & NodeFlags.Abstract) {
if (hasModifier(node, ModifierFlags.Abstract)) {
write("abstract ");
}
@@ -1114,7 +1115,7 @@ namespace ts {
}
emitJsDocComments(node);
emitClassMemberDeclarationFlags(node.flags);
emitClassMemberDeclarationFlags(getModifierFlags(node));
emitVariableDeclaration(<VariableDeclaration>node);
write(";");
writeLine();
@@ -1132,14 +1133,16 @@ namespace ts {
// it if it's not a well known symbol. In that case, the text of the name will be exactly
// what we want, namely the name expression enclosed in brackets.
writeTextOfNode(currentText, node.name);
// If optional property emit ?
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.Parameter) && hasQuestionToken(node)) {
// If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor
// we don't want to emit property declaration with "?"
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature ||
(node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) {
write("?");
}
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!(node.flags & NodeFlags.Private)) {
else if (!hasModifier(node, ModifierFlags.Private)) {
writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError);
}
}
@@ -1156,7 +1159,7 @@ namespace ts {
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (node.flags & NodeFlags.Static) {
if (hasModifier(node, ModifierFlags.Static)) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
@@ -1267,9 +1270,9 @@ namespace ts {
if (node === accessors.firstAccessor) {
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node.flags | (accessors.setAccessor ? 0 : NodeFlags.Readonly));
emitClassMemberDeclarationFlags(getModifierFlags(node) | (accessors.setAccessor ? 0 : ModifierFlags.Readonly));
writeTextOfNode(currentText, node.name);
if (!(node.flags & NodeFlags.Private)) {
if (!hasModifier(node, ModifierFlags.Private)) {
accessorWithTypeAnnotation = node;
let type = getTypeAnnotationFromAccessor(node);
if (!type) {
@@ -1300,7 +1303,7 @@ namespace ts {
let diagnosticMessage: DiagnosticMessage;
if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) {
// Setters have to have type named and cannot infer it so, the type should always be named
if (accessorWithTypeAnnotation.parent.flags & NodeFlags.Static) {
if (hasModifier(accessorWithTypeAnnotation.parent, ModifierFlags.Static)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1;
@@ -1318,7 +1321,7 @@ namespace ts {
};
}
else {
if (accessorWithTypeAnnotation.flags & NodeFlags.Static) {
if (hasModifier(accessorWithTypeAnnotation, ModifierFlags.Static)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
@@ -1354,7 +1357,7 @@ namespace ts {
emitModuleElementDeclarationFlags(node);
}
else if (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.Constructor) {
emitClassMemberDeclarationFlags(node.flags);
emitClassMemberDeclarationFlags(getModifierFlags(node));
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
write("function ");
@@ -1385,7 +1388,7 @@ namespace ts {
if (node.kind === SyntaxKind.IndexSignature) {
// Index signature can have readonly modifier
emitClassMemberDeclarationFlags(node.flags);
emitClassMemberDeclarationFlags(getModifierFlags(node));
write("[");
}
else {
@@ -1426,7 +1429,7 @@ namespace ts {
emitType(node.type);
}
}
else if (node.kind !== SyntaxKind.Constructor && !(node.flags & NodeFlags.Private)) {
else if (node.kind !== SyntaxKind.Constructor && !hasModifier(node, ModifierFlags.Private)) {
writeReturnTypeAtSignature(node, getReturnTypeVisibilityError);
}
@@ -1466,7 +1469,7 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.flags & NodeFlags.Static) {
if (hasModifier(node, ModifierFlags.Static)) {
diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
@@ -1532,7 +1535,7 @@ namespace ts {
node.parent.parent.kind === SyntaxKind.TypeLiteral) {
emitTypeOfVariableDeclarationFromTypeLiteral(node);
}
else if (!(node.parent.flags & NodeFlags.Private)) {
else if (!hasModifier(node.parent, ModifierFlags.Private)) {
writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError);
}
@@ -1568,7 +1571,7 @@ namespace ts {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
if (node.parent.flags & NodeFlags.Static) {
if (hasModifier(node.parent, ModifierFlags.Static)) {
return symbolAccessibilityResult.errorModuleName ?
symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
+14 -10
View File
@@ -827,10 +827,6 @@
"category": "Error",
"code": 1308
},
"Async functions are only available when targeting ECMAScript 2015 or higher.": {
"category": "Error",
"code": 1311
},
"'=' can only be used in an object literal property inside a destructuring assignment.": {
"category": "Error",
"code": 1312
@@ -1703,7 +1699,7 @@
"category": "Error",
"code": 2521
},
"The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression.": {
"The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method.": {
"category": "Error",
"code": 2522
},
@@ -2840,6 +2836,10 @@
"category": "Error",
"code": 6138
},
"Import emit helpers from 'tslib'.": {
"category": "Message",
"code": 6139
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@@ -2871,11 +2871,7 @@
"Element implicitly has an 'any' type because index expression is not of type 'number'.": {
"category": "Error",
"code": 7015
},
"Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation.": {
"category": "Error",
"code": 7016
},
},
"Index signature of object type implicitly has an 'any' type.": {
"category": "Error",
"code": 7017
@@ -2932,6 +2928,14 @@
"category": "Error",
"code": 7031
},
"Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation.": {
"category": "Error",
"code": 7032
},
"Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation.": {
"category": "Error",
"code": 7033
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
+2838 -8297
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+120 -123
View File
@@ -1,5 +1,6 @@
/// <reference path="utilities.ts"/>
/// <reference path="scanner.ts"/>
/// <reference path="factory.ts"/>
namespace ts {
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
@@ -417,6 +418,8 @@ namespace ts {
case SyntaxKind.JSDocPropertyTag:
return visitNode(cbNode, (<JSDocPropertyTag>node).typeExpression) ||
visitNode(cbNode, (<JSDocPropertyTag>node).name);
case SyntaxKind.PartiallyEmittedExpression:
return visitNode(cbNode, (<PartiallyEmittedExpression>node).expression);
case SyntaxKind.JSDocLiteralType:
return visitNode(cbNode, (<JSDocLiteralType>node).literal);
}
@@ -902,6 +905,10 @@ namespace ts {
return currentToken = scanner.scanJsxToken();
}
function scanJsxAttributeValue(): SyntaxKind {
return currentToken = scanner.scanJsxAttributeValue();
}
function speculationHelper<T>(callback: () => T, isLookAhead: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
@@ -1053,6 +1060,16 @@ namespace ts {
new TokenConstructor(kind, pos, pos);
}
function createNodeArray<T extends Node>(elements?: T[], pos?: number): NodeArray<T> {
const array = <NodeArray<T>>(elements || []);
if (!(pos >= 0)) {
pos = getNodePos();
}
array.pos = pos;
array.end = pos;
return array;
}
function finishNode<T extends Node>(node: T, end?: number): T {
node.end = end === undefined ? scanner.getStartPos() : end;
@@ -1440,8 +1457,7 @@ namespace ts {
function parseList<T extends Node>(kind: ParsingContext, parseElement: () => T): NodeArray<T> {
const saveParsingContext = parsingContext;
parsingContext |= 1 << kind;
const result = <NodeArray<T>>[];
result.pos = getNodePos();
const result = createNodeArray<T>();
while (!isListTerminator(kind)) {
if (isListElement(kind, /*inErrorRecovery*/ false)) {
@@ -1788,8 +1804,7 @@ namespace ts {
function parseDelimitedList<T extends Node>(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray<T> {
const saveParsingContext = parsingContext;
parsingContext |= 1 << kind;
const result = <NodeArray<T>>[];
result.pos = getNodePos();
const result = createNodeArray<T>();
let commaStart = -1; // Meaning the previous token was not a comma
while (true) {
@@ -1844,12 +1859,8 @@ namespace ts {
return result;
}
function createMissingList<T>(): NodeArray<T> {
const pos = getNodePos();
const result = <NodeArray<T>>[];
result.pos = pos;
result.end = pos;
return result;
function createMissingList<T extends Node>(): NodeArray<T> {
return createNodeArray<T>();
}
function parseBracketedList<T extends Node>(kind: ParsingContext, parseElement: () => T, open: SyntaxKind, close: SyntaxKind): NodeArray<T> {
@@ -1914,8 +1925,7 @@ namespace ts {
template.head = parseTemplateLiteralFragment();
Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
const templateSpans = <NodeArray<TemplateSpan>>[];
templateSpans.pos = getNodePos();
const templateSpans = createNodeArray<TemplateSpan>();
do {
templateSpans.push(parseTemplateSpan());
@@ -2064,13 +2074,6 @@ namespace ts {
return token() === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token()) || token() === SyntaxKind.AtToken || token() === SyntaxKind.ThisKeyword;
}
function setModifiers(node: Node, modifiers: ModifiersArray) {
if (modifiers) {
node.flags |= modifiers.flags;
node.modifiers = modifiers;
}
}
function parseParameter(): ParameterDeclaration {
const node = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
if (token() === SyntaxKind.ThisKeyword) {
@@ -2080,13 +2083,13 @@ namespace ts {
}
node.decorators = parseDecorators();
setModifiers(node, parseModifiers());
node.modifiers = parseModifiers();
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
node.name = parseIdentifierOrPattern();
if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifierKind(token())) {
if (getFullWidth(node.name) === 0 && !hasModifiers(node) && isModifierKind(token())) {
// in cases like
// 'use strict'
// function foo(static)
@@ -2267,23 +2270,23 @@ namespace ts {
return token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || token() === SyntaxKind.CloseBracketToken;
}
function parseIndexSignatureDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): IndexSignatureDeclaration {
function parseIndexSignatureDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): IndexSignatureDeclaration {
const node = <IndexSignatureDeclaration>createNode(SyntaxKind.IndexSignature, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);
node.type = parseTypeAnnotation();
parseTypeMemberSemicolon();
return finishNode(node);
}
function parsePropertyOrMethodSignature(fullStart: number, modifiers: ModifiersArray): PropertySignature | MethodSignature {
function parsePropertyOrMethodSignature(fullStart: number, modifiers: NodeArray<Modifier>): PropertySignature | MethodSignature {
const name = parsePropertyName();
const questionToken = parseOptionalToken(SyntaxKind.QuestionToken);
if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) {
const method = <MethodSignature>createNode(SyntaxKind.MethodSignature, fullStart);
setModifiers(method, modifiers);
method.modifiers = modifiers;
method.name = name;
method.questionToken = questionToken;
@@ -2295,7 +2298,7 @@ namespace ts {
}
else {
const property = <PropertySignature>createNode(SyntaxKind.PropertySignature, fullStart);
setModifiers(property, modifiers);
property.modifiers = modifiers;
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
@@ -2339,6 +2342,7 @@ namespace ts {
token() === SyntaxKind.LessThanToken ||
token() === SyntaxKind.QuestionToken ||
token() === SyntaxKind.ColonToken ||
token() === SyntaxKind.CommaToken ||
canParseSemicolon();
}
return false;
@@ -2518,8 +2522,7 @@ namespace ts {
function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode {
let type = parseConstituentType();
if (token() === operator) {
const types = <NodeArray<TypeNode>>[type];
types.pos = type.pos;
const types = createNodeArray<TypeNode>([type], type.pos);
while (parseOptional(operator)) {
types.push(parseConstituentType());
}
@@ -2873,13 +2876,13 @@ namespace ts {
}
}
function parseSimpleArrowFunctionExpression(identifier: Identifier, asyncModifier?: ModifiersArray): ArrowFunction {
function parseSimpleArrowFunctionExpression(identifier: Identifier, asyncModifier?: NodeArray<Modifier>): ArrowFunction {
Debug.assert(token() === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
let node: ArrowFunction;
if (asyncModifier) {
node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction, asyncModifier.pos);
setModifiers(node, asyncModifier);
node.modifiers = asyncModifier;
}
else {
node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction, identifier.pos);
@@ -2889,8 +2892,7 @@ namespace ts {
parameter.name = identifier;
finishNode(parameter);
node.parameters = <NodeArray<ParameterDeclaration>>[parameter];
node.parameters.pos = parameter.pos;
node.parameters = createNodeArray<ParameterDeclaration>([parameter], parameter.pos);
node.parameters.end = parameter.end;
node.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, "=>");
@@ -2919,7 +2921,7 @@ namespace ts {
return undefined;
}
const isAsync = !!(arrowFunction.flags & NodeFlags.Async);
const isAsync = !!(getModifierFlags(arrowFunction) & ModifierFlags.Async);
// If we have an arrow, then try to parse the body. Even if not, try to parse if we
// have an opening brace, just in case we're in an error state.
@@ -3098,8 +3100,8 @@ namespace ts {
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction {
const node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction);
setModifiers(node, parseModifiersForArrowFunction());
const isAsync = !!(node.flags & NodeFlags.Async);
node.modifiers = parseModifiersForArrowFunction();
const isAsync = !!(getModifierFlags(node) & ModifierFlags.Async);
// Arrow functions are never generators.
//
@@ -3728,8 +3730,7 @@ namespace ts {
}
function parseJsxChildren(openingTagName: LeftHandSideExpression): NodeArray<JsxChild> {
const result = <NodeArray<JsxChild>>[];
result.pos = scanner.getStartPos();
const result = createNodeArray<JsxChild>();
const saveParsingContext = parsingContext;
parsingContext |= 1 << ParsingContext.JsxChildren;
@@ -3834,8 +3835,8 @@ namespace ts {
scanJsxIdentifier();
const node = <JsxAttribute>createNode(SyntaxKind.JsxAttribute);
node.name = parseIdentifierName();
if (parseOptional(SyntaxKind.EqualsToken)) {
switch (token()) {
if (token() === SyntaxKind.EqualsToken) {
switch (scanJsxAttributeValue()) {
case SyntaxKind.StringLiteral:
node.initializer = parseLiteralNode();
break;
@@ -4111,7 +4112,7 @@ namespace ts {
return finishNode(node);
}
function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): AccessorDeclaration {
function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): AccessorDeclaration {
if (parseContextualModifier(SyntaxKind.GetKeyword)) {
return addJSDocComment(parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, decorators, modifiers));
}
@@ -4196,12 +4197,12 @@ namespace ts {
}
const node = <FunctionExpression>createNode(SyntaxKind.FunctionExpression);
setModifiers(node, parseModifiers());
node.modifiers = parseModifiers();
parseExpected(SyntaxKind.FunctionKeyword);
node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
const isGenerator = !!node.asteriskToken;
const isAsync = !!(node.flags & NodeFlags.Async);
const isAsync = !!(getModifierFlags(node) & ModifierFlags.Async);
node.name =
isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
isGenerator ? doInYieldContext(parseOptionalIdentifier) :
@@ -4238,6 +4239,10 @@ namespace ts {
function parseBlock(ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block {
const node = <Block>createNode(SyntaxKind.Block);
if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) {
if (scanner.hasPrecedingLineBreak()) {
node.multiLine = true;
}
node.statements = parseList(ParsingContext.BlockStatements, parseStatement);
parseExpected(SyntaxKind.CloseBraceToken);
}
@@ -4788,7 +4793,7 @@ namespace ts {
const node = <Statement>createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
node.pos = fullStart;
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
return finishNode(node);
}
}
@@ -4810,9 +4815,9 @@ namespace ts {
// DECLARATIONS
function parseArrayBindingElement(): BindingElement {
function parseArrayBindingElement(): ArrayBindingElement {
if (token() === SyntaxKind.CommaToken) {
return <BindingElement>createNode(SyntaxKind.OmittedExpression);
return <OmittedExpression>createNode(SyntaxKind.OmittedExpression);
}
const node = <BindingElement>createNode(SyntaxKind.BindingElement);
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
@@ -4837,16 +4842,16 @@ namespace ts {
return finishNode(node);
}
function parseObjectBindingPattern(): BindingPattern {
const node = <BindingPattern>createNode(SyntaxKind.ObjectBindingPattern);
function parseObjectBindingPattern(): ObjectBindingPattern {
const node = <ObjectBindingPattern>createNode(SyntaxKind.ObjectBindingPattern);
parseExpected(SyntaxKind.OpenBraceToken);
node.elements = parseDelimitedList(ParsingContext.ObjectBindingElements, parseObjectBindingElement);
parseExpected(SyntaxKind.CloseBraceToken);
return finishNode(node);
}
function parseArrayBindingPattern(): BindingPattern {
const node = <BindingPattern>createNode(SyntaxKind.ArrayBindingPattern);
function parseArrayBindingPattern(): ArrayBindingPattern {
const node = <ArrayBindingPattern>createNode(SyntaxKind.ArrayBindingPattern);
parseExpected(SyntaxKind.OpenBracketToken);
node.elements = parseDelimitedList(ParsingContext.ArrayBindingElements, parseArrayBindingElement);
parseExpected(SyntaxKind.CloseBracketToken);
@@ -4923,57 +4928,57 @@ namespace ts {
return nextTokenIsIdentifier() && nextToken() === SyntaxKind.CloseParenToken;
}
function parseVariableStatement(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): VariableStatement {
function parseVariableStatement(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): VariableStatement {
const node = <VariableStatement>createNode(SyntaxKind.VariableStatement, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
parseSemicolon();
return addJSDocComment(finishNode(node));
}
function parseFunctionDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): FunctionDeclaration {
function parseFunctionDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): FunctionDeclaration {
const node = <FunctionDeclaration>createNode(SyntaxKind.FunctionDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.FunctionKeyword);
node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier();
node.name = hasModifier(node, ModifierFlags.Default) ? parseOptionalIdentifier() : parseIdentifier();
const isGenerator = !!node.asteriskToken;
const isAsync = !!(node.flags & NodeFlags.Async);
const isAsync = hasModifier(node, ModifierFlags.Async);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, Diagnostics.or_expected);
return addJSDocComment(finishNode(node));
}
function parseConstructorDeclaration(pos: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ConstructorDeclaration {
function parseConstructorDeclaration(pos: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ConstructorDeclaration {
const node = <ConstructorDeclaration>createNode(SyntaxKind.Constructor, pos);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.ConstructorKeyword);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, Diagnostics.or_expected);
return addJSDocComment(finishNode(node));
}
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
function parseMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, asteriskToken: Node, name: PropertyName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration {
const method = <MethodDeclaration>createNode(SyntaxKind.MethodDeclaration, fullStart);
method.decorators = decorators;
setModifiers(method, modifiers);
method.modifiers = modifiers;
method.asteriskToken = asteriskToken;
method.name = name;
method.questionToken = questionToken;
const isGenerator = !!asteriskToken;
const isAsync = !!(method.flags & NodeFlags.Async);
const isAsync = hasModifier(method, ModifierFlags.Async);
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method);
method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage);
return addJSDocComment(finishNode(method));
}
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, name: PropertyName, questionToken: Node): ClassElement {
function parsePropertyDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, name: PropertyName, questionToken: Node): ClassElement {
const property = <PropertyDeclaration>createNode(SyntaxKind.PropertyDeclaration, fullStart);
property.decorators = decorators;
setModifiers(property, modifiers);
property.modifiers = modifiers;
property.name = name;
property.questionToken = questionToken;
property.type = parseTypeAnnotation();
@@ -4987,7 +4992,7 @@ namespace ts {
// AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield];
//
// The checker may still error in the static case to explicitly disallow the yield expression.
property.initializer = modifiers && modifiers.flags & NodeFlags.Static
property.initializer = hasModifier(property, ModifierFlags.Static)
? allowInAnd(parseNonParameterInitializer)
: doOutsideOfContext(NodeFlags.YieldContext | NodeFlags.DisallowInContext, parseNonParameterInitializer);
@@ -4995,7 +5000,7 @@ namespace ts {
return finishNode(property);
}
function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ClassElement {
function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ClassElement {
const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
const name = parsePropertyName();
@@ -5014,10 +5019,10 @@ namespace ts {
return parseInitializer(/*inParameter*/ false);
}
function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): AccessorDeclaration {
function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): AccessorDeclaration {
const node = <AccessorDeclaration>createNode(kind, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.name = parsePropertyName();
fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node);
node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false);
@@ -5113,14 +5118,15 @@ namespace ts {
break;
}
if (!decorators) {
decorators = <NodeArray<Decorator>>[];
decorators.pos = decoratorStart;
}
const decorator = <Decorator>createNode(SyntaxKind.Decorator, decoratorStart);
decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
decorators.push(finishNode(decorator));
finishNode(decorator);
if (!decorators) {
decorators = createNodeArray<Decorator>([decorator], decoratorStart);
}
else {
decorators.push(decorator);
}
}
if (decorators) {
decorators.end = getNodeEnd();
@@ -5135,9 +5141,8 @@ namespace ts {
*
* In such situations, 'permitInvalidConstAsModifier' should be set to true.
*/
function parseModifiers(permitInvalidConstAsModifier?: boolean): ModifiersArray {
let flags: NodeFlags = 0;
let modifiers: ModifiersArray;
function parseModifiers(permitInvalidConstAsModifier?: boolean): NodeArray<Modifier> {
let modifiers: NodeArray<Modifier>;
while (true) {
const modifierStart = scanner.getStartPos();
const modifierKind = token();
@@ -5155,33 +5160,28 @@ namespace ts {
}
}
const modifier = finishNode(<Modifier>createNode(modifierKind, modifierStart));
if (!modifiers) {
modifiers = <ModifiersArray>[];
modifiers.pos = modifierStart;
modifiers = createNodeArray<Modifier>([modifier], modifierStart);
}
else {
modifiers.push(modifier);
}
flags |= modifierToFlag(modifierKind);
modifiers.push(finishNode(<Modifier>createNode(modifierKind, modifierStart)));
}
if (modifiers) {
modifiers.flags = flags;
modifiers.end = scanner.getStartPos();
}
return modifiers;
}
function parseModifiersForArrowFunction(): ModifiersArray {
let flags = 0;
let modifiers: ModifiersArray;
function parseModifiersForArrowFunction(): NodeArray<Modifier> {
let modifiers: NodeArray<Modifier>;
if (token() === SyntaxKind.AsyncKeyword) {
const modifierStart = scanner.getStartPos();
const modifierKind = token();
nextToken();
modifiers = <ModifiersArray>[];
modifiers.pos = modifierStart;
flags |= modifierToFlag(modifierKind);
modifiers.push(finishNode(<Modifier>createNode(modifierKind, modifierStart)));
modifiers.flags = flags;
const modifier = finishNode(<Modifier>createNode(modifierKind, modifierStart));
modifiers = createNodeArray<Modifier>([modifier], modifierStart);
modifiers.end = scanner.getStartPos();
}
@@ -5241,14 +5241,14 @@ namespace ts {
SyntaxKind.ClassExpression);
}
function parseClassDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ClassDeclaration {
function parseClassDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ClassDeclaration {
return <ClassDeclaration>parseClassDeclarationOrExpression(fullStart, decorators, modifiers, SyntaxKind.ClassDeclaration);
}
function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration {
function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, kind: SyntaxKind): ClassLikeDeclaration {
const node = <ClassLikeDeclaration>createNode(kind, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.ClassKeyword);
node.name = parseNameOfClassDeclarationOrExpression();
node.typeParameters = parseTypeParameters();
@@ -5323,10 +5323,10 @@ namespace ts {
return parseList(ParsingContext.ClassMembers, parseClassElement);
}
function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): InterfaceDeclaration {
function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): InterfaceDeclaration {
const node = <InterfaceDeclaration>createNode(SyntaxKind.InterfaceDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.InterfaceKeyword);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
@@ -5335,10 +5335,10 @@ namespace ts {
return finishNode(node);
}
function parseTypeAliasDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): TypeAliasDeclaration {
function parseTypeAliasDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): TypeAliasDeclaration {
const node = <TypeAliasDeclaration>createNode(SyntaxKind.TypeAliasDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.TypeKeyword);
node.name = parseIdentifier();
node.typeParameters = parseTypeParameters();
@@ -5359,10 +5359,10 @@ namespace ts {
return finishNode(node);
}
function parseEnumDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): EnumDeclaration {
function parseEnumDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): EnumDeclaration {
const node = <EnumDeclaration>createNode(SyntaxKind.EnumDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
parseExpected(SyntaxKind.EnumKeyword);
node.name = parseIdentifier();
if (parseExpected(SyntaxKind.OpenBraceToken)) {
@@ -5387,25 +5387,25 @@ namespace ts {
return finishNode(node);
}
function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, flags: NodeFlags): ModuleDeclaration {
function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>, flags: NodeFlags): ModuleDeclaration {
const node = <ModuleDeclaration>createNode(SyntaxKind.ModuleDeclaration, fullStart);
// If we are parsing a dotted namespace name, we want to
// propagate the 'Namespace' flag across the names if set.
const namespaceFlag = flags & NodeFlags.Namespace;
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
node.flags |= flags;
node.name = parseIdentifier();
node.body = parseOptional(SyntaxKind.DotToken)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.Export | namespaceFlag)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag)
: parseModuleBlock();
return finishNode(node);
}
function parseAmbientExternalModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ModuleDeclaration {
function parseAmbientExternalModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ModuleDeclaration {
const node = <ModuleDeclaration>createNode(SyntaxKind.ModuleDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
if (token() === SyntaxKind.GlobalKeyword) {
// parse 'global' as name of global scope augmentation
node.name = parseIdentifier();
@@ -5425,8 +5425,8 @@ namespace ts {
return finishNode(node);
}
function parseModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ModuleDeclaration {
let flags = modifiers ? modifiers.flags : 0;
function parseModuleDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ModuleDeclaration {
let flags: NodeFlags = 0;
if (token() === SyntaxKind.GlobalKeyword) {
// global augmentation
return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers);
@@ -5456,7 +5456,7 @@ namespace ts {
return nextToken() === SyntaxKind.SlashToken;
}
function parseNamespaceExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): NamespaceExportDeclaration {
function parseNamespaceExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): NamespaceExportDeclaration {
const exportDeclaration = <NamespaceExportDeclaration>createNode(SyntaxKind.NamespaceExportDeclaration, fullStart);
exportDeclaration.decorators = decorators;
exportDeclaration.modifiers = modifiers;
@@ -5470,7 +5470,7 @@ namespace ts {
return finishNode(exportDeclaration);
}
function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ImportEqualsDeclaration | ImportDeclaration {
function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ImportEqualsDeclaration | ImportDeclaration {
parseExpected(SyntaxKind.ImportKeyword);
const afterImportPos = scanner.getStartPos();
@@ -5483,7 +5483,7 @@ namespace ts {
// import x = M.x;
const importEqualsDeclaration = <ImportEqualsDeclaration>createNode(SyntaxKind.ImportEqualsDeclaration, fullStart);
importEqualsDeclaration.decorators = decorators;
setModifiers(importEqualsDeclaration, modifiers);
importEqualsDeclaration.modifiers = modifiers;
importEqualsDeclaration.name = identifier;
parseExpected(SyntaxKind.EqualsToken);
importEqualsDeclaration.moduleReference = parseModuleReference();
@@ -5495,7 +5495,7 @@ namespace ts {
// Import statement
const importDeclaration = <ImportDeclaration>createNode(SyntaxKind.ImportDeclaration, fullStart);
importDeclaration.decorators = decorators;
setModifiers(importDeclaration, modifiers);
importDeclaration.modifiers = modifiers;
// ImportDeclaration:
// import ImportClause from ModuleSpecifier ;
@@ -5631,10 +5631,10 @@ namespace ts {
return finishNode(node);
}
function parseExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ExportDeclaration {
function parseExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ExportDeclaration {
const node = <ExportDeclaration>createNode(SyntaxKind.ExportDeclaration, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
if (parseOptional(SyntaxKind.AsteriskToken)) {
parseExpected(SyntaxKind.FromKeyword);
node.moduleSpecifier = parseModuleSpecifier();
@@ -5654,10 +5654,10 @@ namespace ts {
return finishNode(node);
}
function parseExportAssignment(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ExportAssignment {
function parseExportAssignment(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): ExportAssignment {
const node = <ExportAssignment>createNode(SyntaxKind.ExportAssignment, fullStart);
node.decorators = decorators;
setModifiers(node, modifiers);
node.modifiers = modifiers;
if (parseOptional(SyntaxKind.EqualsToken)) {
node.isExportEquals = true;
}
@@ -5743,7 +5743,7 @@ namespace ts {
function setExternalModuleIndicator(sourceFile: SourceFile) {
sourceFile.externalModuleIndicator = forEach(sourceFile.statements, node =>
node.flags & NodeFlags.Export
hasModifier(node, ModifierFlags.Export)
|| node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference
|| node.kind === SyntaxKind.ImportDeclaration
|| node.kind === SyntaxKind.ExportAssignment
@@ -6083,10 +6083,8 @@ namespace ts {
function parseJSDocTypeList(firstType: JSDocType) {
Debug.assert(!!firstType);
const types = <NodeArray<JSDocType>>[];
types.pos = firstType.pos;
const types = createNodeArray([firstType], firstType.pos);
types.push(firstType);
while (parseOptional(SyntaxKind.BarToken)) {
types.push(parseJSDocType());
}
@@ -6301,11 +6299,11 @@ namespace ts {
function addTag(tag: JSDocTag): void {
if (tag) {
if (!tags) {
tags = <NodeArray<JSDocTag>>[];
tags.pos = tag.pos;
tags = createNodeArray([tag], tag.pos);
}
else {
tags.push(tag);
}
tags.push(tag);
tags.end = tag.end;
}
}
@@ -6517,8 +6515,7 @@ namespace ts {
}
// Type parameter list looks like '@template T,U,V'
const typeParameters = <NodeArray<TypeParameterDeclaration>>[];
typeParameters.pos = scanner.getStartPos();
const typeParameters = createNodeArray<TypeParameterDeclaration>();
while (true) {
const name = parseJSDocIdentifierName();
+49 -13
View File
@@ -8,11 +8,9 @@ namespace ts {
const emptyArray: any[] = [];
const defaultTypeRoots = ["node_modules/@types"];
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string {
while (true) {
const fileName = combinePaths(searchPath, "tsconfig.json");
const fileName = combinePaths(searchPath, configName);
if (fileExists(fileName)) {
return fileName;
}
@@ -168,7 +166,7 @@ namespace ts {
const typeReferenceExtensions = [".d.ts"];
function getEffectiveTypeRoots(options: CompilerOptions, host: ModuleResolutionHost) {
export function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean, getCurrentDirectory?: () => string }): string[] | undefined {
if (options.typeRoots) {
return options.typeRoots;
}
@@ -181,12 +179,38 @@ namespace ts {
currentDirectory = host.getCurrentDirectory();
}
if (!currentDirectory) {
return undefined;
}
return map(defaultTypeRoots, d => combinePaths(currentDirectory, d));
return currentDirectory && getDefaultTypeRoots(currentDirectory, host);
}
/**
* Returns the path to every node_modules/@types directory from some ancestor directory.
* Returns undefined if there are none.
*/
function getDefaultTypeRoots(currentDirectory: string, host: { directoryExists?: (directoryName: string) => boolean }): string[] | undefined {
if (!host.directoryExists) {
return [combinePaths(currentDirectory, nodeModulesAtTypes)];
// And if it doesn't exist, tough.
}
let typeRoots: string[];
while (true) {
const atTypes = combinePaths(currentDirectory, nodeModulesAtTypes);
if (host.directoryExists(atTypes)) {
(typeRoots || (typeRoots = [])).push(atTypes);
}
const parent = getDirectoryPath(currentDirectory);
if (parent === currentDirectory) {
break;
}
currentDirectory = parent;
}
return typeRoots;
}
const nodeModulesAtTypes = combinePaths("node_modules", "@types");
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
@@ -963,6 +987,7 @@ namespace ts {
readFile: fileName => sys.readFile(fileName),
trace: (s: string) => sys.write(s + newLine),
directoryExists: directoryName => sys.directoryExists(directoryName),
getEnvironmentVariable: name => getEnvironmentVariable(name, /*host*/ undefined),
getDirectories: (path: string) => sys.getDirectories(path),
realpath
};
@@ -1101,7 +1126,7 @@ namespace ts {
// - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
// As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
// The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 2;
const maxNodeModulesJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
let currentNodeModulesDepth = 0;
// If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
@@ -1706,7 +1731,7 @@ namespace ts {
return false;
}
function checkModifiers(modifiers: ModifiersArray): boolean {
function checkModifiers(modifiers: NodeArray<Modifier>): boolean {
if (modifiers) {
for (const modifier of modifiers) {
switch (modifier.kind) {
@@ -1790,6 +1815,17 @@ namespace ts {
let imports: LiteralExpression[];
let moduleAugmentations: LiteralExpression[];
// If we are importing helpers, we need to add a synthetic reference to resolve the
// helpers library.
if (options.importHelpers
&& (options.isolatedModules || isExternalModuleFile)
&& !file.isDeclarationFile) {
const externalHelpersModuleReference = <StringLiteral>createNode(SyntaxKind.StringLiteral);
externalHelpersModuleReference.text = externalHelpersModuleNameText;
externalHelpersModuleReference.parent = file;
imports = [externalHelpersModuleReference];
}
for (const node of file.statements) {
collectModuleReferences(node, /*inAmbientModule*/ false);
if (isJavaScriptFile) {
@@ -1823,7 +1859,7 @@ namespace ts {
}
break;
case SyntaxKind.ModuleDeclaration:
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || isDeclarationFile(file))) {
const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name;
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
// This will happen in two cases:
@@ -2306,7 +2342,7 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) {
if (options.reactNamespace && !isIdentifierText(options.reactNamespace, languageVersion)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
}
+102 -32
View File
@@ -27,6 +27,7 @@ namespace ts {
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scanJsxIdentifier(): SyntaxKind;
scanJsxAttributeValue(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scanJSDocToken(): SyntaxKind;
@@ -439,9 +440,7 @@ namespace ts {
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments = false): number {
// Using ! with a greater than test is a fast way of testing the following conditions:
// pos === undefined || pos === null || isNaN(pos) || pos < 0;
if (!(pos >= 0)) {
if (positionIsSynthesized(pos)) {
return pos;
}
@@ -590,20 +589,34 @@ namespace ts {
}
/**
* Extract comments from text prefixing the token closest following `pos`.
* The return value is an array containing a TextRange for each comment.
* Single-line comment ranges include the beginning '//' characters but not the ending line break.
* Multi - line comment ranges include the beginning '/* and ending '<asterisk>/' characters.
* The return value is undefined if no comments were found.
* @param trailing
* If false, whitespace is skipped until the first line break and comments between that location
* and the next token are returned.
* If true, comments occurring between the given position and the next line break are returned.
* Invokes a callback for each comment range following the provided position.
*
* Single-line comment ranges include the leading double-slash characters but not the ending
* line break. Multi-line comment ranges include the leading slash-asterisk and trailing
* asterisk-slash characters.
*
* @param reduce If true, accumulates the result of calling the callback in a fashion similar
* to reduceLeft. If false, iteration stops when the callback returns a truthy value.
* @param text The source text to scan.
* @param pos The position at which to start scanning.
* @param trailing If false, whitespace is skipped until the first line break and comments
* between that location and the next token are returned. If true, comments occurring
* between the given position and the next line break are returned.
* @param cb The callback to execute as each comment range is encountered.
* @param state A state value to pass to each iteration of the callback.
* @param initial An initial value to pass when accumulating results (when "reduce" is true).
* @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
* return value of the callback.
*/
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
function iterateCommentRanges<T, U>(reduce: boolean, text: string, pos: number, trailing: boolean, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial?: U): U {
let pendingPos: number;
let pendingEnd: number;
let pendingKind: SyntaxKind;
let pendingHasTrailingNewLine: boolean;
let hasPendingCommentRange = false;
let collecting = trailing || pos === 0;
while (pos < text.length) {
let accumulator = initial;
scan: while (pos >= 0 && pos < text.length) {
const ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
@@ -613,12 +626,14 @@ namespace ts {
case CharacterCodes.lineFeed:
pos++;
if (trailing) {
return result;
break scan;
}
collecting = true;
if (result && result.length) {
lastOrUndefined(result).hasTrailingNewLine = true;
if (hasPendingCommentRange) {
pendingHasTrailingNewLine = true;
}
continue;
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
@@ -651,38 +666,78 @@ namespace ts {
pos++;
}
}
if (collecting) {
if (!result) {
result = [];
if (hasPendingCommentRange) {
accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
if (!reduce && accumulator) {
// If we are not reducing and we have a truthy result, return it.
return accumulator;
}
hasPendingCommentRange = false;
}
result.push({ pos: startPos, end: pos, hasTrailingNewLine, kind });
pendingPos = startPos;
pendingEnd = pos;
pendingKind = kind;
pendingHasTrailingNewLine = hasTrailingNewLine;
hasPendingCommentRange = true;
}
continue;
}
break;
break scan;
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch))) {
if (result && result.length && isLineBreak(ch)) {
lastOrUndefined(result).hasTrailingNewLine = true;
if (hasPendingCommentRange && isLineBreak(ch)) {
pendingHasTrailingNewLine = true;
}
pos++;
continue;
}
break;
break scan;
}
return result;
}
return result;
if (hasPendingCommentRange) {
accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
}
return accumulator;
}
export function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) {
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
}
export function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) {
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
}
export function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U) {
return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
}
export function reduceEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U) {
return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
}
function appendCommentRange(pos: number, end: number, kind: SyntaxKind, hasTrailingNewLine: boolean, state: any, comments: CommentRange[]) {
if (!comments) {
comments = [];
}
comments.push({ pos, end, hasTrailingNewLine, kind });
return comments;
}
export function getLeadingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ false);
return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined);
}
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ true);
return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined);
}
/** Optionally, get the shebang */
@@ -705,7 +760,7 @@ namespace ts {
}
/* @internal */
export function isIdentifier(name: string, languageVersion: ScriptTarget): boolean {
export function isIdentifierText(name: string, languageVersion: ScriptTarget): boolean {
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
return false;
}
@@ -763,6 +818,7 @@ namespace ts {
reScanSlashToken,
reScanTemplateToken,
scanJsxIdentifier,
scanJsxAttributeValue,
reScanJsxToken,
scanJsxToken,
scanJSDocToken,
@@ -857,7 +913,7 @@ namespace ts {
return value;
}
function scanString(): string {
function scanString(allowEscapes = true): string {
const quote = text.charCodeAt(pos);
pos++;
let result = "";
@@ -875,7 +931,7 @@ namespace ts {
pos++;
break;
}
if (ch === CharacterCodes.backslash) {
if (ch === CharacterCodes.backslash && allowEscapes) {
result += text.substring(start, pos);
result += scanEscapeSequence();
start = pos;
@@ -1683,6 +1739,20 @@ namespace ts {
return token;
}
function scanJsxAttributeValue(): SyntaxKind {
startPos = pos;
switch (text.charCodeAt(pos)) {
case CharacterCodes.doubleQuote:
case CharacterCodes.singleQuote:
tokenValue = scanString(/*allowEscapes*/ false);
return token = SyntaxKind.StringLiteral;
default:
// If this scans anything other than `{`, it's a parse error.
return scan();
}
}
function scanJSDocToken(): SyntaxKind {
if (pos >= end) {
return token = SyntaxKind.EndOfFileToken;
+497 -40
View File
@@ -3,19 +3,211 @@
/* @internal */
namespace ts {
export interface SourceMapWriter {
getSourceMapData(): SourceMapData;
setSourceFile(sourceFile: SourceFile): void;
emitPos(pos: number): void;
emitStart(range: TextRange): void;
emitEnd(range: TextRange, stopOverridingSpan?: boolean): void;
changeEmitSourcePos(): void;
getText(): string;
getSourceMappingURL(): string;
/**
* Initialize the SourceMapWriter for a new output file.
*
* @param filePath The path to the generated output file.
* @param sourceMapFilePath The path to the output source map file.
* @param sourceFiles The input source files for the program.
* @param isBundledEmit A value indicating whether the generated output file is a bundle.
*/
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void;
/**
* Reset the SourceMapWriter to an empty state.
*/
reset(): void;
/**
* Gets test data for source maps.
*/
getSourceMapData(): SourceMapData;
/**
* Set the current source file.
*
* @param sourceFile The source file.
*/
setSourceFile(sourceFile: SourceFile): void;
/**
* Emits a mapping.
*
* If the position is synthetic (undefined or a negative value), no mapping will be
* created.
*
* @param pos The position.
*/
emitPos(pos: number): void;
/**
* Emits a mapping for the start of a range.
*
* If the range's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.
*/
emitStart(range: TextRange): void;
/**
* Emits a mapping for the start of a range.
*
* If the node's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the start position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void;
/**
* Emits a mapping for the end of a range.
*
* If the range's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
*/
emitEnd(range: TextRange): void;
/**
* Emits a mapping for the end of a range.
*
* If the node's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the end position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void;
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @returns The start position of the token, following any trivia.
*/
emitTokenStart(token: SyntaxKind, tokenStartPos: number): number;
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the start position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The start position of the token, following any trivia.
*/
emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @returns The end position of the token.
*/
emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number;
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the end position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The end position of the token.
*/
emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
/*@deprecated*/ changeEmitSourcePos(): void;
/*@deprecated*/ stopOverridingSpan(): void;
/**
* Gets the text for the source map.
*/
getText(): string;
/**
* Gets the SourceMappingURL for the source map.
*/
getSourceMappingURL(): string;
}
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
const compilerOptions = host.getCompilerOptions();
if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
if (compilerOptions.extendedDiagnostics) {
return createSourceMapWriterWithExtendedDiagnostics(host, writer);
}
return createSourceMapWriterWorker(host, writer);
}
else {
return getNullSourceMapWriter();
}
}
let nullSourceMapWriter: SourceMapWriter;
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
nullSourceMapWriter = {
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void { },
reset(): void { },
getSourceMapData(): SourceMapData { return undefined; },
setSourceFile(sourceFile: SourceFile): void { },
emitPos(pos: number): void { },
emitStart(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void { },
emitEnd(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void { },
emitTokenStart(token: SyntaxKind, pos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number { return -1; },
emitTokenEnd(token: SyntaxKind, end: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number { return -1; },
changeEmitSourcePos(): void { },
stopOverridingSpan(): void { },
getText(): string { return undefined; },
getSourceMappingURL(): string { return undefined; }
};
}
return nullSourceMapWriter;
}
// Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans
const defaultLastEncodedSourceMapSpan: SourceMapSpan = {
emittedLine: 1,
@@ -25,29 +217,11 @@ namespace ts {
sourceIndex: 0
};
export function getNullSourceMapWriter(): SourceMapWriter {
if (nullSourceMapWriter === undefined) {
nullSourceMapWriter = {
getSourceMapData(): SourceMapData { return undefined; },
setSourceFile(sourceFile: SourceFile): void { },
emitStart(range: TextRange): void { },
emitEnd(range: TextRange, stopOverridingSpan?: boolean): void { },
emitPos(pos: number): void { },
changeEmitSourcePos(): void { },
getText(): string { return undefined; },
getSourceMappingURL(): string { return undefined; },
initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void { },
reset(): void { },
};
}
return nullSourceMapWriter;
}
export function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
function createSourceMapWriterWorker(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
const compilerOptions = host.getCompilerOptions();
const extendedDiagnostics = compilerOptions.extendedDiagnostics;
let currentSourceFile: SourceFile;
let currentSourceText: string;
let sourceMapDir: string; // The directory in which sourcemap will be
let stopOverridingSpan = false;
let modifyLastSourcePos = false;
@@ -63,25 +237,45 @@ namespace ts {
// Source map data
let sourceMapData: SourceMapData;
// This keeps track of the number of times `disable` has been called without a
// corresponding call to `enable`. As long as this value is non-zero, mappings will not
// be recorded.
// This is primarily used to provide a better experience when debugging binding
// patterns and destructuring assignments for simple expressions.
let disableDepth: number;
return {
initialize,
reset,
getSourceMapData: () => sourceMapData,
setSourceFile,
emitPos,
emitStart,
emitEnd,
emitTokenStart,
emitTokenEnd,
changeEmitSourcePos,
stopOverridingSpan: () => stopOverridingSpan = true,
getText,
getSourceMappingURL,
initialize,
reset,
};
/**
* Initialize the SourceMapWriter for a new output file.
*
* @param filePath The path to the generated output file.
* @param sourceMapFilePath The path to the output source map file.
* @param sourceFiles The input source files for the program.
* @param isBundledEmit A value indicating whether the generated output file is a bundle.
*/
function initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
if (sourceMapData) {
reset();
}
currentSourceFile = undefined;
currentSourceText = undefined;
disableDepth = 0;
// Current source map file and its index in the sources list
sourceMapSourceIndex = -1;
@@ -140,6 +334,9 @@ namespace ts {
}
}
/**
* Reset the SourceMapWriter to an empty state.
*/
function reset() {
currentSourceFile = undefined;
sourceMapDir = undefined;
@@ -148,6 +345,23 @@ namespace ts {
lastEncodedSourceMapSpan = undefined;
lastEncodedNameIndex = undefined;
sourceMapData = undefined;
disableDepth = 0;
}
/**
* Re-enables the recording of mappings.
*/
function enable() {
if (disableDepth > 0) {
disableDepth--;
}
}
/**
* Disables the recording of mappings.
*/
function disable() {
disableDepth++;
}
function updateLastEncodedAndRecordedSpans() {
@@ -236,8 +450,16 @@ namespace ts {
sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);
}
/**
* Emits a mapping.
*
* If the position is synthetic (undefined or a negative value), no mapping will be
* created.
*
* @param pos The position.
*/
function emitPos(pos: number) {
if (pos === -1) {
if (positionIsSynthesized(pos) || disableDepth > 0) {
return;
}
@@ -291,27 +513,201 @@ namespace ts {
}
}
function getStartPos(range: TextRange) {
function getStartPosPastDecorators(range: TextRange) {
const rangeHasDecorators = !!(range as Node).decorators;
return range.pos !== -1 ? skipTrivia(currentSourceFile.text, rangeHasDecorators ? (range as Node).decorators.end : range.pos) : -1;
return skipTrivia(currentSourceText, rangeHasDecorators ? (range as Node).decorators.end : range.pos);
}
function emitStart(range: TextRange) {
emitPos(getStartPos(range));
/**
* Emits a mapping for the start of a range.
*
* If the range's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.0
*/
function emitStart(range: TextRange): void;
/**
* Emits a mapping for the start of a range.
*
* If the node's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the start position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
function emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallback: (node: Node) => TextRange): void;
function emitStart(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange) {
if (contextNode) {
if (!ignoreNodeCallback(contextNode)) {
range = getTextRangeCallback(contextNode) || range;
emitPos(getStartPosPastDecorators(range));
}
if (ignoreChildrenCallback(contextNode)) {
disable();
}
}
else {
emitPos(getStartPosPastDecorators(range));
}
}
function emitEnd(range: TextRange, stopOverridingEnd?: boolean) {
emitPos(range.end);
stopOverridingSpan = stopOverridingEnd;
/**
* Emits a mapping for the end of a range.
*
* If the range's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
*/
function emitEnd(range: TextRange): void;
/**
* Emits a mapping for the end of a range.
*
* If the node's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param range The range to emit.
* @param contextNode The node for the current range.
* @param ignoreNodeCallback A callback used to determine whether to skip source map
* emit for the end position of this node.
* @param ignoreChildrenCallback A callback used to determine whether to skip source
* map emit for all children of this node.
* @param getTextRangeCallbackCallback A callback used to get a custom source map
* range for this node.
*/
function emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallback: (node: Node) => TextRange): void;
function emitEnd(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange) {
if (contextNode) {
if (ignoreChildrenCallback(contextNode)) {
enable();
}
if (!ignoreNodeCallback(contextNode)) {
range = getTextRangeCallback(contextNode) || range;
emitPos(range.end);
}
}
else {
emitPos(range.end);
}
stopOverridingSpan = false;
}
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @returns The start position of the token, following any trivia.
*/
function emitTokenStart(token: SyntaxKind, tokenStartPos: number): number;
/**
* Emits a mapping for the start position of a token.
*
* If the token's start position is synthetic (undefined or a negative value), no mapping
* will be created. Any trivia at the start position in the original source will be
* skipped.
*
* @param token The token to emit.
* @param tokenStartPos The start position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the start position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The start position of the token, following any trivia.
*/
function emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
function emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
if (contextNode) {
if (ignoreTokenCallback(contextNode, token)) {
return skipTrivia(currentSourceText, tokenStartPos);
}
const range = getTokenTextRangeCallback(contextNode, token);
if (range) {
tokenStartPos = range.pos;
}
}
tokenStartPos = skipTrivia(currentSourceText, tokenStartPos);
emitPos(tokenStartPos);
return tokenStartPos;
}
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @returns The end position of the token.
*/
function emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number;
/**
* Emits a mapping for the end position of a token.
*
* If the token's end position is synthetic (undefined or a negative value), no mapping
* will be created.
*
* @param token The token to emit.
* @param tokenEndPos The end position of the token.
* @param contextNode The node containing this token.
* @param ignoreTokenCallback A callback used to determine whether to skip source map
* emit for the end position of this token.
* @param getTokenTextRangeCallback A callback used to get a custom source
* map range for this node.
* @returns The end position of the token.
*/
function emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number;
function emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
if (contextNode) {
if (ignoreTokenCallback(contextNode, token)) {
return tokenEndPos;
}
const range = getTokenTextRangeCallback(contextNode, token);
if (range) {
tokenEndPos = range.end;
}
}
emitPos(tokenEndPos);
return tokenEndPos;
}
// @deprecated
function changeEmitSourcePos() {
Debug.assert(!modifyLastSourcePos);
modifyLastSourcePos = true;
}
/**
* Set the current source file.
*
* @param sourceFile The source file.
*/
function setSourceFile(sourceFile: SourceFile) {
currentSourceFile = sourceFile;
currentSourceText = currentSourceFile.text;
// Add the file to tsFilePaths
// If sourceroot option: Use the relative path corresponding to the common directory path
@@ -330,14 +726,17 @@ namespace ts {
sourceMapData.sourceMapSources.push(source);
// The one that can be used from program to get the actual source file
sourceMapData.inputSourceFileNames.push(sourceFile.fileName);
sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName);
if (compilerOptions.inlineSources) {
sourceMapData.sourceMapSourcesContent.push(sourceFile.text);
sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text);
}
}
}
/**
* Gets the text for the source map.
*/
function getText() {
encodeLastRecordedSourceMapSpan();
@@ -352,6 +751,9 @@ namespace ts {
});
}
/**
* Gets the SourceMappingURL for the source map.
*/
function getSourceMappingURL() {
if (compilerOptions.inlineSourceMap) {
// Encode the sourceMap into the sourceMap url
@@ -364,6 +766,61 @@ namespace ts {
}
}
function createSourceMapWriterWithExtendedDiagnostics(host: EmitHost, writer: EmitTextWriter): SourceMapWriter {
const {
initialize,
reset,
getSourceMapData,
setSourceFile,
emitPos,
emitStart,
emitEnd,
emitTokenStart,
emitTokenEnd,
changeEmitSourcePos,
stopOverridingSpan,
getText,
getSourceMappingURL,
} = createSourceMapWriterWorker(host, writer);
return {
initialize,
reset,
getSourceMapData,
setSourceFile,
emitPos(pos: number): void {
performance.mark("sourcemapStart");
emitPos(pos);
performance.measure("sourceMapTime", "sourcemapStart");
},
emitStart(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void {
performance.mark("emitSourcemap:emitStart");
emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback);
performance.measure("sourceMapTime", "emitSourcemap:emitStart");
},
emitEnd(range: TextRange, contextNode?: Node, ignoreNodeCallback?: (node: Node) => boolean, ignoreChildrenCallback?: (node: Node) => boolean, getTextRangeCallback?: (node: Node) => TextRange): void {
performance.mark("emitSourcemap:emitEnd");
emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback);
performance.measure("sourceMapTime", "emitSourcemap:emitEnd");
},
emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
performance.mark("emitSourcemap:emitTokenStart");
tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback);
performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart");
return tokenStartPos;
},
emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode?: Node, ignoreTokenCallback?: (node: Node) => boolean, getTokenTextRangeCallback?: (node: Node, token: SyntaxKind) => TextRange): number {
performance.mark("emitSourcemap:emitTokenEnd");
tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback);
performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd");
return tokenEndPos;
},
changeEmitSourcePos,
stopOverridingSpan,
getText,
getSourceMappingURL,
};
}
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64FormatEncode(inValue: number) {
+21 -12
View File
@@ -32,6 +32,8 @@ namespace ts {
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
/*@internal*/ getEnvironmentVariable(name: string): string;
/*@internal*/ tryEnableSourceMapsForHost?(): void;
}
export interface FileWatcher {
@@ -78,6 +80,7 @@ namespace ts {
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
realpath(path: string): string;
getEnvironmentVariable?(name: string): string;
};
export var sys: System = (function() {
@@ -212,6 +215,9 @@ namespace ts {
return shell.CurrentDirectory;
},
getDirectories,
getEnvironmentVariable(name: string) {
return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings(`%${name}%`);
},
readDirectory,
exit(exitCode?: number): void {
try {
@@ -267,7 +273,7 @@ namespace ts {
}
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
(fileWatcherCallbacks[filePath] || (fileWatcherCallbacks[filePath] = [])).push(callback);
multiMapAdd(fileWatcherCallbacks, filePath, callback);
}
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
@@ -283,16 +289,7 @@ namespace ts {
}
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
const callbacks = fileWatcherCallbacks[filePath];
if (callbacks) {
const newCallbacks = copyListRemovingItem(callback, callbacks);
if (newCallbacks.length === 0) {
delete fileWatcherCallbacks[filePath];
}
else {
fileWatcherCallbacks[filePath] = newCallbacks;
}
}
multiMapRemove(fileWatcherCallbacks, filePath, callback);
}
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: string) {
@@ -432,7 +429,7 @@ namespace ts {
}
function getDirectories(path: string): string[] {
return filter<string>(_fs.readdirSync(path), p => fileSystemEntryExists(combinePaths(path, p), FileSystemEntryKind.Directory));
return filter<string>(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory));
}
const nodeSystem: System = {
@@ -508,6 +505,9 @@ namespace ts {
return process.cwd();
},
getDirectories,
getEnvironmentVariable(name: string) {
return process.env[name] || "";
},
readDirectory,
getModifiedTime(path) {
try {
@@ -543,6 +543,14 @@ namespace ts {
},
realpath(path: string): string {
return _fs.realpathSync(path);
},
tryEnableSourceMapsForHost() {
try {
require("source-map-support").install();
}
catch (e) {
// Could not enable source maps.
}
}
};
return nodeSystem;
@@ -574,6 +582,7 @@ namespace ts {
getExecutingFilePath: () => ChakraHost.executingFile,
getCurrentDirectory: () => ChakraHost.currentDirectory,
getDirectories: ChakraHost.getDirectories,
getEnvironmentVariable: ChakraHost.getEnvironmentVariable || ((name: string) => ""),
readDirectory: (path: string, extensions?: string[], excludes?: string[], includes?: string[]) => {
const pattern = getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory);
return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern);
+632
View File
@@ -0,0 +1,632 @@
/// <reference path="visitor.ts" />
/// <reference path="transformers/ts.ts" />
/// <reference path="transformers/jsx.ts" />
/// <reference path="transformers/es7.ts" />
/// <reference path="transformers/es6.ts" />
/// <reference path="transformers/generators.ts" />
/// <reference path="transformers/module/module.ts" />
/// <reference path="transformers/module/system.ts" />
/// <reference path="transformers/module/es6.ts" />
/* @internal */
namespace ts {
const moduleTransformerMap = createMap<Transformer>({
[ModuleKind.ES6]: transformES6Module,
[ModuleKind.System]: transformSystemModule,
[ModuleKind.AMD]: transformModule,
[ModuleKind.CommonJS]: transformModule,
[ModuleKind.UMD]: transformModule,
[ModuleKind.None]: transformModule,
});
const enum SyntaxKindFeatureFlags {
Substitution = 1 << 0,
EmitNotifications = 1 << 1,
}
export interface TransformationResult {
/**
* Gets the transformed source files.
*/
getSourceFiles(): SourceFile[];
/**
* Gets the TextRange to use for source maps for a token of a node.
*/
getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange;
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
isSubstitutionEnabled(node: Node): boolean;
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
isEmitNotificationEnabled(node: Node): boolean;
/**
* Hook used by transformers to substitute expressions just before they
* are emitted by the pretty printer.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is in an expression context.
*/
onSubstituteNode(node: Node, isExpression: boolean): Node;
/**
* Hook used to allow transformers to capture state before or after
* the printer emits a node.
*
* @param node The node to emit.
* @param emitCallback A callback used to emit the node.
*/
onEmitNode(node: Node, emitCallback: (node: Node) => void): void;
/**
* Reset transient transformation properties on parse tree nodes.
*/
dispose(): void;
}
export interface TransformationContext extends LexicalEnvironment {
getCompilerOptions(): CompilerOptions;
getEmitResolver(): EmitResolver;
getEmitHost(): EmitHost;
/**
* Gets flags used to customize later transformations or emit.
*/
getNodeEmitFlags(node: Node): NodeEmitFlags;
/**
* Sets flags used to customize later transformations or emit.
*/
setNodeEmitFlags<T extends Node>(node: T, flags: NodeEmitFlags): T;
/**
* Gets the TextRange to use for source maps for the node.
*/
getSourceMapRange(node: Node): TextRange;
/**
* Sets the TextRange to use for source maps for the node.
*/
setSourceMapRange<T extends Node>(node: T, range: TextRange): T;
/**
* Gets the TextRange to use for source maps for a token of a node.
*/
getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange;
/**
* Sets the TextRange to use for source maps for a token of a node.
*/
setTokenSourceMapRange<T extends Node>(node: T, token: SyntaxKind, range: TextRange): T;
/**
* Gets the TextRange to use for comments for the node.
*/
getCommentRange(node: Node): TextRange;
/**
* Sets the TextRange to use for comments for the node.
*/
setCommentRange<T extends Node>(node: T, range: TextRange): T;
/**
* Hoists a function declaration to the containing scope.
*/
hoistFunctionDeclaration(node: FunctionDeclaration): void;
/**
* Hoists a variable declaration to the containing scope.
*/
hoistVariableDeclaration(node: Identifier): void;
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
enableSubstitution(kind: SyntaxKind): void;
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
isSubstitutionEnabled(node: Node): boolean;
/**
* Hook used by transformers to substitute expressions just before they
* are emitted by the pretty printer.
*/
onSubstituteNode?: (node: Node, isExpression: boolean) => Node;
/**
* Enables before/after emit notifications in the pretty printer for the provided
* SyntaxKind.
*/
enableEmitNotification(kind: SyntaxKind): void;
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
isEmitNotificationEnabled(node: Node): boolean;
/**
* Hook used to allow transformers to capture state before or after
* the printer emits a node.
*/
onEmitNode?: (node: Node, emit: (node: Node) => void) => void;
}
/* @internal */
export type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile;
export function getTransformers(compilerOptions: CompilerOptions) {
const jsx = compilerOptions.jsx;
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
const transformers: Transformer[] = [];
transformers.push(transformTypeScript);
transformers.push(moduleTransformerMap[moduleKind] || moduleTransformerMap[ModuleKind.None]);
if (jsx === JsxEmit.React) {
transformers.push(transformJsx);
}
transformers.push(transformES7);
if (languageVersion < ScriptTarget.ES6) {
transformers.push(transformES6);
transformers.push(transformGenerators);
}
return transformers;
}
/**
* Tracks a monotonically increasing transformation id used to associate a node with a specific
* transformation. This ensures transient properties related to transformations can be safely
* stored on source tree nodes that may be reused across multiple transformations (such as
* with compile-on-save).
*/
let nextTransformId = 1;
/**
* Transforms an array of SourceFiles by passing them through each transformer.
*
* @param resolver The emit resolver provided by the checker.
* @param host The emit host.
* @param sourceFiles An array of source files
* @param transforms An array of Transformers.
*/
export function transformFiles(resolver: EmitResolver, host: EmitHost, sourceFiles: SourceFile[], transformers: Transformer[]): TransformationResult {
const transformId = nextTransformId;
nextTransformId++;
const tokenSourceMapRanges = createMap<TextRange>();
const lexicalEnvironmentVariableDeclarationsStack: VariableDeclaration[][] = [];
const lexicalEnvironmentFunctionDeclarationsStack: FunctionDeclaration[][] = [];
const enabledSyntaxKindFeatures = new Array<SyntaxKindFeatureFlags>(SyntaxKind.Count);
const parseTreeNodesWithAnnotations: Node[] = [];
let lastTokenSourceMapRangeNode: Node;
let lastTokenSourceMapRangeToken: SyntaxKind;
let lastTokenSourceMapRange: TextRange;
let lexicalEnvironmentStackOffset = 0;
let hoistedVariableDeclarations: VariableDeclaration[];
let hoistedFunctionDeclarations: FunctionDeclaration[];
let lexicalEnvironmentDisabled: boolean;
// The transformation context is provided to each transformer as part of transformer
// initialization.
const context: TransformationContext = {
getCompilerOptions: () => host.getCompilerOptions(),
getEmitResolver: () => resolver,
getEmitHost: () => host,
getNodeEmitFlags,
setNodeEmitFlags,
getSourceMapRange,
setSourceMapRange,
getTokenSourceMapRange,
setTokenSourceMapRange,
getCommentRange,
setCommentRange,
hoistVariableDeclaration,
hoistFunctionDeclaration,
startLexicalEnvironment,
endLexicalEnvironment,
onSubstituteNode,
enableSubstitution,
isSubstitutionEnabled,
onEmitNode,
enableEmitNotification,
isEmitNotificationEnabled
};
// Chain together and initialize each transformer.
const transformation = chain(...transformers)(context);
// Transform each source file.
const transformed = map(sourceFiles, transformSourceFile);
// Disable modification of the lexical environment.
lexicalEnvironmentDisabled = true;
return {
getSourceFiles: () => transformed,
getTokenSourceMapRange,
isSubstitutionEnabled,
isEmitNotificationEnabled,
onSubstituteNode: context.onSubstituteNode,
onEmitNode: context.onEmitNode,
dispose() {
// During transformation we may need to annotate a parse tree node with transient
// transformation properties. As parse tree nodes live longer than transformation
// nodes, we need to make sure we reclaim any memory allocated for custom ranges
// from these nodes to ensure we do not hold onto entire subtrees just for position
// information. We also need to reset these nodes to a pre-transformation state
// for incremental parsing scenarios so that we do not impact later emit.
for (const node of parseTreeNodesWithAnnotations) {
if (node.transformId === transformId) {
node.transformId = 0;
node.emitFlags = 0;
node.commentRange = undefined;
node.sourceMapRange = undefined;
}
}
parseTreeNodesWithAnnotations.length = 0;
}
};
/**
* Transforms a source file.
*
* @param sourceFile The source file to transform.
*/
function transformSourceFile(sourceFile: SourceFile) {
if (isDeclarationFile(sourceFile)) {
return sourceFile;
}
return transformation(sourceFile);
}
/**
* Enables expression substitutions in the pretty printer for the provided SyntaxKind.
*/
function enableSubstitution(kind: SyntaxKind) {
enabledSyntaxKindFeatures[kind] |= SyntaxKindFeatureFlags.Substitution;
}
/**
* Determines whether expression substitutions are enabled for the provided node.
*/
function isSubstitutionEnabled(node: Node) {
return (enabledSyntaxKindFeatures[node.kind] & SyntaxKindFeatureFlags.Substitution) !== 0;
}
/**
* Default hook for node substitutions.
*
* @param node The node to substitute.
* @param isExpression A value indicating whether the node is to be used in an expression
* position.
*/
function onSubstituteNode(node: Node, isExpression: boolean) {
return node;
}
/**
* Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
*/
function enableEmitNotification(kind: SyntaxKind) {
enabledSyntaxKindFeatures[kind] |= SyntaxKindFeatureFlags.EmitNotifications;
}
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
function isEmitNotificationEnabled(node: Node) {
return (enabledSyntaxKindFeatures[node.kind] & SyntaxKindFeatureFlags.EmitNotifications) !== 0
|| (getNodeEmitFlags(node) & NodeEmitFlags.AdviseOnEmitNode) !== 0;
}
/**
* Default hook for node emit.
*
* @param node The node to emit.
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(node: Node, emit: (node: Node) => void) {
emit(node);
}
/**
* Associates a node with the current transformation, initializing
* various transient transformation properties.
*
* @param node The node.
*/
function beforeSetAnnotation(node: Node) {
if ((node.flags & NodeFlags.Synthesized) === 0 && node.transformId !== transformId) {
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
parseTreeNodesWithAnnotations.push(node);
node.transformId = transformId;
}
}
/**
* Gets flags that control emit behavior of a node.
*
* If the node does not have its own NodeEmitFlags set, the node emit flags of its
* original pointer are used.
*
* @param node The node.
*/
function getNodeEmitFlags(node: Node) {
return node.emitFlags;
}
/**
* Sets flags that control emit behavior of a node.
*
* @param node The node.
* @param emitFlags The NodeEmitFlags for the node.
*/
function setNodeEmitFlags<T extends Node>(node: T, emitFlags: NodeEmitFlags) {
beforeSetAnnotation(node);
node.emitFlags = emitFlags;
return node;
}
/**
* Gets a custom text range to use when emitting source maps.
*
* If a node does not have its own custom source map text range, the custom source map
* text range of its original pointer is used.
*
* @param node The node.
*/
function getSourceMapRange(node: Node) {
return node.sourceMapRange || node;
}
/**
* Sets a custom text range to use when emitting source maps.
*
* @param node The node.
* @param range The text range.
*/
function setSourceMapRange<T extends Node>(node: T, range: TextRange) {
beforeSetAnnotation(node);
node.sourceMapRange = range;
return node;
}
/**
* Gets the TextRange to use for source maps for a token of a node.
*
* If a node does not have its own custom source map text range for a token, the custom
* source map text range for the token of its original pointer is used.
*
* @param node The node.
* @param token The token.
*/
function getTokenSourceMapRange(node: Node, token: SyntaxKind) {
// As a performance optimization, use the cached value of the most recent node.
// This helps for cases where this function is called repeatedly for the same node.
if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) {
return lastTokenSourceMapRange;
}
// Get the custom token source map range for a node or from one of its original nodes.
// Custom token ranges are not stored on the node to avoid the GC burden.
let range: TextRange;
let current = node;
while (current) {
range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined;
if (range !== undefined) {
break;
}
current = current.original;
}
// Cache the most recently requested value.
lastTokenSourceMapRangeNode = node;
lastTokenSourceMapRangeToken = token;
lastTokenSourceMapRange = range;
return range;
}
/**
* Sets the TextRange to use for source maps for a token of a node.
*
* @param node The node.
* @param token The token.
* @param range The text range.
*/
function setTokenSourceMapRange<T extends Node>(node: T, token: SyntaxKind, range: TextRange) {
// Cache the most recently requested value.
lastTokenSourceMapRangeNode = node;
lastTokenSourceMapRangeToken = token;
lastTokenSourceMapRange = range;
tokenSourceMapRanges[getNodeId(node) + "-" + token] = range;
return node;
}
/**
* Gets a custom text range to use when emitting comments.
*
* If a node does not have its own custom source map text range, the custom source map
* text range of its original pointer is used.
*
* @param node The node.
*/
function getCommentRange(node: Node) {
return node.commentRange || node;
}
/**
* Sets a custom text range to use when emitting comments.
*/
function setCommentRange<T extends Node>(node: T, range: TextRange) {
beforeSetAnnotation(node);
node.commentRange = range;
return node;
}
/**
* Records a hoisted variable declaration for the provided name within a lexical environment.
*/
function hoistVariableDeclaration(name: Identifier): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
const decl = createVariableDeclaration(name);
if (!hoistedVariableDeclarations) {
hoistedVariableDeclarations = [decl];
}
else {
hoistedVariableDeclarations.push(decl);
}
}
/**
* Records a hoisted function declaration within a lexical environment.
*/
function hoistFunctionDeclaration(func: FunctionDeclaration): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase.");
if (!hoistedFunctionDeclarations) {
hoistedFunctionDeclarations = [func];
}
else {
hoistedFunctionDeclarations.push(func);
}
}
/**
* Starts a new lexical environment. Any existing hoisted variable or function declarations
* are pushed onto a stack, and the related storage variables are reset.
*/
function startLexicalEnvironment(): void {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot start a lexical environment during the print phase.");
// Save the current lexical environment. Rather than resizing the array we adjust the
// stack size variable. This allows us to reuse existing array slots we've
// already allocated between transformations to avoid allocation and GC overhead during
// transformation.
lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedVariableDeclarations;
lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = hoistedFunctionDeclarations;
lexicalEnvironmentStackOffset++;
hoistedVariableDeclarations = undefined;
hoistedFunctionDeclarations = undefined;
}
/**
* Ends a lexical environment. The previous set of hoisted declarations are restored and
* any hoisted declarations added in this environment are returned.
*/
function endLexicalEnvironment(): Statement[] {
Debug.assert(!lexicalEnvironmentDisabled, "Cannot end a lexical environment during the print phase.");
let statements: Statement[];
if (hoistedVariableDeclarations || hoistedFunctionDeclarations) {
if (hoistedFunctionDeclarations) {
statements = [...hoistedFunctionDeclarations];
}
if (hoistedVariableDeclarations) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(hoistedVariableDeclarations)
);
if (!statements) {
statements = [statement];
}
else {
statements.push(statement);
}
}
}
// Restore the previous lexical environment.
lexicalEnvironmentStackOffset--;
hoistedVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
hoistedFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
return statements;
}
}
/**
* High-order function, creates a function that executes a function composition.
* For example, `chain(a, b)` is the equivalent of `x => ((a', b') => y => b'(a'(y)))(a(x), b(x))`
*
* @param args The functions to chain.
*/
function chain<T, U>(...args: ((t: T) => (u: U) => U)[]): (t: T) => (u: U) => U;
function chain<T, U>(a: (t: T) => (u: U) => U, b: (t: T) => (u: U) => U, c: (t: T) => (u: U) => U, d: (t: T) => (u: U) => U, e: (t: T) => (u: U) => U): (t: T) => (u: U) => U {
if (e) {
const args: ((t: T) => (u: U) => U)[] = [];
for (let i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return t => compose(...map(args, f => f(t)));
}
else if (d) {
return t => compose(a(t), b(t), c(t), d(t));
}
else if (c) {
return t => compose(a(t), b(t), c(t));
}
else if (b) {
return t => compose(a(t), b(t));
}
else if (a) {
return t => compose(a(t));
}
else {
return t => u => u;
}
}
/**
* High-order function, composes functions. Note that functions are composed inside-out;
* for example, `compose(a, b)` is the equivalent of `x => b(a(x))`.
*
* @param args The functions to compose.
*/
function compose<T>(...args: ((t: T) => T)[]): (t: T) => T;
function compose<T>(a: (t: T) => T, b: (t: T) => T, c: (t: T) => T, d: (t: T) => T, e: (t: T) => T): (t: T) => T {
if (e) {
const args: ((t: T) => T)[] = [];
for (let i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return t => reduceLeft<(t: T) => T, T>(args, (u, f) => f(u), t);
}
else if (d) {
return t => d(c(b(a(t))));
}
else if (c) {
return t => c(b(a(t)));
}
else if (b) {
return t => b(a(t));
}
else if (a) {
return t => a(t);
}
else {
return t => t;
}
}
}
+426
View File
@@ -0,0 +1,426 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/*@internal*/
namespace ts {
/**
* Flattens a destructuring assignment expression.
*
* @param root The destructuring assignment expression.
* @param needsValue Indicates whether the value from the right-hand-side of the
* destructuring assignment is needed as part of a larger expression.
* @param recordTempVariable A callback used to record new temporary variables.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenDestructuringAssignment(
context: TransformationContext,
node: BinaryExpression,
needsValue: boolean,
recordTempVariable: (node: Identifier) => void,
visitor?: (node: Node) => VisitResult<Node>): Expression {
if (isEmptyObjectLiteralOrArrayLiteral(node.left)) {
const right = node.right;
if (isDestructuringAssignment(right)) {
return flattenDestructuringAssignment(context, right, needsValue, recordTempVariable, visitor);
}
else {
return node.right;
}
}
let location: TextRange = node;
let value = node.right;
const expressions: Expression[] = [];
if (needsValue) {
// If the right-hand value of the destructuring assignment needs to be preserved (as
// is the case when the destructuring assignmen) is part of a larger expression),
// then we need to cache the right-hand value.
//
// The source map location for the assignment should point to the entire binary
// expression.
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment, visitor);
}
else if (nodeIsSynthesized(node)) {
// Generally, the source map location for a destructuring assignment is the root
// expression.
//
// However, if the root expression is synthesized (as in the case
// of the initializer when transforming a ForOfStatement), then the source map
// location should point to the right-hand value of the expression.
location = value;
}
flattenDestructuring(context, node, value, location, emitAssignment, emitTempVariableAssignment, visitor);
if (needsValue) {
expressions.push(value);
}
const expression = inlineExpressions(expressions);
aggregateTransformFlags(expression);
return expression;
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
const expression = createAssignment(name, value, location);
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(expression, NodeEmitFlags.NoNestedSourceMaps);
aggregateTransformFlags(expression);
expressions.push(expression);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(recordTempVariable);
emitAssignment(name, value, location);
return name;
}
}
/**
* Flattens binding patterns in a parameter declaration.
*
* @param node The ParameterDeclaration to flatten.
* @param value The rhs value for the binding pattern.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenParameterDestructuring(
context: TransformationContext,
node: ParameterDeclaration,
value: Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const declarations: VariableDeclaration[] = [];
flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
return declarations;
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(declaration, NodeEmitFlags.NoNestedSourceMaps);
aggregateTransformFlags(declaration);
declarations.push(declaration);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(/*recordTempVariable*/ undefined);
emitAssignment(name, value, location);
return name;
}
}
/**
* Flattens binding patterns in a variable declaration.
*
* @param node The VariableDeclaration to flatten.
* @param value An optional rhs value for the binding pattern.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenVariableDestructuring(
context: TransformationContext,
node: VariableDeclaration,
value?: Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const declarations: VariableDeclaration[] = [];
flattenDestructuring(context, node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
return declarations;
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
declaration.original = original;
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(declaration, NodeEmitFlags.NoNestedSourceMaps);
declarations.push(declaration);
aggregateTransformFlags(declaration);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(/*recordTempVariable*/ undefined);
emitAssignment(name, value, location, /*original*/ undefined);
return name;
}
}
/**
* Flattens binding patterns in a variable declaration and transforms them into an expression.
*
* @param node The VariableDeclaration to flatten.
* @param recordTempVariable A callback used to record new temporary variables.
* @param nameSubstitution An optional callback used to substitute binding names.
* @param visitor An optional visitor to use to visit expressions.
*/
export function flattenVariableDestructuringToExpression(
context: TransformationContext,
node: VariableDeclaration,
recordTempVariable: (name: Identifier) => void,
nameSubstitution?: (name: Identifier) => Expression,
visitor?: (node: Node) => VisitResult<Node>) {
const pendingAssignments: Expression[] = [];
flattenDestructuring(context, node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor);
const expression = inlineExpressions(pendingAssignments);
aggregateTransformFlags(expression);
return expression;
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
const left = nameSubstitution && nameSubstitution(name) || name;
emitPendingAssignment(left, value, location, original);
}
function emitTempVariableAssignment(value: Expression, location: TextRange) {
const name = createTempVariable(recordTempVariable);
emitPendingAssignment(name, value, location, /*original*/ undefined);
return name;
}
function emitPendingAssignment(name: Expression, value: Expression, location: TextRange, original: Node) {
const expression = createAssignment(name, value, location);
expression.original = original;
// NOTE: this completely disables source maps, but aligns with the behavior of
// `emitAssignment` in the old emitter.
context.setNodeEmitFlags(expression, NodeEmitFlags.NoNestedSourceMaps);
pendingAssignments.push(expression);
return expression;
}
}
function flattenDestructuring(
context: TransformationContext,
root: BindingElement | BinaryExpression,
value: Expression,
location: TextRange,
emitAssignment: (name: Identifier, value: Expression, location: TextRange, original: Node) => void,
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
visitor?: (node: Node) => VisitResult<Node>) {
if (value && visitor) {
value = visitNode(value, visitor, isExpression);
}
if (isBinaryExpression(root)) {
emitDestructuringAssignment(root.left, value, location);
}
else {
emitBindingElement(root, value);
}
function emitDestructuringAssignment(bindingTarget: Expression | ShorthandPropertyAssignment, value: Expression, location: TextRange) {
// When emitting target = value use source map node to highlight, including any temporary assignments needed for this
let target: Expression;
if (isShorthandPropertyAssignment(bindingTarget)) {
const initializer = visitor
? visitNode(bindingTarget.objectAssignmentInitializer, visitor, isExpression)
: bindingTarget.objectAssignmentInitializer;
if (initializer) {
value = createDefaultValueCheck(value, initializer, location);
}
target = bindingTarget.name;
}
else if (isBinaryExpression(bindingTarget) && bindingTarget.operatorToken.kind === SyntaxKind.EqualsToken) {
const initializer = visitor
? visitNode(bindingTarget.right, visitor, isExpression)
: bindingTarget.right;
value = createDefaultValueCheck(value, initializer, location);
target = bindingTarget.left;
}
else {
target = bindingTarget;
}
if (target.kind === SyntaxKind.ObjectLiteralExpression) {
emitObjectLiteralAssignment(<ObjectLiteralExpression>target, value, location);
}
else if (target.kind === SyntaxKind.ArrayLiteralExpression) {
emitArrayLiteralAssignment(<ArrayLiteralExpression>target, value, location);
}
else {
const name = getMutableClone(<Identifier>target);
context.setSourceMapRange(name, target);
context.setCommentRange(name, target);
emitAssignment(name, value, location, /*original*/ undefined);
}
}
function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression, location: TextRange) {
const properties = target.properties;
if (properties.length !== 1) {
// For anything but a single element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once.
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
}
for (const p of properties) {
if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) {
const propName = <Identifier | LiteralExpression>(<PropertyAssignment>p).name;
const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? <ShorthandPropertyAssignment>p : (<PropertyAssignment>p).initializer || propName;
// Assignment for target = value.propName should highligh whole property, hence use p as source map node
emitDestructuringAssignment(target, createDestructuringPropertyAccess(value, propName), p);
}
}
}
function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) {
const elements = target.elements;
const numElements = elements.length;
if (numElements !== 1) {
// For anything but a single element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once.
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
}
for (let i = 0; i < numElements; i++) {
const e = elements[i];
if (e.kind !== SyntaxKind.OmittedExpression) {
// Assignment for target = value.propName should highligh whole property, hence use e as source map node
if (e.kind !== SyntaxKind.SpreadElementExpression) {
emitDestructuringAssignment(e, createElementAccess(value, createLiteral(i)), e);
}
else if (i === numElements - 1) {
emitDestructuringAssignment((<SpreadElementExpression>e).expression, createArraySlice(value, i), e);
}
}
}
}
function emitBindingElement(target: BindingElement, value: Expression) {
// Any temporary assignments needed to emit target = value should point to target
const initializer = visitor ? visitNode(target.initializer, visitor, isExpression) : target.initializer;
if (initializer) {
// Combine value and initializer
value = value ? createDefaultValueCheck(value, initializer, target) : initializer;
}
else if (!value) {
// Use 'void 0' in absence of value and initializer
value = createVoidZero();
}
const name = target.name;
if (isBindingPattern(name)) {
const elements = name.elements;
const numElements = elements.length;
if (numElements !== 1) {
// For anything other than a single-element destructuring we need to generate a temporary
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
// we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
// so in that case, we'll intentionally create that temporary.
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment);
}
for (let i = 0; i < numElements; i++) {
const element = elements[i];
if (isOmittedExpression(element)) {
continue;
}
else if (name.kind === SyntaxKind.ObjectBindingPattern) {
// Rewrite element to a declaration with an initializer that fetches property
const propName = element.propertyName || <Identifier>element.name;
emitBindingElement(element, createDestructuringPropertyAccess(value, propName));
}
else {
if (!element.dotDotDotToken) {
// Rewrite element to a declaration that accesses array element at index i
emitBindingElement(element, createElementAccess(value, i));
}
else if (i === numElements - 1) {
emitBindingElement(element, createArraySlice(value, i));
}
}
}
}
else {
emitAssignment(name, value, target, target);
}
}
function createDefaultValueCheck(value: Expression, defaultValue: Expression, location: TextRange): Expression {
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
return createConditional(
createStrictEquality(value, createVoidZero()),
createToken(SyntaxKind.QuestionToken),
defaultValue,
createToken(SyntaxKind.ColonToken),
value
);
}
/**
* Creates either a PropertyAccessExpression or an ElementAccessExpression for the
* right-hand side of a transformed destructuring assignment.
*
* @param expression The right-hand expression that is the source of the property.
* @param propertyName The destructuring property name.
*/
function createDestructuringPropertyAccess(expression: Expression, propertyName: PropertyName): LeftHandSideExpression {
if (isComputedPropertyName(propertyName)) {
return createElementAccess(
expression,
ensureIdentifier(propertyName.expression, /*reuseIdentifierExpressions*/ false, /*location*/ propertyName, emitTempVariableAssignment)
);
}
else if (isLiteralExpression(propertyName)) {
const clone = getSynthesizedClone(propertyName);
clone.text = unescapeIdentifier(clone.text);
return createElementAccess(expression, clone);
}
else {
if (isGeneratedIdentifier(propertyName)) {
const clone = getSynthesizedClone(propertyName);
clone.text = unescapeIdentifier(clone.text);
return createPropertyAccess(expression, clone);
}
else {
return createPropertyAccess(expression, createIdentifier(unescapeIdentifier(propertyName.text)));
}
}
}
}
/**
* Ensures that there exists a declared identifier whose value holds the given expression.
* This function is useful to ensure that the expression's value can be read from in subsequent expressions.
* Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
*
* @param value the expression whose value needs to be bound.
* @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
* false if it is necessary to always emit an identifier.
* @param location The location to use for source maps and comments.
* @param emitTempVariableAssignment A callback used to emit a temporary variable.
* @param visitor An optional callback used to visit the value.
*/
function ensureIdentifier(
value: Expression,
reuseIdentifierExpressions: boolean,
location: TextRange,
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
visitor?: (node: Node) => VisitResult<Node>) {
if (isIdentifier(value) && reuseIdentifierExpressions) {
return value;
}
else {
if (visitor) {
value = visitNode(value, visitor, isExpression);
}
return emitTempVariableAssignment(value, location);
}
}
}
File diff suppressed because it is too large Load Diff
+97
View File
@@ -0,0 +1,97 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/*@internal*/
namespace ts {
export function transformES7(context: TransformationContext) {
const { hoistVariableDeclaration } = context;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES7) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES7) {
return visitEachChild(node, visitor, context);
}
else {
return node;
}
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
default:
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
function visitBinaryExpression(node: BinaryExpression): Expression {
// We are here because ES7 adds support for the exponentiation operator.
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) {
let target: Expression;
let value: Expression;
if (isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
target = createElementAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
/*location*/ left
);
value = createElementAccess(
expressionTemp,
argumentExpressionTemp,
/*location*/ left
);
}
else if (isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
target = createPropertyAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
left.name,
/*location*/ left
);
value = createPropertyAccess(
expressionTemp,
left.name,
/*location*/ left
);
}
else {
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node);
}
else if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskToken) {
// Transforms `a ** b` into `Math.pow(a, b)`
return createMathPow(left, right, /*location*/ node);
}
else {
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
}
}
File diff suppressed because it is too large Load Diff
+531
View File
@@ -0,0 +1,531 @@
/// <reference path="../factory.ts" />
/// <reference path="../visitor.ts" />
/*@internal*/
namespace ts {
const entities: Map<number> = createEntitiesMap();
export function transformJsx(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
let currentSourceFile: SourceFile;
return transformSourceFile;
/**
* Transform JSX-specific syntax in a SourceFile.
*
* @param node A SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
currentSourceFile = node;
node = visitEachChild(node, visitor, context);
currentSourceFile = undefined;
return node;
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.Jsx) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsJsx) {
return visitEachChild(node, visitor, context);
}
else {
return node;
}
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.JsxElement:
return visitJsxElement(<JsxElement>node, /*isChild*/ false);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ false);
case SyntaxKind.JsxExpression:
return visitJsxExpression(<JsxExpression>node);
default:
Debug.failBadSyntaxKind(node);
return undefined;
}
}
function transformJsxChildToExpression(node: JsxChild): Expression {
switch (node.kind) {
case SyntaxKind.JsxText:
return visitJsxText(<JsxText>node);
case SyntaxKind.JsxExpression:
return visitJsxExpression(<JsxExpression>node);
case SyntaxKind.JsxElement:
return visitJsxElement(<JsxElement>node, /*isChild*/ true);
case SyntaxKind.JsxSelfClosingElement:
return visitJsxSelfClosingElement(<JsxSelfClosingElement>node, /*isChild*/ true);
default:
Debug.failBadSyntaxKind(node);
return undefined;
}
}
function visitJsxElement(node: JsxElement, isChild: boolean) {
return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
}
function visitJsxSelfClosingElement(node: JsxSelfClosingElement, isChild: boolean) {
return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
}
function visitJsxOpeningLikeElement(node: JsxOpeningLikeElement, children: JsxChild[], isChild: boolean, location: TextRange) {
const tagName = getTagName(node);
let objectProperties: Expression;
const attrs = node.attributes;
if (attrs.length === 0) {
// When there are no attributes, React wants "null"
objectProperties = createNull();
}
else {
// Map spans of JsxAttribute nodes into object literals and spans
// of JsxSpreadAttribute nodes into expressions.
const segments = flatten(
spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread
? map(attrs, transformJsxSpreadAttributeToExpression)
: createObjectLiteral(map(attrs, transformJsxAttributeToObjectLiteralElement))
)
);
if (isJsxSpreadAttribute(attrs[0])) {
// We must always emit at least one object literal before a spread
// argument.
segments.unshift(createObjectLiteral());
}
// Either emit one big object literal (no spread attribs), or
// a call to the __assign helper.
objectProperties = singleOrUndefined(segments)
|| createAssignHelper(currentSourceFile.externalHelpersModuleName, segments);
}
const element = createReactCreateElement(
compilerOptions.reactNamespace,
tagName,
objectProperties,
filter(map(children, transformJsxChildToExpression), isDefined),
node,
location
);
if (isChild) {
startOnNewLine(element);
}
return element;
}
function transformJsxSpreadAttributeToExpression(node: JsxSpreadAttribute) {
return visitNode(node.expression, visitor, isExpression);
}
function transformJsxAttributeToObjectLiteralElement(node: JsxAttribute) {
const name = getAttributeName(node);
const expression = transformJsxAttributeInitializer(node.initializer);
return createPropertyAssignment(name, expression);
}
function transformJsxAttributeInitializer(node: StringLiteral | JsxExpression) {
if (node === undefined) {
return createLiteral(true);
}
else if (node.kind === SyntaxKind.StringLiteral) {
const decoded = tryDecodeEntities((<StringLiteral>node).text);
return decoded ? createLiteral(decoded, /*location*/ node) : node;
}
else if (node.kind === SyntaxKind.JsxExpression) {
return visitJsxExpression(<JsxExpression>node);
}
else {
Debug.failBadSyntaxKind(node);
}
}
function visitJsxText(node: JsxText) {
const text = getTextOfNode(node, /*includeTrivia*/ true);
let parts: Expression[];
let firstNonWhitespace = 0;
let lastNonWhitespace = -1;
// JSX trims whitespace at the end and beginning of lines, except that the
// start/end of a tag is considered a start/end of a line only if that line is
// on the same line as the closing tag. See examples in
// tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (isLineBreak(c)) {
if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
const part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
if (!parts) {
parts = [];
}
// We do not escape the string here as that is handled by the printer
// when it emits the literal. We do, however, need to decode JSX entities.
parts.push(createLiteral(decodeEntities(part)));
}
firstNonWhitespace = -1;
}
else if (!isWhiteSpace(c)) {
lastNonWhitespace = i;
if (firstNonWhitespace === -1) {
firstNonWhitespace = i;
}
}
}
if (firstNonWhitespace !== -1) {
const part = text.substr(firstNonWhitespace);
if (!parts) {
parts = [];
}
// We do not escape the string here as that is handled by the printer
// when it emits the literal. We do, however, need to decode JSX entities.
parts.push(createLiteral(decodeEntities(part)));
}
if (parts) {
return reduceLeft(parts, aggregateJsxTextParts);
}
return undefined;
}
/**
* Aggregates two expressions by interpolating them with a whitespace literal.
*/
function aggregateJsxTextParts(left: Expression, right: Expression) {
return createAdd(createAdd(left, createLiteral(" ")), right);
}
/**
* Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
* See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
*/
function decodeEntities(text: string): string {
return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, (match, _all, _number, _digits, decimal, hex, word) => {
if (decimal) {
return String.fromCharCode(parseInt(decimal, 10));
}
else if (hex) {
return String.fromCharCode(parseInt(hex, 16));
}
else {
const ch = entities[word];
// If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
return ch ? String.fromCharCode(ch) : match;
}
});
}
/** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
function tryDecodeEntities(text: string): string | undefined {
const decoded = decodeEntities(text);
return decoded === text ? undefined : decoded;
}
function getTagName(node: JsxElement | JsxOpeningLikeElement): Expression {
if (node.kind === SyntaxKind.JsxElement) {
return getTagName((<JsxElement>node).openingElement);
}
else {
const name = (<JsxOpeningLikeElement>node).tagName;
if (isIdentifier(name) && isIntrinsicJsxName(name.text)) {
return createLiteral(name.text);
}
else {
return createExpressionFromEntityName(name);
}
}
}
/**
* Emit an attribute name, which is quoted if it needs to be quoted. Because
* these emit into an object literal property name, we don't need to be worried
* about keywords, just non-identifier characters
*/
function getAttributeName(node: JsxAttribute): StringLiteral | Identifier {
const name = node.name;
if (/^[A-Za-z_]\w*$/.test(name.text)) {
return name;
}
else {
return createLiteral(name.text);
}
}
function visitJsxExpression(node: JsxExpression) {
return visitNode(node.expression, visitor, isExpression);
}
}
function createEntitiesMap(): Map<number> {
return createMap<number>({
"quot": 0x0022,
"amp": 0x0026,
"apos": 0x0027,
"lt": 0x003C,
"gt": 0x003E,
"nbsp": 0x00A0,
"iexcl": 0x00A1,
"cent": 0x00A2,
"pound": 0x00A3,
"curren": 0x00A4,
"yen": 0x00A5,
"brvbar": 0x00A6,
"sect": 0x00A7,
"uml": 0x00A8,
"copy": 0x00A9,
"ordf": 0x00AA,
"laquo": 0x00AB,
"not": 0x00AC,
"shy": 0x00AD,
"reg": 0x00AE,
"macr": 0x00AF,
"deg": 0x00B0,
"plusmn": 0x00B1,
"sup2": 0x00B2,
"sup3": 0x00B3,
"acute": 0x00B4,
"micro": 0x00B5,
"para": 0x00B6,
"middot": 0x00B7,
"cedil": 0x00B8,
"sup1": 0x00B9,
"ordm": 0x00BA,
"raquo": 0x00BB,
"frac14": 0x00BC,
"frac12": 0x00BD,
"frac34": 0x00BE,
"iquest": 0x00BF,
"Agrave": 0x00C0,
"Aacute": 0x00C1,
"Acirc": 0x00C2,
"Atilde": 0x00C3,
"Auml": 0x00C4,
"Aring": 0x00C5,
"AElig": 0x00C6,
"Ccedil": 0x00C7,
"Egrave": 0x00C8,
"Eacute": 0x00C9,
"Ecirc": 0x00CA,
"Euml": 0x00CB,
"Igrave": 0x00CC,
"Iacute": 0x00CD,
"Icirc": 0x00CE,
"Iuml": 0x00CF,
"ETH": 0x00D0,
"Ntilde": 0x00D1,
"Ograve": 0x00D2,
"Oacute": 0x00D3,
"Ocirc": 0x00D4,
"Otilde": 0x00D5,
"Ouml": 0x00D6,
"times": 0x00D7,
"Oslash": 0x00D8,
"Ugrave": 0x00D9,
"Uacute": 0x00DA,
"Ucirc": 0x00DB,
"Uuml": 0x00DC,
"Yacute": 0x00DD,
"THORN": 0x00DE,
"szlig": 0x00DF,
"agrave": 0x00E0,
"aacute": 0x00E1,
"acirc": 0x00E2,
"atilde": 0x00E3,
"auml": 0x00E4,
"aring": 0x00E5,
"aelig": 0x00E6,
"ccedil": 0x00E7,
"egrave": 0x00E8,
"eacute": 0x00E9,
"ecirc": 0x00EA,
"euml": 0x00EB,
"igrave": 0x00EC,
"iacute": 0x00ED,
"icirc": 0x00EE,
"iuml": 0x00EF,
"eth": 0x00F0,
"ntilde": 0x00F1,
"ograve": 0x00F2,
"oacute": 0x00F3,
"ocirc": 0x00F4,
"otilde": 0x00F5,
"ouml": 0x00F6,
"divide": 0x00F7,
"oslash": 0x00F8,
"ugrave": 0x00F9,
"uacute": 0x00FA,
"ucirc": 0x00FB,
"uuml": 0x00FC,
"yacute": 0x00FD,
"thorn": 0x00FE,
"yuml": 0x00FF,
"OElig": 0x0152,
"oelig": 0x0153,
"Scaron": 0x0160,
"scaron": 0x0161,
"Yuml": 0x0178,
"fnof": 0x0192,
"circ": 0x02C6,
"tilde": 0x02DC,
"Alpha": 0x0391,
"Beta": 0x0392,
"Gamma": 0x0393,
"Delta": 0x0394,
"Epsilon": 0x0395,
"Zeta": 0x0396,
"Eta": 0x0397,
"Theta": 0x0398,
"Iota": 0x0399,
"Kappa": 0x039A,
"Lambda": 0x039B,
"Mu": 0x039C,
"Nu": 0x039D,
"Xi": 0x039E,
"Omicron": 0x039F,
"Pi": 0x03A0,
"Rho": 0x03A1,
"Sigma": 0x03A3,
"Tau": 0x03A4,
"Upsilon": 0x03A5,
"Phi": 0x03A6,
"Chi": 0x03A7,
"Psi": 0x03A8,
"Omega": 0x03A9,
"alpha": 0x03B1,
"beta": 0x03B2,
"gamma": 0x03B3,
"delta": 0x03B4,
"epsilon": 0x03B5,
"zeta": 0x03B6,
"eta": 0x03B7,
"theta": 0x03B8,
"iota": 0x03B9,
"kappa": 0x03BA,
"lambda": 0x03BB,
"mu": 0x03BC,
"nu": 0x03BD,
"xi": 0x03BE,
"omicron": 0x03BF,
"pi": 0x03C0,
"rho": 0x03C1,
"sigmaf": 0x03C2,
"sigma": 0x03C3,
"tau": 0x03C4,
"upsilon": 0x03C5,
"phi": 0x03C6,
"chi": 0x03C7,
"psi": 0x03C8,
"omega": 0x03C9,
"thetasym": 0x03D1,
"upsih": 0x03D2,
"piv": 0x03D6,
"ensp": 0x2002,
"emsp": 0x2003,
"thinsp": 0x2009,
"zwnj": 0x200C,
"zwj": 0x200D,
"lrm": 0x200E,
"rlm": 0x200F,
"ndash": 0x2013,
"mdash": 0x2014,
"lsquo": 0x2018,
"rsquo": 0x2019,
"sbquo": 0x201A,
"ldquo": 0x201C,
"rdquo": 0x201D,
"bdquo": 0x201E,
"dagger": 0x2020,
"Dagger": 0x2021,
"bull": 0x2022,
"hellip": 0x2026,
"permil": 0x2030,
"prime": 0x2032,
"Prime": 0x2033,
"lsaquo": 0x2039,
"rsaquo": 0x203A,
"oline": 0x203E,
"frasl": 0x2044,
"euro": 0x20AC,
"image": 0x2111,
"weierp": 0x2118,
"real": 0x211C,
"trade": 0x2122,
"alefsym": 0x2135,
"larr": 0x2190,
"uarr": 0x2191,
"rarr": 0x2192,
"darr": 0x2193,
"harr": 0x2194,
"crarr": 0x21B5,
"lArr": 0x21D0,
"uArr": 0x21D1,
"rArr": 0x21D2,
"dArr": 0x21D3,
"hArr": 0x21D4,
"forall": 0x2200,
"part": 0x2202,
"exist": 0x2203,
"empty": 0x2205,
"nabla": 0x2207,
"isin": 0x2208,
"notin": 0x2209,
"ni": 0x220B,
"prod": 0x220F,
"sum": 0x2211,
"minus": 0x2212,
"lowast": 0x2217,
"radic": 0x221A,
"prop": 0x221D,
"infin": 0x221E,
"ang": 0x2220,
"and": 0x2227,
"or": 0x2228,
"cap": 0x2229,
"cup": 0x222A,
"int": 0x222B,
"there4": 0x2234,
"sim": 0x223C,
"cong": 0x2245,
"asymp": 0x2248,
"ne": 0x2260,
"equiv": 0x2261,
"le": 0x2264,
"ge": 0x2265,
"sub": 0x2282,
"sup": 0x2283,
"nsub": 0x2284,
"sube": 0x2286,
"supe": 0x2287,
"oplus": 0x2295,
"otimes": 0x2297,
"perp": 0x22A5,
"sdot": 0x22C5,
"lceil": 0x2308,
"rceil": 0x2309,
"lfloor": 0x230A,
"rfloor": 0x230B,
"lang": 0x2329,
"rang": 0x232A,
"loz": 0x25CA,
"spades": 0x2660,
"clubs": 0x2663,
"hearts": 0x2665,
"diams": 0x2666
});
}
}
+140
View File
@@ -0,0 +1,140 @@
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/*@internal*/
namespace ts {
export function transformES6Module(context: TransformationContext) {
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
let currentSourceFile: SourceFile;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isExternalModule(node) || compilerOptions.isolatedModules) {
currentSourceFile = node;
return visitEachChild(node, visitor, context);
}
return node;
}
function visitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportClause:
return visitImportClause(<ImportClause>node);
case SyntaxKind.NamedImports:
case SyntaxKind.NamespaceImport:
return visitNamedBindings(<NamedImportBindings>node);
case SyntaxKind.ImportSpecifier:
return visitImportSpecifier(<ImportSpecifier>node);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(<ExportDeclaration>node);
case SyntaxKind.NamedExports:
return visitNamedExports(<NamedExports>node);
case SyntaxKind.ExportSpecifier:
return visitExportSpecifier(<ExportSpecifier>node);
}
return node;
}
function visitExportAssignment(node: ExportAssignment): ExportAssignment {
if (node.isExportEquals) {
return undefined; // do not emit export equals for ES6
}
const original = getOriginalNode(node);
return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined;
}
function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration {
if (!node.exportClause) {
return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;
}
if (!resolver.isValueAliasDeclaration(node)) {
return undefined;
}
const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true);
if (node.exportClause === newExportClause) {
return node;
}
return newExportClause
? createExportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
newExportClause,
node.moduleSpecifier)
: undefined;
}
function visitNamedExports(node: NamedExports): NamedExports {
const newExports = visitNodes(node.elements, visitor, isExportSpecifier);
if (node.elements === newExports) {
return node;
}
return newExports.length ? createNamedExports(newExports) : undefined;
}
function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier {
return resolver.isValueAliasDeclaration(node) ? node : undefined;
}
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration {
return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
function visitImportDeclaration(node: ImportDeclaration) {
if (node.importClause) {
const newImportClause = visitNode(node.importClause, visitor, isImportClause);
if (!newImportClause.name && !newImportClause.namedBindings) {
return undefined;
}
else if (newImportClause !== node.importClause) {
return createImportDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
newImportClause,
node.moduleSpecifier);
}
}
return node;
}
function visitImportClause(node: ImportClause): ImportClause {
let newDefaultImport = node.name;
if (!resolver.isReferencedAliasDeclaration(node)) {
newDefaultImport = undefined;
}
const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true);
return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings
? createImportClause(newDefaultImport, newNamedBindings)
: node;
}
function visitNamedBindings(node: NamedImportBindings): VisitResult<NamedImportBindings> {
if (node.kind === SyntaxKind.NamespaceImport) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
else {
const newNamedImportElements = visitNodes((<NamedImports>node).elements, visitor, isImportSpecifier);
if (!newNamedImportElements || newNamedImportElements.length == 0) {
return undefined;
}
if (newNamedImportElements === (<NamedImports>node).elements) {
return node;
}
return createNamedImports(newNamedImportElements);
}
}
function visitImportSpecifier(node: ImportSpecifier) {
return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+46 -17
View File
@@ -6,6 +6,11 @@ namespace ts {
fileWatcher?: FileWatcher;
}
interface Statistic {
name: string;
value: string;
}
const defaultFormatDiagnosticsHost: FormatDiagnosticsHost = {
getCurrentDirectory: () => sys.getCurrentDirectory(),
getNewLine: () => sys.newLine,
@@ -230,18 +235,6 @@ namespace ts {
return s;
}
function reportStatisticalValue(name: string, value: string) {
sys.write(padRight(name + ":", 12) + padLeft(value.toString(), 10) + sys.newLine);
}
function reportCountStatistic(name: string, count: number) {
reportStatisticalValue(name, "" + count);
}
function reportTimeStatistic(name: string, time: number) {
reportStatisticalValue(name, (time / 1000).toFixed(2) + "s");
}
function isJSONSupported() {
return typeof JSON === "object" && typeof JSON.parse === "function";
}
@@ -489,10 +482,7 @@ namespace ts {
sourceFile.fileWatcher.close();
sourceFile.fileWatcher = undefined;
if (removed) {
const index = rootFileNames.indexOf(sourceFile.fileName);
if (index >= 0) {
rootFileNames.splice(index, 1);
}
unorderedRemoveItem(rootFileNames, sourceFile.fileName);
}
startTimerForRecompilation();
}
@@ -550,7 +540,11 @@ namespace ts {
function compile(fileNames: string[], compilerOptions: CompilerOptions, compilerHost: CompilerHost) {
const hasDiagnostics = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics;
if (hasDiagnostics) performance.enable();
let statistics: Statistic[];
if (hasDiagnostics) {
performance.enable();
statistics = [];
}
const program = createProgram(fileNames, compilerOptions, compilerHost);
const exitStatus = compileProgram();
@@ -594,6 +588,7 @@ namespace ts {
reportTimeStatistic("Emit time", emitTime);
}
reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime);
reportStatistics();
performance.disable();
}
@@ -635,6 +630,36 @@ namespace ts {
}
return ExitStatus.Success;
}
function reportStatistics() {
let nameSize = 0;
let valueSize = 0;
for (const { name, value } of statistics) {
if (name.length > nameSize) {
nameSize = name.length;
}
if (value.length > valueSize) {
valueSize = value.length;
}
}
for (const { name, value } of statistics) {
sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + sys.newLine);
}
}
function reportStatisticalValue(name: string, value: string) {
statistics.push({ name, value });
}
function reportCountStatistic(name: string, count: number) {
reportStatisticalValue(name, "" + count);
}
function reportTimeStatistic(name: string, time: number) {
reportStatisticalValue(name, (time / 1000).toFixed(2) + "s");
}
}
function printVersion() {
@@ -771,4 +796,8 @@ namespace ts {
}
}
if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) {
ts.sys.tryEnableSourceMapsForHost();
}
ts.executeCommandLine(ts.sys.args);
+13
View File
@@ -20,6 +20,19 @@
"utilities.ts",
"binder.ts",
"checker.ts",
"factory.ts",
"visitor.ts",
"transformers/ts.ts",
"transformers/jsx.ts",
"transformers/es7.ts",
"transformers/es6.ts",
"transformers/generators.ts",
"transformers/destructuring.ts",
"transformers/module/module.ts",
"transformers/module/system.ts",
"transformers/module/es6.ts",
"transformer.ts",
"comments.ts",
"sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
+258 -58
View File
@@ -357,11 +357,18 @@ namespace ts {
// Synthesized list
SyntaxList,
// Transformation nodes
NotEmittedStatement,
PartiallyEmittedExpression,
// Enum value count
Count,
// Markers
FirstAssignment = EqualsToken,
LastAssignment = CaretEqualsToken,
FirstCompoundAssignment = PlusEqualsToken,
LastCompoundAssignment = CaretEqualsToken,
FirstReservedWord = BreakKeyword,
LastReservedWord = WithKeyword,
FirstKeyword = BreakKeyword,
@@ -390,6 +397,47 @@ namespace ts {
}
export const enum NodeFlags {
None = 0,
Let = 1 << 0, // Variable declaration
Const = 1 << 1, // Variable declaration
NestedNamespace = 1 << 2, // Namespace declaration
Synthesized = 1 << 3, // Node was synthesized during transformation
Namespace = 1 << 4, // Namespace declaration
ExportContext = 1 << 5, // Export context (initialized by binding)
ContainsThis = 1 << 6, // Interface contains references to "this"
HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope
HasClassExtends = 1 << 10, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
HasDecorators = 1 << 11, // If the file has decorators (initialized by binding)
HasParamDecorators = 1 << 12, // If the file has parameter decorators (initialized by binding)
HasAsyncFunctions = 1 << 13, // If the file has async functions (initialized by binding)
HasJsxSpreadAttributes = 1 << 14, // If the file as JSX spread attributes (initialized by binding)
DisallowInContext = 1 << 15, // If node was parsed in a context where 'in-expressions' are not allowed
YieldContext = 1 << 16, // If node was parsed in the 'yield' context created when parsing a generator
DecoratorContext = 1 << 17, // If node was parsed as part of a decorator
AwaitContext = 1 << 18, // If node was parsed in the 'await' context created when parsing an async function
ThisNodeHasError = 1 << 19, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 20, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 21, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node
BlockScoped = Let | Const,
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions | HasJsxSpreadAttributes,
ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags,
// Parsing context flags
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile,
// Exclude these flags when parsing a Type
TypeExcludesFlags = YieldContext | AwaitContext,
}
export type ModifiersArray = NodeArray<Modifier>;
export const enum ModifierFlags {
None = 0,
Export = 1 << 0, // Declarations
Ambient = 1 << 1, // Declarations
@@ -401,43 +449,14 @@ namespace ts {
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
Let = 1 << 10, // Variable declaration
Const = 1 << 11, // Variable declaration
Namespace = 1 << 12, // Namespace declaration
ExportContext = 1 << 13, // Export context (initialized by binding)
ContainsThis = 1 << 14, // Interface contains references to "this"
HasImplicitReturn = 1 << 15, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 16, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 17, // Set if module declaration is an augmentation for the global scope
HasClassExtends = 1 << 18, // If the file has a non-ambient class with an extends clause in ES5 or lower (initialized by binding)
HasDecorators = 1 << 19, // If the file has decorators (initialized by binding)
HasParamDecorators = 1 << 20, // If the file has parameter decorators (initialized by binding)
HasAsyncFunctions = 1 << 21, // If the file has async functions (initialized by binding)
DisallowInContext = 1 << 22, // If node was parsed in a context where 'in-expressions' are not allowed
YieldContext = 1 << 23, // If node was parsed in the 'yield' context created when parsing a generator
DecoratorContext = 1 << 24, // If node was parsed as part of a decorator
AwaitContext = 1 << 25, // If node was parsed in the 'await' context created when parsing an async function
ThisNodeHasError = 1 << 26, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 27, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 28, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 29, // If we've computed data from children and cached it in this node
HasJsxSpreadAttribute = 1 << 30,
Const = 1 << 11, // Variable declaration
HasComputedFlags = 1 << 29, // Modifier flags have been computed
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async | Readonly,
AccessibilityModifier = Public | Private | Protected,
// Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
ParameterPropertyModifier = AccessibilityModifier | Readonly,
BlockScoped = Let | Const,
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions,
ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags,
// Parsing context flags
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile,
// Exclude these flags when parsing a Type
TypeExcludesFlags = YieldContext | AwaitContext,
NonPublicAccessibilityModifier = Private | Protected,
}
export const enum JsxFlags {
@@ -460,26 +479,30 @@ namespace ts {
export interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
/* @internal */ modifierFlagsCache?: ModifierFlags;
/* @internal */ transformFlags?: TransformFlags;
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
modifiers?: ModifiersArray; // Array of modifiers
/* @internal */ id?: number; // Unique id (used to look up NodeLinks)
parent?: Node; // Parent node (initialized by binding
parent?: Node; // Parent node (initialized by binding)
/* @internal */ original?: Node; // The original node if this is an updated node.
/* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms).
/* @internal */ jsDocComments?: JSDocComment[]; // JSDoc for the node, if it has any. Only for .js files.
/* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding)
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
/* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
/* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding)
/* @internal */ transformId?: number; // Associates transient transformation properties with a specific transformation (initialized by transformation).
/* @internal */ emitFlags?: NodeEmitFlags; // Transient emit flags for a synthesized node (initialized by transformation).
/* @internal */ sourceMapRange?: TextRange; // Transient custom sourcemap range for a synthesized node (initialized by transformation).
/* @internal */ commentRange?: TextRange; // Transient custom comment range for a synthesized node (initialized by transformation).
}
export interface NodeArray<T> extends Array<T>, TextRange {
export interface NodeArray<T extends Node> extends Array<T>, TextRange {
hasTrailingComma?: boolean;
}
export interface ModifiersArray extends NodeArray<Modifier> {
flags: NodeFlags;
}
export interface Token extends Node {
__tokenTag: any;
}
@@ -496,10 +519,26 @@ namespace ts {
// @kind(SyntaxKind.StaticKeyword)
export interface Modifier extends Token { }
/*@internal*/
export const enum GeneratedIdentifierKind {
None, // Not automatically generated.
Auto, // Automatically generated identifier.
Loop, // Automatically generated identifier with a preference for '_i'.
Unique, // Unique name based on the 'text' property.
Node, // Unique name based on the node in the 'original' property.
}
// @kind(SyntaxKind.Identifier)
export interface Identifier extends PrimaryExpression {
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
}
// Transient identifier node (marked by id === -1)
export interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
// @kind(SyntaxKind.QualifiedName)
@@ -556,10 +595,12 @@ namespace ts {
// @kind(SyntaxKind.ConstructSignature)
export interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { }
export type BindingName = Identifier | BindingPattern;
// @kind(SyntaxKind.VariableDeclaration)
export interface VariableDeclaration extends Declaration {
parent?: VariableDeclarationList;
name: Identifier | BindingPattern; // Declared variable name
name: BindingName; // Declared variable name
type?: TypeNode; // Optional type annotation
initializer?: Expression; // Optional initializer
}
@@ -572,7 +613,7 @@ namespace ts {
// @kind(SyntaxKind.Parameter)
export interface ParameterDeclaration extends Declaration {
dotDotDotToken?: Node; // Present on rest parameter
name: Identifier | BindingPattern; // Declared parameter name
name: BindingName; // Declared parameter name
questionToken?: Node; // Present on optional parameter
type?: TypeNode; // Optional type annotation
initializer?: Expression; // Optional initializer
@@ -582,7 +623,7 @@ namespace ts {
export interface BindingElement extends Declaration {
propertyName?: PropertyName; // Binding property name (in object binding pattern)
dotDotDotToken?: Node; // Present on rest binding element
name: Identifier | BindingPattern; // Declared binding element name
name: BindingName; // Declared binding element name
initializer?: Expression; // Optional initializer
}
@@ -647,14 +688,20 @@ namespace ts {
}
export interface BindingPattern extends Node {
elements: NodeArray<BindingElement>;
elements: NodeArray<BindingElement | ArrayBindingElement>;
}
// @kind(SyntaxKind.ObjectBindingPattern)
export interface ObjectBindingPattern extends BindingPattern { }
export interface ObjectBindingPattern extends BindingPattern {
elements: NodeArray<BindingElement>;
}
export type ArrayBindingElement = BindingElement | OmittedExpression;
// @kind(SyntaxKind.ArrayBindingPattern)
export interface ArrayBindingPattern extends BindingPattern { }
export interface ArrayBindingPattern extends BindingPattern {
elements: NodeArray<ArrayBindingElement>;
}
/**
* Several node kinds share function-like features such as a signature,
@@ -810,6 +857,8 @@ namespace ts {
// @kind(SyntaxKind.StringLiteral)
export interface StringLiteral extends LiteralExpression {
_stringLiteralBrand: any;
/* @internal */
textSourceNode?: Identifier | StringLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
}
// Note: 'brands' in our syntax nodes serve to give us a small amount of nominal typing.
@@ -825,7 +874,17 @@ namespace ts {
}
// @kind(SyntaxKind.OmittedExpression)
export interface OmittedExpression extends Expression { }
export interface OmittedExpression extends Expression {
_omittedExpressionBrand: any;
}
// Represents an expression that is elided as part of a transformation to emit comments on a
// not-emitted node. The 'expression' property of a NotEmittedExpression should be emitted.
// @internal
// @kind(SyntaxKind.NotEmittedExpression)
export interface PartiallyEmittedExpression extends LeftHandSideExpression {
expression: Expression;
}
export interface UnaryExpression extends Expression {
_unaryExpressionBrand: any;
@@ -937,13 +996,18 @@ namespace ts {
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
// or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
// For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
// @kind(SyntaxKind.NumericLiteral)
// @kind(SyntaxKind.RegularExpressionLiteral)
// @kind(SyntaxKind.NoSubstitutionTemplateLiteral)
export interface LiteralExpression extends LiteralLikeNode, PrimaryExpression {
_literalExpressionBrand: any;
}
// @kind(SyntaxKind.NumericLiteral)
export interface NumericLiteral extends LiteralExpression {
_numericLiteralBrand: any;
trailingComment?: string;
}
// @kind(SyntaxKind.TemplateHead)
// @kind(SyntaxKind.TemplateMiddle)
// @kind(SyntaxKind.TemplateTail)
@@ -951,6 +1015,8 @@ namespace ts {
_templateLiteralFragmentBrand: any;
}
export type Template = TemplateExpression | LiteralExpression;
// @kind(SyntaxKind.TemplateExpression)
export interface TemplateExpression extends PrimaryExpression {
head: TemplateLiteralFragment;
@@ -1029,7 +1095,7 @@ namespace ts {
// @kind(SyntaxKind.TaggedTemplateExpression)
export interface TaggedTemplateExpression extends MemberExpression {
tag: LeftHandSideExpression;
template: LiteralExpression | TemplateExpression;
template: Template;
}
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
@@ -1080,11 +1146,13 @@ namespace ts {
/// Either the opening tag in a <Tag>...</Tag> pair, or the lone <Tag /> in a self-closing form
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
export type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute;
// @kind(SyntaxKind.JsxAttribute)
export interface JsxAttribute extends Node {
name: Identifier;
/// JSX attribute initializers are optional; <X y /> is sugar for <X y={true} />
initializer?: Expression;
initializer?: StringLiteral | JsxExpression;
}
// @kind(SyntaxKind.JsxSpreadAttribute)
@@ -1113,6 +1181,13 @@ namespace ts {
_statementBrand: any;
}
// Represents a statement that is elided as part of a transformation to emit comments on a
// not-emitted node.
// @internal
// @kind(SyntaxKind.NotEmittedStatement)
export interface NotEmittedStatement extends Statement {
}
// @kind(SyntaxKind.EmptyStatement)
export interface EmptyStatement extends Statement { }
@@ -1129,6 +1204,7 @@ namespace ts {
// @kind(SyntaxKind.Block)
export interface Block extends Statement {
statements: NodeArray<Statement>;
/*@internal*/ multiLine?: boolean;
}
// @kind(SyntaxKind.VariableStatement)
@@ -1162,22 +1238,24 @@ namespace ts {
expression: Expression;
}
export type ForInitializer = VariableDeclarationList | Expression;
// @kind(SyntaxKind.ForStatement)
export interface ForStatement extends IterationStatement {
initializer?: VariableDeclarationList | Expression;
initializer?: ForInitializer;
condition?: Expression;
incrementor?: Expression;
}
// @kind(SyntaxKind.ForInStatement)
export interface ForInStatement extends IterationStatement {
initializer: VariableDeclarationList | Expression;
initializer: ForInitializer;
expression: Expression;
}
// @kind(SyntaxKind.ForOfStatement)
export interface ForOfStatement extends IterationStatement {
initializer: VariableDeclarationList | Expression;
initializer: ForInitializer;
expression: Expression;
}
@@ -1307,7 +1385,7 @@ namespace ts {
export interface EnumMember extends Declaration {
// This does include ComputedPropertyName, but the parser will give an error
// if it parses a ComputedPropertyName in an EnumMember
name: DeclarationName;
name: PropertyName;
initializer?: Expression;
}
@@ -1319,6 +1397,8 @@ namespace ts {
export type ModuleBody = ModuleBlock | ModuleDeclaration;
export type ModuleName = Identifier | StringLiteral;
// @kind(SyntaxKind.ModuleDeclaration)
export interface ModuleDeclaration extends DeclarationStatement {
name: Identifier | LiteralExpression;
@@ -1330,13 +1410,15 @@ namespace ts {
statements: NodeArray<Statement>;
}
export type ModuleReference = EntityName | ExternalModuleReference;
// @kind(SyntaxKind.ImportEqualsDeclaration)
export interface ImportEqualsDeclaration extends DeclarationStatement {
name: Identifier;
// 'EntityName' for an internal module reference, 'ExternalModuleReference' for an external
// module reference.
moduleReference: EntityName | ExternalModuleReference;
moduleReference: ModuleReference;
}
// @kind(SyntaxKind.ExternalModuleReference)
@@ -1354,6 +1436,8 @@ namespace ts {
moduleSpecifier: Expression;
}
export type NamedImportBindings = NamespaceImport | NamedImports;
// In case of:
// import d from "mod" => name = d, namedBinding = undefined
// import * as ns from "mod" => name = undefined, namedBinding: NamespaceImport = { name: ns }
@@ -1363,7 +1447,7 @@ namespace ts {
// @kind(SyntaxKind.ImportClause)
export interface ImportClause extends Declaration {
name?: Identifier; // Default binding
namedBindings?: NamespaceImport | NamedImports;
namedBindings?: NamedImportBindings;
}
// @kind(SyntaxKind.NamespaceImport)
@@ -1702,6 +1786,8 @@ namespace ts {
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
/* @internal */ patternAmbientModules?: PatternAmbientModule[];
// The synthesized identifier for an imported external helpers module.
/* @internal */ externalHelpersModuleName?: Identifier;
}
export interface ScriptReferenceHost {
@@ -1889,6 +1975,7 @@ namespace ts {
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -2019,12 +2106,13 @@ namespace ts {
// function that can be reached at runtime (e.g. a `class`
// declaration or a `var` declaration for the static side
// of a type, such as the global `Promise` type in lib.d.ts).
VoidType, // The TypeReferenceNode resolves to a Void-like type.
VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
NumberLikeType, // The TypeReferenceNode resolves to a Number-like type.
StringLikeType, // The TypeReferenceNode resolves to a String-like type.
BooleanType, // The TypeReferenceNode resolves to a Boolean-like type.
ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type.
ESSymbolType, // The TypeReferenceNode resolves to the ESSymbol type.
Promise, // The TypeReferenceNode resolved to the global Promise constructor symbol.
TypeWithCallSignature, // The TypeReferenceNode resolves to a Function type or a type
// with call signatures.
ObjectType, // The TypeReferenceNode resolves to any other type.
@@ -2033,7 +2121,7 @@ namespace ts {
/* @internal */
export interface EmitResolver {
hasGlobalName(name: string): boolean;
getReferencedExportContainer(node: Identifier): SourceFile | ModuleDeclaration | EnumDeclaration;
getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration;
getReferencedImportDeclaration(node: Identifier): Declaration;
getReferencedDeclarationWithCollidingName(node: Identifier): Declaration;
isDeclarationWithCollidingName(node: Declaration): boolean;
@@ -2053,7 +2141,7 @@ namespace ts {
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
@@ -2228,6 +2316,8 @@ namespace ts {
BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body.
NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop
AssignmentsMarked = 0x00400000, // Parameter assignments have been marked
ClassWithConstructorReference = 0x00800000, // Class that contains a binding to its constructor inside of the class body.
ConstructorReferenceInClass = 0x01000000, // Binding to a class constructor inside of the class's body.
}
/* @internal */
@@ -2596,6 +2686,7 @@ namespace ts {
experimentalDecorators?: boolean;
forceConsistentCasingInFileNames?: boolean;
/*@internal*/help?: boolean;
importHelpers?: boolean;
/*@internal*/init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
@@ -2983,8 +3074,117 @@ namespace ts {
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getEnvironmentVariable?(name: string): string;
}
/* @internal */
export const enum TransformFlags {
None = 0,
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
TypeScript = 1 << 0,
ContainsTypeScript = 1 << 1,
Jsx = 1 << 2,
ContainsJsx = 1 << 3,
ES7 = 1 << 4,
ContainsES7 = 1 << 5,
ES6 = 1 << 6,
ContainsES6 = 1 << 7,
DestructuringAssignment = 1 << 8,
Generator = 1 << 9,
ContainsGenerator = 1 << 10,
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
ContainsDecorators = 1 << 11,
ContainsPropertyInitializer = 1 << 12,
ContainsLexicalThis = 1 << 13,
ContainsCapturedLexicalThis = 1 << 14,
ContainsLexicalThisInComputedPropertyName = 1 << 15,
ContainsDefaultValueAssignments = 1 << 16,
ContainsParameterPropertyAssignments = 1 << 17,
ContainsSpreadElementExpression = 1 << 18,
ContainsComputedPropertyName = 1 << 19,
ContainsBlockScopedBinding = 1 << 20,
ContainsBindingPattern = 1 << 21,
ContainsYield = 1 << 22,
ContainsHoistedDeclarationOrCompletion = 1 << 23,
HasComputedFlags = 1 << 29, // Transform flags have been computed.
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
AssertTypeScript = TypeScript | ContainsTypeScript,
AssertJsx = Jsx | ContainsJsx,
AssertES7 = ES7 | ContainsES7,
AssertES6 = ES6 | ContainsES6,
AssertGenerator = Generator | ContainsGenerator,
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
NodeExcludes = TypeScript | Jsx | ES7 | ES6 | DestructuringAssignment | Generator | HasComputedFlags,
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName,
ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
TypeExcludes = ~ContainsTypeScript,
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadElementExpression,
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern,
ParameterExcludes = NodeExcludes | ContainsBindingPattern,
// Masks
// - Additional bitmasks
TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators,
ES6FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments,
}
/* @internal */
export const enum NodeEmitFlags {
EmitEmitHelpers = 1 << 0, // Any emit helpers should be written to this node.
EmitExportStar = 1 << 1, // The export * helper should be written to this node.
EmitSuperHelper = 1 << 2, // Emit the basic _super helper for async methods.
EmitAdvancedSuperHelper = 1 << 3, // Emit the advanced _super helper for async methods.
UMDDefine = 1 << 4, // This node should be replaced with the UMD define helper.
SingleLine = 1 << 5, // The contents of this node should be emitted on a single line.
AdviseOnEmitNode = 1 << 6, // The printer should invoke the onEmitNode callback when printing this node.
NoSubstitution = 1 << 7, // Disables further substitution of an expression.
CapturesThis = 1 << 8, // The function captures a lexical `this`
NoLeadingSourceMap = 1 << 9, // Do not emit a leading source map location for this node.
NoTrailingSourceMap = 1 << 10, // Do not emit a trailing source map location for this node.
NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node.
NoNestedSourceMaps = 1 << 11, // Do not emit source map locations for children of this node.
NoTokenLeadingSourceMaps = 1 << 12, // Do not emit leading source map location for token nodes.
NoTokenTrailingSourceMaps = 1 << 13, // Do not emit trailing source map location for token nodes.
NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node.
NoLeadingComments = 1 << 14, // Do not emit leading comments for this node.
NoTrailingComments = 1 << 15, // Do not emit trailing comments for this node.
NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node.
NoNestedComments = 1 << 16,
ExportName = 1 << 17, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
LocalName = 1 << 18, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
Indented = 1 << 19, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
NoIndentation = 1 << 20, // Do not indent the node.
AsyncFunctionBody = 1 << 21,
ReuseTempVariableScope = 1 << 22, // Reuse the existing temp variable scope during emit.
CustomPrologue = 1 << 23, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
}
/** Additional context provided to `visitEachChild` */
/* @internal */
export interface LexicalEnvironment {
/** Starts a new lexical environment. */
startLexicalEnvironment(): void;
/** Ends a lexical environment, returning any declarations. */
endLexicalEnvironment(): Statement[];
}
export interface TextSpan {
start: number;
length: number;
+1629 -335
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -154,7 +154,7 @@ class CompilerBaselineRunner extends RunnerBase {
if (options.sourceMap || options.inlineSourceMap) {
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => {
const record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
if ((options.noEmitOnError && result.errors.length !== 0) || record === undefined) {
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
/* tslint:disable:no-null-keyword */
return null;
+236 -112
View File
@@ -206,6 +206,24 @@ namespace FourSlash {
private inputFiles = ts.createMap<string>(); // Map between inputFile's fileName and its content for easily looking up when resolving references
private static getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
let result = "";
ts.forEach(displayParts, part => {
if (result) {
result += ",\n ";
}
else {
result = "[\n ";
}
result += JSON.stringify(part);
});
if (result) {
result += "\n]";
}
return result;
}
// Add input file which has matched file name with the given reference-file path.
// This is necessary when resolveReference flag is specified
private addMatchedInputFile(referenceFilePath: string, extensions: string[]) {
@@ -245,22 +263,31 @@ namespace FourSlash {
constructor(private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) {
// Create a new Services Adapter
this.cancellationToken = new TestCancellationToken();
const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
if (compilationOptions.typeRoots) {
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
}
let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
compilationOptions.skipDefaultLibCheck = true;
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = languageServiceAdapter.getLanguageService();
// Initialize the language service with all the scripts
let startResolveFileRef: FourSlashFile;
ts.forEach(testData.files, file => {
// Create map between fileName and its content for easily looking up when resolveReference flag is specified
this.inputFiles[file.fileName] = file.content;
if (ts.getBaseFileName(file.fileName).toLowerCase() === "tsconfig.json") {
const configJson = ts.parseConfigFileTextToJson(file.fileName, file.content);
assert.isTrue(configJson.config !== undefined);
// Extend our existing compiler options so that we can also support tsconfig only options
if (configJson.config.compilerOptions) {
const baseDirectory = ts.normalizePath(ts.getDirectoryPath(file.fileName));
const tsConfig = ts.convertCompilerOptionsFromJson(configJson.config.compilerOptions, baseDirectory, file.fileName);
if (!tsConfig.errors || !tsConfig.errors.length) {
compilationOptions = ts.extend(compilationOptions, tsConfig.options);
}
}
}
if (!startResolveFileRef && file.fileOptions[metadataOptionNames.resolveReference] === "true") {
startResolveFileRef = file;
}
@@ -270,6 +297,15 @@ namespace FourSlash {
}
});
if (compilationOptions.typeRoots) {
compilationOptions.typeRoots = compilationOptions.typeRoots.map(p => ts.getNormalizedAbsolutePath(p, this.basePath));
}
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = languageServiceAdapter.getLanguageService();
if (startResolveFileRef) {
// Add the entry-point file itself into the languageServiceShimHost
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content, /*isRootFile*/ true);
@@ -324,6 +360,7 @@ namespace FourSlash {
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false,
PlaceOpenBraceOnNewLineForFunctions: false,
@@ -507,6 +544,67 @@ namespace FourSlash {
}
}
public verifyGoToDefinitionIs(endMarker: string | string[]) {
this.verifyGoToDefinitionWorker(endMarker instanceof Array ? endMarker : [endMarker]);
}
public verifyGoToDefinition(arg0: any, endMarkerNames?: string | string[]) {
if (endMarkerNames) {
this.verifyGoToDefinitionPlain(arg0, endMarkerNames);
}
else if (arg0 instanceof Array) {
const pairs: [string | string[], string | string[]][] = arg0;
for (const [start, end] of pairs) {
this.verifyGoToDefinitionPlain(start, end);
}
}
else {
const obj: { [startMarkerName: string]: string | string[] } = arg0;
for (const startMarkerName in obj) {
if (ts.hasProperty(obj, startMarkerName)) {
this.verifyGoToDefinitionPlain(startMarkerName, obj[startMarkerName]);
}
}
}
}
private verifyGoToDefinitionPlain(startMarkerNames: string | string[], endMarkerNames: string | string[]) {
if (startMarkerNames instanceof Array) {
for (const start of startMarkerNames) {
this.verifyGoToDefinitionSingle(start, endMarkerNames);
}
}
else {
this.verifyGoToDefinitionSingle(startMarkerNames, endMarkerNames);
}
}
public verifyGoToDefinitionForMarkers(markerNames: string[]) {
for (const markerName of markerNames) {
this.verifyGoToDefinitionSingle(`${markerName}Reference`, `${markerName}Definition`);
}
}
private verifyGoToDefinitionSingle(startMarkerName: string, endMarkerNames: string | string[]) {
this.goToMarker(startMarkerName);
this.verifyGoToDefinitionWorker(endMarkerNames instanceof Array ? endMarkerNames : [endMarkerNames]);
}
private verifyGoToDefinitionWorker(endMarkers: string[]) {
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition) || [];
if (endMarkers.length !== definitions.length) {
this.raiseError(`goToDefinitions failed - expected to find ${endMarkers.length} definitions but got ${definitions.length}`);
}
for (let i = 0; i < endMarkers.length; i++) {
const marker = this.getMarkerByName(endMarkers[i]), definition = definitions[i];
if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) {
this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`);
}
}
}
public verifyGetEmitOutputForCurrentFile(expected: string): void {
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
if (emit.outputFiles.length !== 1) {
@@ -651,10 +749,10 @@ namespace FourSlash {
}
}
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
const completions = this.getCompletionListAtCaret();
if (completions) {
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind, spanIndex);
}
else {
this.raiseError(`No completions at position '${this.currentCaretPosition}' when looking for '${symbol}'.`);
@@ -670,25 +768,32 @@ namespace FourSlash {
* @param expectedText the text associated with the symbol
* @param expectedDocumentation the documentation text associated with the symbol
* @param expectedKind the kind of symbol (see ScriptElementKind)
* @param spanIndex the index of the range that the completion item's replacement text span should match
*/
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) {
public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string, spanIndex?: number) {
const that = this;
let replacementSpan: ts.TextSpan;
if (spanIndex !== undefined) {
replacementSpan = this.getTextSpanForRangeAtIndex(spanIndex);
}
function filterByTextOrDocumentation(entry: ts.CompletionEntry) {
const details = that.getCompletionEntryDetails(entry.name);
const documentation = ts.displayPartsToString(details.documentation);
const text = ts.displayPartsToString(details.displayParts);
if (expectedText && expectedDocumentation) {
return (documentation === expectedDocumentation && text === expectedText) ? true : false;
// If any of the expected values are undefined, assume that users don't
// care about them.
if (replacementSpan && !TestState.textSpansEqual(replacementSpan, entry.replacementSpan)) {
return false;
}
else if (expectedText && !expectedDocumentation) {
return text === expectedText ? true : false;
else if (expectedText && text !== expectedText) {
return false;
}
else if (expectedDocumentation && !expectedText) {
return documentation === expectedDocumentation ? true : false;
else if (expectedDocumentation && documentation !== expectedDocumentation) {
return false;
}
// Because expectedText and expectedDocumentation are undefined, we assume that
// users don"t care to compare them so we will treat that entry as if the entry has matching text and documentation
// and keep it in the list of filtered entry.
return true;
}
@@ -712,6 +817,10 @@ namespace FourSlash {
if (expectedKind) {
error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + ".";
}
if (replacementSpan) {
const spanText = filterCompletions[0].replacementSpan ? stringify(filterCompletions[0].replacementSpan) : undefined;
error += "Expected replacement span: " + stringify(replacementSpan) + " to equal: " + spanText + ".";
}
this.raiseError(error);
}
}
@@ -777,6 +886,20 @@ namespace FourSlash {
ts.forEachProperty(this.rangesByText(), ranges => this.verifyRangesReferenceEachOther(ranges));
}
public verifyDisplayPartsOfReferencedSymbol(expected: ts.SymbolDisplayPart[]) {
const referencedSymbols = this.findReferencesAtCaret();
if (referencedSymbols.length === 0) {
this.raiseError("No referenced symbols found at current caret position");
}
else if (referencedSymbols.length > 1) {
this.raiseError("More than one referenced symbol found");
}
assert.equal(TestState.getDisplayPartsJson(referencedSymbols[0].definition.displayParts),
TestState.getDisplayPartsJson(expected), this.messageAtLastKnownMarker("referenced symbol definition display parts"));
}
private verifyReferencesWorker(references: ts.ReferenceEntry[], fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) {
for (let i = 0; i < references.length; i++) {
const reference = references[i];
@@ -811,6 +934,10 @@ namespace FourSlash {
return this.languageService.getReferencesAtPosition(this.activeFile.fileName, this.currentCaretPosition);
}
private findReferencesAtCaret() {
return this.languageService.findReferences(this.activeFile.fileName, this.currentCaretPosition);
}
public getSyntacticDiagnostics(expected: string) {
const diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
this.testDiagnostics(expected, diagnostics);
@@ -856,30 +983,12 @@ namespace FourSlash {
displayParts: ts.SymbolDisplayPart[],
documentation: ts.SymbolDisplayPart[]) {
function getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) {
let result = "";
ts.forEach(displayParts, part => {
if (result) {
result += ",\n ";
}
else {
result = "[\n ";
}
result += JSON.stringify(part);
});
if (result) {
result += "\n]";
}
return result;
}
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind"));
assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers"));
assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan"));
assert.equal(getDisplayPartsJson(actualQuickInfo.displayParts), getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
assert.equal(getDisplayPartsJson(actualQuickInfo.documentation), getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
}
public verifyRenameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]) {
@@ -1185,6 +1294,22 @@ namespace FourSlash {
});
}
public baselineQuickInfo() {
let baselineFile = this.testData.globalOptions[metadataOptionNames.baselineFile];
if (!baselineFile) {
baselineFile = ts.getBaseFileName(this.activeFile.fileName).replace(".ts", ".baseline");
}
Harness.Baseline.runBaseline(
baselineFile,
() => stringify(
this.testData.markers.map(marker => ({
marker,
quickInfo: this.languageService.getQuickInfoAtPosition(marker.fileName, marker.position)
}))
));
}
public printBreakpointLocation(pos: number) {
Harness.IO.log("\n**Pos: " + pos + " " + this.spanInfoToString(pos, this.getBreakpointStatementLocation(pos), " "));
}
@@ -1543,25 +1668,10 @@ namespace FourSlash {
this.goToPosition(len);
}
public goToDefinition(definitionIndex: number) {
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
this.raiseError("goToDefinition failed - expected to at least one definition location but got 0");
}
if (definitionIndex >= definitions.length) {
this.raiseError(`goToDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`);
}
const definition = definitions[definitionIndex];
this.openFile(definition.fileName);
this.currentCaretPosition = definition.textSpan.start;
}
public goToTypeDefinition(definitionIndex: number) {
const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
this.raiseError("goToTypeDefinition failed - expected to at least one definition location but got 0");
this.raiseError("goToTypeDefinition failed - expected to find at least one definition location but got 0");
}
if (definitionIndex >= definitions.length) {
@@ -1573,28 +1683,6 @@ namespace FourSlash {
this.currentCaretPosition = definition.textSpan.start;
}
public verifyDefinitionLocationExists(negative: boolean) {
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
const foundDefinitions = definitions && definitions.length;
if (foundDefinitions && negative) {
this.raiseError(`goToDefinition - expected to 0 definition locations but got ${definitions.length}`);
}
else if (!foundDefinitions && !negative) {
this.raiseError("goToDefinition - expected to at least one definition location but got 0");
}
}
public verifyDefinitionsCount(negative: boolean, expectedCount: number) {
const assertFn = negative ? assert.notEqual : assert.equal;
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
const actualCount = definitions && definitions.length || 0;
assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Definitions Count"));
}
public verifyTypeDefinitionsCount(negative: boolean, expectedCount: number) {
const assertFn = negative ? assert.notEqual : assert.equal;
@@ -1604,18 +1692,12 @@ namespace FourSlash {
assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Type definitions Count"));
}
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
public verifyGoToDefinitionName(expectedName: string, expectedContainerName: string) {
const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
const actualDefinitionName = definitions && definitions.length ? definitions[0].name : "";
const actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : "";
if (negative) {
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
}
else {
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
}
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
}
public getMarkers(): Marker[] {
@@ -1623,6 +1705,10 @@ namespace FourSlash {
return this.testData.markers.slice(0);
}
public getMarkerNames(): string[] {
return Object.keys(this.testData.markerPositions);
}
public getRanges(): Range[] {
return this.testData.ranges;
}
@@ -1631,8 +1717,7 @@ namespace FourSlash {
const result = ts.createMap<Range[]>();
for (const range of this.getRanges()) {
const text = this.rangeText(range);
const ranges = result[text] || (result[text] = []);
ranges.push(range);
ts.multiMapAdd(result, text, range);
}
return result;
}
@@ -2149,7 +2234,7 @@ namespace FourSlash {
return text.substring(startPos, endPos);
}
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string) {
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.name === name) {
@@ -2168,6 +2253,11 @@ namespace FourSlash {
assert.equal(item.kind, kind, this.assertionMessageAtLastKnownMarker("completion item kind for " + name));
}
if (spanIndex !== undefined) {
const span = this.getTextSpanForRangeAtIndex(spanIndex);
assert.isTrue(TestState.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + name));
}
return;
}
}
@@ -2224,6 +2314,17 @@ namespace FourSlash {
return `line ${(pos.line + 1)}, col ${pos.character}`;
}
private getTextSpanForRangeAtIndex(index: number): ts.TextSpan {
const ranges = this.getRanges();
if (ranges && ranges.length > index) {
const range = ranges[index];
return { start: range.start, length: range.end - range.start };
}
else {
this.raiseError("Supplied span index: " + index + " does not exist in range list of size: " + (ranges ? 0 : ranges.length));
}
}
public getMarkerByName(markerName: string) {
const markerPos = this.testData.markerPositions[markerName];
if (markerPos === undefined) {
@@ -2247,6 +2348,10 @@ namespace FourSlash {
public resetCancelled(): void {
this.cancellationToken.resetCancelled();
}
private static textSpansEqual(a: ts.TextSpan, b: ts.TextSpan) {
return a && b && a.start === b.start && a.length === b.length;
}
}
export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) {
@@ -2255,12 +2360,16 @@ namespace FourSlash {
}
export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): void {
// Give file paths an absolute path for the virtual file system
const absoluteBasePath = ts.combinePaths(Harness.virtualFileSystemRoot, basePath);
const absoluteFileName = ts.combinePaths(Harness.virtualFileSystemRoot, fileName);
// Parse out the files and their metadata
const testData = parseTestData(basePath, content, fileName);
const state = new TestState(basePath, testType, testData);
const testData = parseTestData(absoluteBasePath, content, absoluteFileName);
const state = new TestState(absoluteBasePath, testType, testData);
const output = ts.transpileModule(content, { reportDiagnostics: true });
if (output.diagnostics.length > 0) {
throw new Error(`Syntax error in ${basePath}: ${output.diagnostics[0].messageText}`);
throw new Error(`Syntax error in ${absoluteBasePath}: ${output.diagnostics[0].messageText}`);
}
runCode(output.outputText, state);
}
@@ -2725,6 +2834,10 @@ namespace FourSlashInterface {
return this.state.getMarkers();
}
public markerNames(): string[] {
return this.state.getMarkerNames();
}
public marker(name?: string): FourSlash.Marker {
return this.state.getMarkerByName(name);
}
@@ -2760,10 +2873,6 @@ namespace FourSlashInterface {
this.state.goToEOF();
}
public definition(definitionIndex = 0) {
this.state.goToDefinition(definitionIndex);
}
public type(definitionIndex = 0) {
this.state.goToTypeDefinition(definitionIndex);
}
@@ -2813,12 +2922,12 @@ namespace FourSlashInterface {
// Verifies the completion list contains the specified symbol. The
// completion list is brought up if necessary
public completionListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
public completionListContains(symbol: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
if (this.negative) {
this.state.verifyCompletionListDoesNotContain(symbol, text, documentation, kind);
this.state.verifyCompletionListDoesNotContain(symbol, text, documentation, kind, spanIndex);
}
else {
this.state.verifyCompletionListContains(symbol, text, documentation, kind);
this.state.verifyCompletionListContains(symbol, text, documentation, kind, spanIndex);
}
}
@@ -2868,22 +2977,10 @@ namespace FourSlashInterface {
this.state.verifyQuickInfoExists(this.negative);
}
public definitionCountIs(expectedCount: number) {
this.state.verifyDefinitionsCount(this.negative, expectedCount);
}
public typeDefinitionCountIs(expectedCount: number) {
this.state.verifyTypeDefinitionsCount(this.negative, expectedCount);
}
public definitionLocationExists() {
this.state.verifyDefinitionLocationExists(this.negative);
}
public verifyDefinitionsName(name: string, containerName: string) {
this.state.verifyDefinitionsName(this.negative, name, containerName);
}
public isValidBraceCompletionAtPosition(openingBrace: string) {
this.state.verifyBraceCompletionAtPosition(this.negative, openingBrace);
}
@@ -2927,6 +3024,25 @@ namespace FourSlashInterface {
this.state.verifyCurrentFileContent(text);
}
public goToDefinitionIs(endMarkers: string | string[]) {
this.state.verifyGoToDefinitionIs(endMarkers);
}
public goToDefinition(startMarkerName: string | string[], endMarkerName: string | string[]): void;
public goToDefinition(startsAndEnds: [string | string[], string | string[]][]): void;
public goToDefinition(startsAndEnds: { [startMarkerName: string]: string | string[] }): void;
public goToDefinition(arg0: any, endMarkerName?: string | string[]) {
this.state.verifyGoToDefinition(arg0, endMarkerName);
}
public goToDefinitionForMarkers(...markerNames: string[]) {
this.state.verifyGoToDefinitionForMarkers(markerNames);
}
public goToDefinitionName(name: string, containerName: string) {
this.state.verifyGoToDefinitionName(name, containerName);
}
public verifyGetEmitOutputForCurrentFile(expected: string): void {
this.state.verifyGetEmitOutputForCurrentFile(expected);
}
@@ -2947,6 +3063,10 @@ namespace FourSlashInterface {
this.state.verifyRangesReferenceEachOther(ranges);
}
public findReferencesDefinitionDisplayPartsAtCaretAre(expected: ts.SymbolDisplayPart[]) {
this.state.verifyDisplayPartsOfReferencedSymbol(expected);
}
public rangesWithSameTextReferenceEachOther() {
this.state.verifyRangesWithSameTextReferenceEachOther();
}
@@ -2999,6 +3119,10 @@ namespace FourSlashInterface {
this.state.baselineGetEmitOutput();
}
public baselineQuickInfo() {
this.state.baselineQuickInfo();
}
public nameOrDottedNameSpanTextIs(text: string) {
this.state.verifyCurrentNameOrDottedNameSpanText(text);
}
+101 -13
View File
@@ -416,6 +416,60 @@ namespace Utils {
throw new Error("Could not find child in parent");
}
const maxHarnessFrames = 1;
export function filterStack(error: Error, stackTraceLimit: number = Infinity) {
const stack = <string>(<any>error).stack;
if (stack) {
const lines = stack.split(/\r\n?|\n/g);
const filtered: string[] = [];
let frameCount = 0;
let harnessFrameCount = 0;
for (let line of lines) {
if (isStackFrame(line)) {
if (frameCount >= stackTraceLimit
|| isMocha(line)
|| isNode(line)) {
continue;
}
if (isHarness(line)) {
if (harnessFrameCount >= maxHarnessFrames) {
continue;
}
harnessFrameCount++;
}
line = line.replace(/\bfile:\/\/\/(.*?)(?=(:\d+)*($|\)))/, (_, path) => ts.sys.resolvePath(path));
frameCount++;
}
filtered.push(line);
}
(<any>error).stack = filtered.join(Harness.IO.newLine());
}
return error;
}
function isStackFrame(line: string) {
return /^\s+at\s/.test(line);
}
function isMocha(line: string) {
return /[\\/](node_modules|components)[\\/]mocha(js)?[\\/]|[\\/]mocha\.js/.test(line);
}
function isNode(line: string) {
return /\((timers|events|node|module)\.js:/.test(line);
}
function isHarness(line: string) {
return /[\\/]src[\\/]harness[\\/]|[\\/]run\.js/.test(line);
}
}
namespace Harness.Path {
@@ -452,12 +506,17 @@ namespace Harness {
getExecutingFilePath(): string;
exit(exitCode?: number): void;
readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]): string[];
tryEnableSourceMapsForHost?(): void;
getEnvironmentVariable?(name: string): string;
}
export var IO: IO;
// harness always uses one kind of new line
const harnessNewLine = "\r\n";
// Root for file paths that are stored in a virtual file system
export const virtualFileSystemRoot = "/";
namespace IOImpl {
declare class Enumerator {
public atEnd(): boolean;
@@ -490,6 +549,7 @@ namespace Harness {
export const directoryExists: typeof IO.directoryExists = fso.FolderExists;
export const fileExists: typeof IO.fileExists = fso.FileExists;
export const log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export const getEnvironmentVariable: typeof IO.getEnvironmentVariable = name => ts.sys.getEnvironmentVariable(name);
export const readDirectory: typeof IO.readDirectory = (path, extension, exclude, include) => ts.sys.readDirectory(path, extension, exclude, include);
export function createDirectory(path: string) {
@@ -559,7 +619,13 @@ namespace Harness {
export const writeFile: typeof IO.writeFile = (path, content) => ts.sys.writeFile(path, content);
export const fileExists: typeof IO.fileExists = fs.existsSync;
export const log: typeof IO.log = s => console.log(s);
export const getEnvironmentVariable: typeof IO.getEnvironmentVariable = name => ts.sys.getEnvironmentVariable(name);
export function tryEnableSourceMapsForHost() {
if (ts.sys.tryEnableSourceMapsForHost) {
ts.sys.tryEnableSourceMapsForHost();
}
}
export const readDirectory: typeof IO.readDirectory = (path, extension, exclude, include) => ts.sys.readDirectory(path, extension, exclude, include);
export function createDirectory(path: string) {
@@ -710,7 +776,16 @@ namespace Harness {
return dirPath;
}
export let directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export const resolvePath = (path: string) => directoryName(path);
export function resolvePath(path: string) {
const response = Http.getFileFromServerSync(serverRoot + path + "?resolve=true");
if (response.status === 200) {
return response.responseText;
}
else {
return undefined;
}
}
export function fileExists(path: string): boolean {
const response = Http.getFileFromServerSync(serverRoot + path);
@@ -784,7 +859,9 @@ namespace Harness {
namespace Harness {
export const libFolder = "built/local/";
const tcServicesFileName = ts.combinePaths(libFolder, Utils.getExecutionEnvironment() === Utils.ExecutionEnvironment.Browser ? "typescriptServicesInBrowserTest.js" : "typescriptServices.js");
export const tcServicesFile = IO.readFile(tcServicesFileName);
export const tcServicesFile = IO.readFile(tcServicesFileName) + (Utils.getExecutionEnvironment() !== Utils.ExecutionEnvironment.Browser
? IO.newLine() + `//# sourceURL=${IO.resolvePath(tcServicesFileName)}`
: "");
export interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
@@ -1370,23 +1447,31 @@ namespace Harness {
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
let typesError: Error, symbolsError: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
typesError = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
symbolsError = e;
}
if (e1 || e2) {
throw e1 || e2;
if (typesError && symbolsError) {
throw new Error(typesError.message + ts.sys.newLine + symbolsError.message);
}
if (typesError) {
throw typesError;
}
if (symbolsError) {
throw symbolsError;
}
return;
@@ -1396,7 +1481,12 @@ namespace Harness {
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?/, fullExtension), () => fullBaseLine, opts);
// When calling this function from rwc-runner, the baselinePath will have no extension.
// As rwc test- file is stored in json which ".json" will get stripped off.
// When calling this function from compiler-runner, the baselinePath will then has either ".ts" or ".tsx" extension
const outputFileName = ts.endsWith(baselinePath, ".ts") || ts.endsWith(baselinePath, ".tsx") ?
baselinePath.replace(/\.tsx?/, fullExtension) : baselinePath.concat(fullExtension);
Harness.Baseline.runBaseline(outputFileName, () => fullBaseLine, opts);
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
@@ -1468,7 +1558,7 @@ namespace Harness {
}
Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ".js.map"), () => {
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
if ((options.noEmitOnError && result.errors.length !== 0) || result.sourceMaps.length === 0) {
// We need to return null here or the runBaseLine will actually create a empty file.
// Baselining isn't required here because there is no output.
/* tslint:disable:no-null-keyword */
@@ -1635,7 +1725,7 @@ namespace Harness {
}
public getSourceMapRecord() {
if (this.sourceMapData) {
if (this.sourceMapData && this.sourceMapData.length > 0) {
return Harness.SourceMapRecorder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
}
}
@@ -1772,7 +1862,7 @@ namespace Harness {
tsConfig.options.configFilePath = data.name;
// delete entry from the list
testUnitData.splice(i, 1);
ts.orderedRemoveItemAt(testUnitData, i);
break;
}
@@ -1892,9 +1982,7 @@ namespace Harness {
}
export function runBaseline(relativeFileName: string, generateContent: () => string, opts?: BaselineOptions): void {
const actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
const actual = generateActual(generateContent);
const comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName);
+36 -8
View File
@@ -123,7 +123,7 @@ namespace Harness.LanguageService {
}
export class LanguageServiceAdapterHost {
protected fileNameToScript = ts.createMap<ScriptInfo>();
protected virtualFileSystem: Utils.VirtualFileSystem = new Utils.VirtualFileSystem(virtualFileSystemRoot, /*useCaseSensitiveFilenames*/false);
constructor(protected cancellationToken = DefaultHostCancellationToken.Instance,
protected settings = ts.getDefaultCompilerOptions()) {
@@ -135,22 +135,24 @@ namespace Harness.LanguageService {
public getFilenames(): string[] {
const fileNames: string[] = [];
ts.forEachProperty(this.fileNameToScript, (scriptInfo) => {
for (const virtualEntry of this.virtualFileSystem.getAllFileEntries()){
const scriptInfo = virtualEntry.content;
if (scriptInfo.isRootFile) {
// only include root files here
// usually it means that we won't include lib.d.ts in the list of root files so it won't mess the computation of compilation root dir.
fileNames.push(scriptInfo.fileName);
}
});
}
return fileNames;
}
public getScriptInfo(fileName: string): ScriptInfo {
return this.fileNameToScript[fileName];
const fileEntry = this.virtualFileSystem.traversePath(fileName);
return fileEntry && fileEntry.isFile() ? (<Utils.VirtualFile>fileEntry).content : undefined;
}
public addScript(fileName: string, content: string, isRootFile: boolean): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content, isRootFile);
this.virtualFileSystem.addFile(fileName, new ScriptInfo(fileName, content, isRootFile));
}
public editScript(fileName: string, start: number, end: number, newText: string) {
@@ -171,7 +173,7 @@ namespace Harness.LanguageService {
* @param col 0 based index
*/
public positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter {
const script: ScriptInfo = this.fileNameToScript[fileName];
const script: ScriptInfo = this.getScriptInfo(fileName);
assert.isOk(script);
return ts.computeLineAndCharacterOfPosition(script.getLineMap(), position);
@@ -182,8 +184,14 @@ namespace Harness.LanguageService {
class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost {
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getDirectories(path: string): string[] { return []; }
getCurrentDirectory(): string { return ""; }
getDirectories(path: string): string[] {
const dir = this.virtualFileSystem.traversePath(path);
if (dir && dir.isDirectory()) {
return ts.map((<Utils.VirtualDirectory>dir).getDirectories(), (d) => ts.combinePaths(path, d.name));
}
return [];
}
getCurrentDirectory(): string { return virtualFileSystemRoot; }
getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; }
getScriptFileNames(): string[] { return this.getFilenames(); }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
@@ -196,6 +204,22 @@ namespace Harness.LanguageService {
return script ? script.version.toString() : undefined;
}
fileExists(fileName: string): boolean {
const script = this.getScriptSnapshot(fileName);
return script !== undefined;
}
readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[] {
return ts.matchFiles(path, extensions, exclude, include,
/*useCaseSensitiveFileNames*/false,
this.getCurrentDirectory(),
(p) => this.virtualFileSystem.getAccessibleFileSystemEntries(p));
}
readFile(path: string, encoding?: string): string {
const snapshot = this.getScriptSnapshot(path);
return snapshot.getText(0, snapshot.getLength());
}
log(s: string): void { }
trace(s: string): void { }
error(s: string): void { }
@@ -617,6 +641,10 @@ namespace Harness.LanguageService {
return [];
}
getEnvironmentVariable(name: string): string {
return ts.sys.getEnvironmentVariable(name);
}
readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]): string[] {
throw new Error("Not implemented Yet.");
}
+8 -11
View File
@@ -473,7 +473,6 @@ class ProjectRunner extends RunnerBase {
}
});
it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (testCase.baselineCheck) {
const errs: Error[] = [];
@@ -500,18 +499,16 @@ class ProjectRunner extends RunnerBase {
}
});
it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline(getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
return Harness.SourceMapRecorder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
}
});
// it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
// if (compilerResult.sourceMapData) {
// Harness.Baseline.runBaseline(getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
// return Harness.SourceMapRecorder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
// ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
// });
// }
// });
// Verify that all the generated .d.ts files compile
it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
const dTsCompileResult = compileCompileDTsFiles(compilerResult);
+8
View File
@@ -82,6 +82,7 @@ interface TestConfig {
light?: boolean;
taskConfigsFolder?: string;
workerCount?: number;
stackTraceLimit?: number | "full";
tasks?: TaskSet[];
test?: string[];
runUnitTests?: boolean;
@@ -116,6 +117,13 @@ if (testConfigContent !== "") {
}
}
if (testConfig.stackTraceLimit === "full") {
(<any>Error).stackTraceLimit = Infinity;
}
else if ((+testConfig.stackTraceLimit | 0) > 0) {
(<any>Error).stackTraceLimit = testConfig.stackTraceLimit;
}
if (testConfig.test && testConfig.test.length > 0) {
for (const option of testConfig.test) {
if (!option) {
+2 -1
View File
@@ -223,7 +223,8 @@ namespace RWC {
});
it("has the expected types", () => {
Harness.Compiler.doTypeAndSymbolBaseline(`${baseName}.types`, compilerResult, inputFiles
// We don't need to pass the extension here because "doTypeAndSymbolBaseline" will append appropriate extension of ".types" or ".symbols"
Harness.Compiler.doTypeAndSymbolBaseline(baseName, compilerResult, inputFiles
.concat(otherFiles)
.filter(file => !!compilerResult.program.getSourceFile(file.unitName))
.filter(e => !Harness.isDefaultLibraryFile(e.unitName)), baselineOpts);
+1 -1
View File
@@ -29,7 +29,7 @@ class TypeWriterWalker {
}
private visitNode(node: ts.Node): void {
if (ts.isExpression(node) || node.kind === ts.SyntaxKind.Identifier) {
if (ts.isPartOfExpression(node) || node.kind === ts.SyntaxKind.Identifier) {
this.logTypeAndSymbol(node);
}
@@ -47,6 +47,7 @@ namespace ts {
return "";
},
getDirectories: (path: string) => [],
getEnvironmentVariable: (name: string) => "",
readDirectory: (path: string, extension?: string[], exclude?: string[], include?: string[]): string[] => {
throw new Error("NYI");
},
@@ -403,6 +403,7 @@ namespace ts {
{
compilerOptions: <CompilerOptions>{
allowJs: true,
maxNodeModuleJsDepth: 2,
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
@@ -429,6 +430,7 @@ namespace ts {
{
compilerOptions: <CompilerOptions>{
allowJs: false,
maxNodeModuleJsDepth: 2,
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
@@ -450,7 +452,8 @@ namespace ts {
{
compilerOptions:
{
allowJs: true
allowJs: true,
maxNodeModuleJsDepth: 2
},
errors: [{
file: undefined,
@@ -469,7 +472,8 @@ namespace ts {
{
compilerOptions:
{
allowJs: true
allowJs: true,
maxNodeModuleJsDepth: 2
},
errors: <Diagnostic[]>[]
}
File diff suppressed because it is too large Load Diff
@@ -1,79 +0,0 @@
class a {
constructor ( n : number ) ;
constructor ( s : string ) ;
constructor ( ns : any ) {
}
public pgF ( ) { } ;
public pv ;
public get d ( ) {
return 30 ;
}
public set d ( ) {
}
public static get p2 ( ) {
return { x : 30 , y : 40 } ;
}
private static d2 ( ) {
}
private static get p3 ( ) {
return "string" ;
}
private pv3 ;
private foo ( n : number ) : string ;
private foo ( s : string ) : string ;
private foo ( ns : any ) {
return ns.toString ( ) ;
}
}
class b extends a {
}
class m1b {
}
interface m1ib {
}
class c extends m1b {
}
class ib2 implements m1ib {
}
declare class aAmbient {
constructor ( n : number ) ;
constructor ( s : string ) ;
public pgF ( ) : void ;
public pv ;
public d : number ;
static p2 : { x : number ; y : number ; } ;
static d2 ( ) ;
static p3 ;
private pv3 ;
private foo ( s ) ;
}
class d {
private foo ( n : number ) : string ;
private foo ( ns : any ) {
return ns.toString ( ) ;
}
private foo ( s : string ) : string ;
}
class e {
private foo ( ns : any ) {
return ns.toString ( ) ;
}
private foo ( s : string ) : string ;
private foo ( n : number ) : string ;
}
@@ -1,79 +0,0 @@
class a {
constructor(n: number);
constructor(s: string);
constructor(ns: any) {
}
public pgF() { };
public pv;
public get d() {
return 30;
}
public set d() {
}
public static get p2() {
return { x: 30, y: 40 };
}
private static d2() {
}
private static get p3() {
return "string";
}
private pv3;
private foo(n: number): string;
private foo(s: string): string;
private foo(ns: any) {
return ns.toString();
}
}
class b extends a {
}
class m1b {
}
interface m1ib {
}
class c extends m1b {
}
class ib2 implements m1ib {
}
declare class aAmbient {
constructor(n: number);
constructor(s: string);
public pgF(): void;
public pv;
public d: number;
static p2: { x: number; y: number; };
static d2();
static p3;
private pv3;
private foo(s);
}
class d {
private foo(n: number): string;
private foo(ns: any) {
return ns.toString();
}
private foo(s: string): string;
}
class e {
private foo(ns: any) {
return ns.toString();
}
private foo(s: string): string;
private foo(n: number): string;
}
@@ -1,4 +0,0 @@
class foo {
constructor (n?: number, m? = 5, o?: string = "") { }
x:number = 1?2:3;
}
@@ -1,4 +0,0 @@
class foo {
constructor(n?: number, m? = 5, o?: string = "") { }
x: number = 1 ? 2 : 3;
}
@@ -1,3 +0,0 @@
$ ( document ) . ready ( function ( ) {
alert ( 'i am ready' ) ;
} );
@@ -1,3 +0,0 @@
$(document).ready(function() {
alert('i am ready');
});
@@ -1,10 +0,0 @@
function foo ( x : { } ) { }
foo ( { } ) ;
interface bar {
x : { } ;
y : ( ) => { } ;
}
@@ -1,10 +0,0 @@
function foo(x: {}) { }
foo({});
interface bar {
x: {};
y: () => {};
}
@@ -1,112 +0,0 @@
// valid
( ) => 1 ;
( arg ) => 2 ;
arg => 2 ;
( arg = 1 ) => 3 ;
( arg ? ) => 4 ;
( arg : number ) => 5 ;
( arg : number = 0 ) => 6 ;
( arg ? : number ) => 7 ;
( ... arg : number [ ] ) => 8 ;
( arg1 , arg2 ) => 12 ;
( arg1 = 1 , arg2 =3 ) => 13 ;
( arg1 ? , arg2 ? ) => 14 ;
( arg1 : number , arg2 : number ) => 15 ;
( arg1 : number = 0 , arg2 : number = 1 ) => 16 ;
( arg1 ? : number , arg2 ? : number ) => 17 ;
( arg1 , ... arg2 : number [ ] ) => 18 ;
( arg1 , arg2 ? : number ) => 19 ;
// in paren
( ( ) => 21 ) ;
( ( arg ) => 22 ) ;
( ( arg = 1 ) => 23 ) ;
( ( arg ? ) => 24 ) ;
( ( arg : number ) => 25 ) ;
( ( arg : number = 0 ) => 26 ) ;
( ( arg ? : number ) => 27 ) ;
( ( ... arg : number [ ] ) => 28 ) ;
// in multiple paren
( ( ( ( ( arg ) => { return 32 ; } ) ) ) ) ;
// in ternary exression
false ? ( ) => 41 : null ;
false ? ( arg ) => 42 : null ;
false ? ( arg = 1 ) => 43 : null ;
false ? ( arg ? ) => 44 : null ;
false ? ( arg : number ) => 45 : null ;
false ? ( arg ? : number ) => 46 : null ;
false ? ( arg ? : number = 0 ) => 47 : null ;
false ? ( ... arg : number [ ] ) => 48 : null ;
// in ternary exression within paren
false ? ( ( ) => 51 ) : null ;
false ? ( ( arg ) => 52 ) : null ;
false ? ( ( arg = 1 ) => 53 ) : null ;
false ? ( ( arg ? ) => 54 ) : null ;
false ? ( ( arg : number ) => 55 ) : null ;
false ? ( ( arg ? : number ) => 56 ) : null ;
false ? ( ( arg ? : number = 0 ) => 57 ) : null ;
false ? ( ( ... arg : number [ ] ) => 58 ) : null ;
// ternary exression's else clause
false ? null : ( ) => 61 ;
false ? null : ( arg ) => 62 ;
false ? null : ( arg = 1 ) => 63 ;
false ? null : ( arg ? ) => 64 ;
false ? null : ( arg : number ) => 65 ;
false ? null : ( arg ? : number ) => 66 ;
false ? null : ( arg ? : number = 0 ) => 67 ;
false ? null : ( ... arg : number [ ] ) => 68 ;
// nested ternary expressions
( a ? ) => { return a ; } ? ( b ? ) => { return b ; } : ( c ? ) => { return c ; } ;
//multiple levels
( a ? ) => { return a ; } ? ( b ) => ( c ) => 81 : ( c ) => ( d ) => 82 ;
// In Expressions
( ( arg ) => 90 ) instanceof Function ;
( ( arg = 1 ) => 91 ) instanceof Function ;
( ( arg ? ) => 92 ) instanceof Function ;
( ( arg : number ) => 93 ) instanceof Function ;
( ( arg : number = 1 ) => 94 ) instanceof Function ;
( ( arg ? : number ) => 95 ) instanceof Function ;
( ( ... arg : number [ ] ) => 96 ) instanceof Function ;
'' + ( arg ) => 100 ;
( ( arg ) => 0 ) + '' + ( arg ) => 101 ;
( ( arg = 1 ) => 0 ) + '' + ( arg = 2 ) => 102 ;
( ( arg ? ) => 0 ) + '' + ( arg ? ) => 103 ;
( ( arg : number ) => 0 ) + '' + ( arg : number ) => 104 ;
( ( arg : number = 1 ) => 0 ) + '' + ( arg : number = 2 ) => 105 ;
( ( arg ? : number = 1 ) => 0 ) + '' + ( arg ? : number = 2 ) => 106 ;
( ( ... arg : number [ ] ) => 0 ) + '' + ( ... arg : number [ ] ) => 107 ;
( ( arg1 , arg2 ? ) => 0 ) + '' + ( arg1 , arg2 ? ) => 108 ;
( ( arg1 , ... arg2 : number [ ] ) => 0 ) + '' + ( arg1 , ... arg2 : number [ ] ) => 108 ;
// Function Parameters
function foo ( ... arg : any [ ] ) { }
foo (
( a ) => 110 ,
( ( a ) => 111 ) ,
( a ) => {
return 112 ;
} ,
( a ? ) => 113 ,
( a , b ? ) => 114 ,
( a : number ) => 115 ,
( a : number = 0 ) => 116 ,
( a = 0 ) => 117 ,
( a ? : number = 0 ) => 118 ,
( a ? , b ? : number = 0 ) => 118 ,
( ... a : number [ ] ) => 119 ,
( a , b ? = 0 , ... c : number [ ] ) => 120 ,
( a ) => ( b ) => ( c ) => 121 ,
false ? ( a ) => 0 : ( b ) => 122
) ;
@@ -1,112 +0,0 @@
// valid
() => 1;
(arg) => 2;
arg => 2;
(arg = 1) => 3;
(arg?) => 4;
(arg: number) => 5;
(arg: number = 0) => 6;
(arg?: number) => 7;
(...arg: number[]) => 8;
(arg1, arg2) => 12;
(arg1 = 1, arg2 = 3) => 13;
(arg1?, arg2?) => 14;
(arg1: number, arg2: number) => 15;
(arg1: number = 0, arg2: number = 1) => 16;
(arg1?: number, arg2?: number) => 17;
(arg1, ...arg2: number[]) => 18;
(arg1, arg2?: number) => 19;
// in paren
(() => 21);
((arg) => 22);
((arg = 1) => 23);
((arg?) => 24);
((arg: number) => 25);
((arg: number = 0) => 26);
((arg?: number) => 27);
((...arg: number[]) => 28);
// in multiple paren
(((((arg) => { return 32; }))));
// in ternary exression
false ? () => 41 : null;
false ? (arg) => 42 : null;
false ? (arg = 1) => 43 : null;
false ? (arg?) => 44 : null;
false ? (arg: number) => 45 : null;
false ? (arg?: number) => 46 : null;
false ? (arg?: number = 0) => 47 : null;
false ? (...arg: number[]) => 48 : null;
// in ternary exression within paren
false ? (() => 51) : null;
false ? ((arg) => 52) : null;
false ? ((arg = 1) => 53) : null;
false ? ((arg?) => 54) : null;
false ? ((arg: number) => 55) : null;
false ? ((arg?: number) => 56) : null;
false ? ((arg?: number = 0) => 57) : null;
false ? ((...arg: number[]) => 58) : null;
// ternary exression's else clause
false ? null : () => 61;
false ? null : (arg) => 62;
false ? null : (arg = 1) => 63;
false ? null : (arg?) => 64;
false ? null : (arg: number) => 65;
false ? null : (arg?: number) => 66;
false ? null : (arg?: number = 0) => 67;
false ? null : (...arg: number[]) => 68;
// nested ternary expressions
(a?) => { return a; } ? (b?) => { return b; } : (c?) => { return c; };
//multiple levels
(a?) => { return a; } ? (b) => (c) => 81 : (c) => (d) => 82;
// In Expressions
((arg) => 90) instanceof Function;
((arg = 1) => 91) instanceof Function;
((arg?) => 92) instanceof Function;
((arg: number) => 93) instanceof Function;
((arg: number = 1) => 94) instanceof Function;
((arg?: number) => 95) instanceof Function;
((...arg: number[]) => 96) instanceof Function;
'' + (arg) => 100;
((arg) => 0) + '' + (arg) => 101;
((arg = 1) => 0) + '' + (arg = 2) => 102;
((arg?) => 0) + '' + (arg?) => 103;
((arg: number) => 0) + '' + (arg: number) => 104;
((arg: number = 1) => 0) + '' + (arg: number = 2) => 105;
((arg?: number = 1) => 0) + '' + (arg?: number = 2) => 106;
((...arg: number[]) => 0) + '' + (...arg: number[]) => 107;
((arg1, arg2?) => 0) + '' + (arg1, arg2?) => 108;
((arg1, ...arg2: number[]) => 0) + '' + (arg1, ...arg2: number[]) => 108;
// Function Parameters
function foo(...arg: any[]) { }
foo(
(a) => 110,
((a) => 111),
(a) => {
return 112;
},
(a?) => 113,
(a, b?) => 114,
(a: number) => 115,
(a: number = 0) => 116,
(a = 0) => 117,
(a?: number = 0) => 118,
(a?, b?: number = 0) => 118,
(...a: number[]) => 119,
(a, b? = 0, ...c: number[]) => 120,
(a) => (b) => (c) => 121,
false ? (a) => 0 : (b) => 122
);
@@ -1,2 +0,0 @@
if(false){debugger;}
if ( false ) { debugger ; }
@@ -1,2 +0,0 @@
if (false) { debugger; }
if (false) { debugger; }
@@ -1,13 +0,0 @@
var fun1 = function ( ) {
var x = 'foo' ,
z = 'bar' ;
return x ;
},
fun2 = ( function ( f ) {
var fun = function ( ) {
console . log ( f ( ) ) ;
},
x = 'Foo' ;
return fun ;
} ( fun1 ) ) ;
@@ -1,13 +0,0 @@
var fun1 = function() {
var x = 'foo',
z = 'bar';
return x;
},
fun2 = (function(f) {
var fun = function() {
console.log(f());
},
x = 'Foo';
return fun;
} (fun1));
@@ -1,3 +0,0 @@
export class A {
}
@@ -1,6 +0,0 @@
module Foo {
}
import bar = Foo;
import bar2=Foo;
@@ -1,6 +0,0 @@
module Foo {
}
import bar = Foo;
import bar2 = Foo;
@@ -1,95 +0,0 @@
var a;var c , b;var $d
var $e
var f
a++;b++;
function f ( ) {
for (i = 0; i < 10; i++) {
k = abc + 123 ^ d;
a = XYZ[m (a[b[c][d]])];
break;
switch ( variable){
case 1: abc += 425;
break;
case 404 : a [x--/2]%=3 ;
break ;
case vari : v[--x ] *=++y*( m + n / k[z]);
for (a in b){
for (a = 0; a < 10; ++a) {
a++;--a;
if (a == b) {
a++;b--;
}
else
if (a == c){
++a;
(--c)+=d;
$c = $a + --$b;
}
if (a == b)
if (a != b) {
if (a !== b)
if (a === b)
--a;
else
--a;
else {
a--;++b;
a++
}
}
}
for (x in y) {
m-=m;
k=1+2+3+4;
}
}
break;
}
}
var a ={b:function(){}};
return {a:1,b:2}
}
var z = 1;
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
for (k = 0; k < 10; ++k) {
z++;
}
for (k = 0; k < 10; k += 2) {
z++;
}
$(document).ready ();
function pageLoad() {
$('#TextBox1' ) . unbind ( ) ;
$('#TextBox1' ) . datepicker ( ) ;
}
function pageLoad ( ) {
var webclass=[
{ 'student' :
{ 'id': '1', 'name': 'Linda Jones', 'legacySkill': 'Access, VB 5.0' }
} ,
{ 'student':
{'id':'2','name':'Adam Davidson','legacySkill':'Cobol,MainFrame'}
} ,
{ 'student':
{ 'id':'3','name':'Charles Boyer' ,'legacySkill':'HTML, XML'}
}
];
$create(Sys.UI.DataView,{data:webclass},null,null,$get('SList'));
}
$( document ).ready(function(){
alert('hello');
} ) ;
@@ -1,98 +0,0 @@
var a; var c, b; var $d
var $e
var f
a++; b++;
function f() {
for (i = 0; i < 10; i++) {
k = abc + 123 ^ d;
a = XYZ[m(a[b[c][d]])];
break;
switch (variable) {
case 1: abc += 425;
break;
case 404: a[x-- / 2] %= 3;
break;
case vari: v[--x] *= ++y * (m + n / k[z]);
for (a in b) {
for (a = 0; a < 10; ++a) {
a++; --a;
if (a == b) {
a++; b--;
}
else
if (a == c) {
++a;
(--c) += d;
$c = $a + --$b;
}
if (a == b)
if (a != b) {
if (a !== b)
if (a === b)
--a;
else
--a;
else {
a--; ++b;
a++
}
}
}
for (x in y) {
m -= m;
k = 1 + 2 + 3 + 4;
}
}
break;
}
}
var a = { b: function() { } };
return { a: 1, b: 2 }
}
var z = 1;
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
for (k = 0; k < 10; ++k) {
z++;
}
for (k = 0; k < 10; k += 2) {
z++;
}
$(document).ready();
function pageLoad() {
$('#TextBox1').unbind();
$('#TextBox1').datepicker();
}
function pageLoad() {
var webclass = [
{
'student':
{ 'id': '1', 'name': 'Linda Jones', 'legacySkill': 'Access, VB 5.0' }
},
{
'student':
{ 'id': '2', 'name': 'Adam Davidson', 'legacySkill': 'Cobol,MainFrame' }
},
{
'student':
{ 'id': '3', 'name': 'Charles Boyer', 'legacySkill': 'HTML, XML' }
}
];
$create(Sys.UI.DataView, { data: webclass }, null, null, $get('SList'));
}
$(document).ready(function() {
alert('hello');
});
@@ -1,3 +0,0 @@
module Foo {
export module A . B . C { }
}
@@ -1,3 +0,0 @@
module Foo {
export module A.B.C { }
}
@@ -1,76 +0,0 @@
module mod1 {
export class b {
}
class d {
}
export interface ib {
}
}
module m2 {
export module m3 {
export class c extends mod1.b {
}
export class ib2 implements mod1.ib {
}
}
}
class c extends mod1.b {
}
class ib2 implements mod1.ib {
}
declare export module "m4" {
export class d {
} ;
var x : d ;
export function foo ( ) : d ;
}
import m4 = module ( "m4" ) ;
export var x4 = m4.x ;
export var d4 = m4.d ;
export var f4 = m4.foo ( ) ;
export module m1 {
declare export module "m2" {
export class d {
} ;
var x: d ;
export function foo ( ) : d ;
}
import m2 = module ( "m2" ) ;
import m3 = module ( "m4" ) ;
export var x2 = m2.x ;
export var d2 = m2.d ;
export var f2 = m2.foo ( ) ;
export var x3 = m3.x ;
export var d3 = m3.d ;
export var f3 = m3.foo ( ) ;
}
export var x2 = m1.m2.x ;
export var d2 = m1.m2.d ;
export var f2 = m1.m2.foo ( ) ;
export var x3 = m1.m3.x ;
export var d3 = m1.m3.d ;
export var f3 = m1.m3.foo ( ) ;
export module m5 {
export var x2 = m1.m2.x ;
export var d2 = m1.m2.d ;
export var f2 = m1.m2.foo ( ) ;
export var x3 = m1.m3.x ;
export var d3 = m1.m3.d ;
export var f3 = m1.m3.foo ( ) ;
}
@@ -1,76 +0,0 @@
module mod1 {
export class b {
}
class d {
}
export interface ib {
}
}
module m2 {
export module m3 {
export class c extends mod1.b {
}
export class ib2 implements mod1.ib {
}
}
}
class c extends mod1.b {
}
class ib2 implements mod1.ib {
}
declare export module "m4" {
export class d {
};
var x: d;
export function foo(): d;
}
import m4 = module("m4");
export var x4 = m4.x;
export var d4 = m4.d;
export var f4 = m4.foo();
export module m1 {
declare export module "m2" {
export class d {
};
var x: d;
export function foo(): d;
}
import m2 = module("m2");
import m3 = module("m4");
export var x2 = m2.x;
export var d2 = m2.d;
export var f2 = m2.foo();
export var x3 = m3.x;
export var d3 = m3.d;
export var f3 = m3.foo();
}
export var x2 = m1.m2.x;
export var d2 = m1.m2.d;
export var f2 = m1.m2.foo();
export var x3 = m1.m3.x;
export var d3 = m1.m3.d;
export var f3 = m1.m3.foo();
export module m5 {
export var x2 = m1.m2.x;
export var d2 = m1.m2.d;
export var f2 = m1.m2.foo();
export var x3 = m1.m3.x;
export var d3 = m1.m3.d;
export var f3 = m1.m3.foo();
}
@@ -1,27 +0,0 @@
var x = {foo: 1,
bar: "tt",
boo: 1 + 5};
var x2 = {foo: 1,
bar: "tt",boo:1+5};
function Foo() {
var typeICalc = {
clear: {
"()": [1, 2, 3]
}
}
}
// Rule for object literal members for the "value" of the memebr to follow the indent
// of the member, i.e. the relative position of the value is maintained when the member
// is indented.
var x2 = {
foo:
3,
'bar':
{ a: 1, b : 2}
};
var x={ };
var y = {};
@@ -1,31 +0,0 @@
var x = {
foo: 1,
bar: "tt",
boo: 1 + 5
};
var x2 = {
foo: 1,
bar: "tt", boo: 1 + 5
};
function Foo() {
var typeICalc = {
clear: {
"()": [1, 2, 3]
}
}
}
// Rule for object literal members for the "value" of the memebr to follow the indent
// of the member, i.e. the relative position of the value is maintained when the member
// is indented.
var x2 = {
foo:
3,
'bar':
{ a: 1, b: 2 }
};
var x = {};
var y = {};
@@ -1,32 +0,0 @@
function f( ) {
var x = 3;
var z = 2 ;
a = z ++ - 2 * x ;
for ( ; ; ) {
a+=(g +g)*a%t;
b -- ;
}
switch ( a )
{
case 1 : {
a ++ ;
b--;
if(a===a)
return;
else
{
for(a in b)
if(a!=a)
{
for(a in b)
{
a++;
}
}
}
}
default:
break;
}
}
@@ -1,28 +0,0 @@
function f() {
var x = 3;
var z = 2;
a = z++ - 2 * x;
for (; ;) {
a += (g + g) * a % t;
b--;
}
switch (a) {
case 1: {
a++;
b--;
if (a === a)
return;
else {
for (a in b)
if (a != a) {
for (a in b) {
a++;
}
}
}
}
default:
break;
}
}
@@ -1 +0,0 @@
var a=b+c^d-e*++f;
@@ -1 +0,0 @@
var a = b + c ^ d - e * ++f;
@@ -1 +0,0 @@
class test { constructor () { } }
@@ -1 +0,0 @@
class test { constructor() { } }
@@ -1,10 +0,0 @@
module Tools {
export enum NodeType {
Error,
Comment,
}
export enum foob
{
Blah=1, Bleah=2
}
}
@@ -1,9 +0,0 @@
module Tools {
export enum NodeType {
Error,
Comment,
}
export enum foob {
Blah = 1, Bleah = 2
}
}
@@ -1,65 +0,0 @@
module MyModule
{
module A.B.C {
module F {
}
}
interface Blah
{
boo: string;
}
class Foo
{
}
class Foo2 {
public foo():number {
return 5 * 6;
}
public foo2() {
if (1 === 2)
{
var y : number= 76;
return y;
}
while (2 == 3) {
if ( y == null ) {
}
}
}
public foo3() {
if (1 === 2)
//comment preventing line merging
{
var y = 76;
return y;
}
}
}
}
function foo(a:number, b:number):number
{
return 0;
}
function bar(a:number, b:number) :number[] {
return [];
}
module BugFix3 {
declare var f: {
(): any;
(x: number): string;
foo: number;
};
}
@@ -1,58 +0,0 @@
module MyModule {
module A.B.C {
module F {
}
}
interface Blah {
boo: string;
}
class Foo {
}
class Foo2 {
public foo(): number {
return 5 * 6;
}
public foo2() {
if (1 === 2) {
var y: number = 76;
return y;
}
while (2 == 3) {
if (y == null) {
}
}
}
public foo3() {
if (1 === 2)
//comment preventing line merging
{
var y = 76;
return y;
}
}
}
}
function foo(a: number, b: number): number {
return 0;
}
function bar(a: number, b: number): number[] {
return [];
}
module BugFix3 {
declare var f: {
(): any;
(x: number): string;
foo: number;
};
}
@@ -1,17 +0,0 @@
function f(a,b,c,d){
for(var i=0;i<10;i++){
var a=0;
var b=a+a+a*a%a/2-1;
b+=a;
++b;
f(a,b,c,d);
if(1===1){
var m=function(e,f){
return e^f;
}
}
}
}
for (var i = 0 ; i < this.foo(); i++) {
}
@@ -1,17 +0,0 @@
function f(a, b, c, d) {
for (var i = 0; i < 10; i++) {
var a = 0;
var b = a + a + a * a % a / 2 - 1;
b += a;
++b;
f(a, b, c, d);
if (1 === 1) {
var m = function(e, f) {
return e ^ f;
}
}
}
}
for (var i = 0 ; i < this.foo(); i++) {
}
@@ -1,9 +0,0 @@
with (foo.bar)
{
}
with (bar.blah)
{
}
@@ -1,6 +0,0 @@
with (foo.bar) {
}
with (bar.blah) {
}
+1
View File
@@ -18,6 +18,7 @@ namespace ts.server {
createDirectory(): void {},
getExecutingFilePath(): string { return void 0; },
getCurrentDirectory(): string { return void 0; },
getEnvironmentVariable(name: string): string { return ""; },
readDirectory(): string[] { return []; },
exit(): void { },
setTimeout(callback, ms, ...args) { return 0; },
-1
View File
@@ -101,7 +101,6 @@ namespace ts {
});
});
if (canUseOldTranspile) {
it("Correct output (old transpile) for " + justName, () => {
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".oldTranspile.js"), () => {
+3 -2
View File
@@ -151,7 +151,7 @@ namespace ts {
);
});
it("always exclude outDir", () => {
it("exclude outDir unless overridden", () => {
const tsconfigWithoutExclude =
`{
"compilerOptions": {
@@ -169,7 +169,7 @@ namespace ts {
const allFiles = ["/bin/a.ts", "/b.ts"];
const expectedFiles = ["/b.ts"];
assertParseFileList(tsconfigWithoutExclude, "tsconfig.json", rootDir, allFiles, expectedFiles);
assertParseFileList(tsconfigWithExclude, "tsconfig.json", rootDir, allFiles, expectedFiles);
assertParseFileList(tsconfigWithExclude, "tsconfig.json", rootDir, allFiles, allFiles);
});
it("implicitly exclude common package folders", () => {
@@ -186,6 +186,7 @@ namespace ts {
const content = `{
"compilerOptions": {
"allowJs": true
// Some comments
"outDir": "bin"
}
"files": ["file1.ts"]

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