Merge branch 'master' into comparableRelation

This commit is contained in:
Daniel Rosenwasser
2016-03-30 01:01:02 -07:00
10717 changed files with 358022 additions and 117255 deletions
+3 -13
View File
@@ -1,15 +1,5 @@
node_modules/
built/*
tests/cases/*.js
tests/cases/*/*.js
tests/cases/*/*/*.js
tests/cases/*/*/*/*.js
tests/cases/*/*/*/*/*.js
tests/cases/*.js.map
tests/cases/*/*.js.map
tests/cases/*/*/*.js.map
tests/cases/*/*/*/*.js.map
tests/cases/*/*/*/*/*.js.map
tests/cases/rwc/*
tests/cases/test262/*
tests/cases/perf/*
@@ -38,9 +28,9 @@ build.json
*.actual
tests/webhost/*.d.ts
tests/webhost/webtsc.js
tests/*.js
tests/*.js.map
tests/*.d.ts
tests/cases/**/*.js
tests/cases/**/*.js.map
tests/cases/**/*.d.ts
*.config
scripts/debug.bat
scripts/run.bat
+1
View File
@@ -1,6 +1,7 @@
language: node_js
node_js:
- 'stable'
- '4'
- '0.10'
+39 -4
View File
@@ -2,69 +2,104 @@ TypeScript is authored by:
* Adam Freidin
* Ahmad Farid
* Akshar Patel
* Anders Hejlsberg
* Arnav Singh
* Arthur Ozga
* Asad Saeeduddin
* Basarat Ali Syed
* Ben Duffield
* Bill Ticehurst
* Brett Mayen
* Bryan Forbes
* Caitlin Potter
* Chris Bubernak
* Colby Russell
* Colin Snover
* Cyrus Najmabadi
* Dan Corder
* Dan Quirk
* Daniel Rosenwasser
* @dashaus
* David Li
* Dick van den Brink
* Dirk Bäumer
* Denis Nedelyaev
* Dick van den Brink
* Dirk Bäumer
* Dirk Holtwick
* Eyas Sharaiha
* @falsandtru
* Frank Wallis
* Gabriel Isenberg
* Gilad Peleg
* Graeme Wicksted
* Guillaume Salles
* Guy Bedford
* Harald Niesche
* Iain Monro
* Ingvar Stepanyan
* Ivo Gabe de Wolff
* James Whitney
* Jason Freeman
* Jason Killian
* Jason Ramsay
* Jed Mao
* Jeffrey Morlan
* Johannes Rieken
* John Vilk
* Jonathan Bond-Caron
* Jonathan Park
* Jonathan Turner
* Jonathon Smith
* Josh Kalderimis
* Julian Williams
* Kagami Sascha Rosylight
* Keith Mashinter
* Ken Howard
* Kenji Imamula
* Lorant Pinter
* Lucien Greathouse
* Martin Všetička
* Masahiro Wakame
* Mattias Buelens
* Max Deepfield
* Micah Zoltu
* Mohamed Hegazy
* Nathan Shively-Sanders
* Nathan Yee
* Oleg Mihailik
* Oleksandr Chekhovskyi
* Paul van Brenk
* @pcbro
* Pedro Maltez
* Philip Bulley
* piloopin
* @progre
* Punya Biswal
* Richard Sentino
* Ron Buckton
* Rowan Wyborn
* Ryan Cavanaugh
* Ryohei Ikegami
* Sébastien Arod
* Sheetal Nandi
* Shengping Zhong
* Shyyko Serhiy
* Simon Hürlimann
* Simon Hürlimann
* Solal Pirelli
* Stan Thomas
* Steve Lucco
* Thomas Loubiou
* Tien Hoanhtien
* Tim Perry
* Tingan Ho
* togru
* Tomas Grubliauskas
* TruongSinh Tran-Nguyen
* Viliv Vane
* Vladimir Matveev
* Wesley Wigham
* York Yao
* Yui Tanglertsampan
* Yuichi Nukiyama
* Zev Spitz
* Zhengbo Li
* Zhengbo Li
+47 -3
View File
@@ -1,3 +1,45 @@
# Instructions for Logging Issues
## 1. Read the FAQ
Please [read the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) before logging new issues, even if you think you have found a bug.
Issues that ask questions answered in the FAQ will be closed without elaboration.
## 2. Search for Duplicates
[Search the existing issues](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) before logging a new one.
## 3. Do you have a question?
The issue tracker is for **issues**, in other words, bugs and suggestions.
If you have a *question*, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources.
Due to increased traffic, we can no longer answer questions in the issue tracker.
## 4. Did you find a bug?
When logging a bug, please be sure to include the following:
* What version of TypeScript you're using (run `tsc --v`)
* If at all possible, an *isolated* way to reproduce the behavior
* The behavior you expect to see, and the actual behavior
You can try out the nightly build of TypeScript (`npm install typescript@next`) to see if the bug has already been fixed.
## 5. Do you have a suggestion?
We also accept suggestions in the issue tracker.
Be sure to [check the FAQ](https://github.com/Microsoft/TypeScript/wiki/FAQ) and [search](https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue) first.
In general, things we find useful when reviewing suggestions are:
* A description of the problem you're trying to solve
* An overview of the suggested solution
* Examples of how the suggestion would work in various places
* Code examples showing e.g. "this would be an error, this wouldn't"
* Code examples showing the generated JavaScript (if applicable)
* If relevant, precedent in other languages can be useful for establishing context and expected behavior
# Instructions for Contributing Code
## Contributing bug fixes
TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved ("Milestone == Community") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort.
@@ -29,18 +71,20 @@ Your pull request should:
* Tests should include reasonable permutations of the target fix/change
* Include baseline changes with your change
* All changed code must have 100% code coverage
* Follow the code conventions descriped in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines)
* Follow the code conventions described in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines)
* To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration
## Contributing `lib.d.ts` fixes
The library sources are in: [src/lib](https://github.com/Microsoft/TypeScript/tree/master/src/lib)
To build the library files, run
Library files in `built/local/` are updated by running
```Shell
jake lib
jake
```
The files in `lib/` are used to bootstrap compilation and usually do not need to be updated.
#### `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts`
These two files represent the DOM typings and are auto-generated. To make any modifications to them, please submit a PR to https://github.com/Microsoft/TSJS-lib-generator
+87 -51
View File
@@ -40,6 +40,7 @@ var compilerSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
"sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -59,6 +60,7 @@ var servicesSources = [
"utilities.ts",
"binder.ts",
"checker.ts",
"sourcemap.ts",
"declarationEmitter.ts",
"emitter.ts",
"program.ts",
@@ -148,7 +150,10 @@ var harnessSources = harnessCoreSources.concat([
"reuseProgramStructure.ts",
"cachingInServerLSHost.ts",
"moduleResolution.ts",
"tsconfigParsing.ts"
"tsconfigParsing.ts",
"commandLineParsing.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts"
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
@@ -161,13 +166,15 @@ var harnessSources = harnessCoreSources.concat([
}));
var librarySourceMap = [
{ target: "lib.core.d.ts", sources: ["core.d.ts"] },
{ target: "lib.core.d.ts", sources: ["header.d.ts", "core.d.ts"] },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], },
{ target: "lib.d.ts", sources: ["core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.core.es6.d.ts", sources: ["core.d.ts", "es6.d.ts"]},
{ target: "lib.es6.d.ts", sources: ["es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
{ target: "lib.d.ts", sources: ["header.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.core.es6.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts"]},
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"]},
{ target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
];
var libraryTargets = librarySourceMap.map(function (f) {
@@ -219,48 +226,59 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
* @param prereqs: prerequisite tasks to compiling the file
* @param prefixes: a list of files to prepend to the target file
* @param useBuiltCompiler: true to use the built compiler, false to use the LKG
* @param noOutFile: true to compile without using --out
* @param generateDeclarations: true to compile using --declaration
* @param outDir: true to compile using --outDir
* @param keepComments: false to compile using --removeComments
* @parap {Object} opts - property bag containing auxiliary options
* @param {boolean} opts.noOutFile: true to compile without using --out
* @param {boolean} opts.generateDeclarations: true to compile using --declaration
* @param {string} opts.outDir: value for '--outDir' command line option
* @param {boolean} opts.keepComments: false to compile using --removeComments
* @param {boolean} opts.preserveConstEnums: true if compiler should keep const enums in code
* @param {boolean} opts.noResolve: true if compiler should not include non-rooted files in compilation
* @param {boolean} opts.stripInternal: true if compiler should remove declarations marked as @internal
* @param {boolean} opts.noMapRoot: true if compiler omit mapRoot option
* @param callback: a function to execute after the compilation process ends
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) {
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) {
file(outFile, prereqs, function() {
var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler;
var options = "--module commonjs --noImplicitAny --noEmitOnError --pretty";
var options = "--noImplicitAny --noEmitOnError --pretty";
opts = opts || {};
// Keep comments when specifically requested
// or when in debug mode.
if (!(keepComments || useDebugMode)) {
if (!(opts.keepComments || useDebugMode)) {
options += " --removeComments";
}
if (generateDeclarations) {
if (opts.generateDeclarations) {
options += " --declaration";
}
if (preserveConstEnums || useDebugMode) {
if (opts.preserveConstEnums || useDebugMode) {
options += " --preserveConstEnums";
}
if (outDir) {
options += " --outDir " + outDir;
if (opts.outDir) {
options += " --outDir " + opts.outDir;
}
if (!noOutFile) {
if (!opts.noOutFile) {
options += " --out " + outFile;
}
else {
options += " --module commonjs"
}
if(noResolve) {
if(opts.noResolve) {
options += " --noResolve";
}
if (useDebugMode) {
options += " -sourcemap -mapRoot file:///" + path.resolve(path.dirname(outFile));
options += " -sourcemap";
if (!opts.noMapRoot) {
options += " -mapRoot file:///" + path.resolve(path.dirname(outFile));
}
}
if (stripInternal) {
if (opts.stripInternal) {
options += " --stripInternal"
}
@@ -362,7 +380,6 @@ file(builtGeneratedDiagnosticMessagesJSON,[generatedDiagnosticMessagesJSON], fun
desc("Generates a diagnostic file in TypeScript based on an input JSON file");
task("generate-diagnostics", [diagnosticInfoMapTs]);
// Publish nightly
var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js");
var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts");
@@ -376,13 +393,7 @@ compileFile(/*outfile*/configureNightlyJs,
/*prereqs*/ [configureNightlyTs],
/*prefixes*/ [],
/*useBuiltCompiler*/ false,
/*noOutFile*/ false,
/*generateDeclarations*/ false,
/*outDir*/ undefined,
/*preserveConstEnums*/ undefined,
/*keepComments*/ false,
/*noResolve*/ false,
/*stripInternal*/ false);
{ noOutFile: false, generateDeclarations: false, keepComments: false, noResolve: false, stripInternal: false });
task("setDebugMode", function() {
useDebugMode = true;
@@ -432,6 +443,7 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js");
var servicesFileInBrowserTest = path.join(builtLocalDirectory, "typescriptServicesInBrowserTest.js");
var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts");
var nodePackageFile = path.join(builtLocalDirectory, "typescript.js");
var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts");
@@ -440,13 +452,7 @@ var nodeStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescript_s
compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ true,
/*outDir*/ undefined,
/*preserveConstEnums*/ true,
/*keepComments*/ true,
/*noResolve*/ false,
/*stripInternal*/ true,
{ noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true },
/*callback*/ function () {
jake.cpR(servicesFile, nodePackageFile, {silent: true});
@@ -463,12 +469,22 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
var nodeDefinitionsFileContents = definitionFileContents + "\r\nexport = ts;";
fs.writeFileSync(nodeDefinitionsFile, nodeDefinitionsFileContents);
// Node package definition file to be distributed without the package. Created by replacing
// Node package definition file to be distributed without the package. Created by replacing
// 'ts' namespace with '"typescript"' as a module.
var nodeStandaloneDefinitionsFileContents = definitionFileContents.replace(/declare (namespace|module) ts/g, 'declare module "typescript"');
fs.writeFileSync(nodeStandaloneDefinitionsFile, nodeStandaloneDefinitionsFileContents);
});
compileFile(servicesFileInBrowserTest, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
{ noOutFile: false, generateDeclarations: true, preserveConstEnums: true, keepComments: true, noResolve: false, stripInternal: true, noMapRoot: true },
/*callback*/ function () {
var content = fs.readFileSync(servicesFileInBrowserTest).toString();
var i = content.lastIndexOf("\n");
fs.writeFileSync(servicesFileInBrowserTest, content.substring(0, i) + "\r\n//# sourceURL=../built/local/typeScriptServices.js" + content.substring(i));
});
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
@@ -480,8 +496,7 @@ compileFile(
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ true);
{ noOutFile: false, generateDeclarations: true });
// Local target to build the language service server library
desc("Builds language service server library");
@@ -529,7 +544,8 @@ compileFile(word2mdJs,
// The generated spec.md; built for the 'generate-spec' task
file(specMd, [word2mdJs, specWord], function () {
var specWordFullPath = path.resolve(specWord);
var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + specMd;
var specMDFullPath = path.resolve(specMd);
var cmd = "cscript //nologo " + word2mdJs + ' "' + specWordFullPath + '" ' + '"' + specMDFullPath + '"';
console.log(cmd);
child_process.exec(cmd, function () {
complete();
@@ -639,7 +655,7 @@ function deleteTemporaryProjectOutput() {
}
}
function runConsoleTests(defaultReporter, defaultSubsets, postLint) {
function runConsoleTests(defaultReporter, defaultSubsets) {
cleanTestDirs();
var debug = process.env.debug || process.env.d;
tests = process.env.test || process.env.tests || process.env.t;
@@ -672,13 +688,13 @@ function runConsoleTests(defaultReporter, defaultSubsets, postLint) {
subsetRegexes = subsets.map(function (sub) { return "^" + sub + ".*$"; });
subsetRegexes.push("^(?!" + subsets.join("|") + ").*$");
}
subsetRegexes.forEach(function (subsetRegex) {
subsetRegexes.forEach(function (subsetRegex, i) {
tests = subsetRegex ? ' -g "' + subsetRegex + '"' : '';
var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd, function () {
deleteTemporaryProjectOutput();
if (postLint) {
if (i === 0) {
var lint = jake.Task['lint'];
lint.addListener('complete', function () {
complete();
@@ -700,7 +716,7 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function() {
runConsoleTests('mocha-fivemat-progress-reporter', [], /*postLint*/ true);
runConsoleTests('mocha-fivemat-progress-reporter', []);
}, {async: true});
desc("Generates code coverage data via instanbul");
@@ -713,7 +729,7 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
// Browser tests
var nodeServerOutFile = 'tests/webTestServer.js'
var nodeServerInFile = 'tests/webTestServer.ts'
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, /*noOutFile*/ true);
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() {
@@ -722,7 +738,7 @@ task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function()
}, {async: true});
desc("Runs the tests using the built run.js file like 'jake runtests'. Syntax is jake runtests-browser. Additional optional parameters tests=[regex], port=, browser=[chrome|IE]");
task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function() {
task("runtests-browser", ["tests", "browserify", builtLocalDirectory, servicesFileInBrowserTest], function() {
cleanTestDirs();
host = "node"
port = process.env.port || process.env.p || '8888';
@@ -861,7 +877,9 @@ var tslintRules = ([
"noNullRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule"
"typeOperatorSpacingRule",
"noInOperatorRule",
"noIncrementDecrementRule"
]);
var tslintRulesFiles = tslintRules.map(function(p) {
return path.join(tslintRuleDir, p + ".ts");
@@ -872,7 +890,8 @@ var tslintRulesOutFiles = tslintRules.map(function(p) {
desc("Compiles tslint rules to js");
task("build-rules", tslintRulesOutFiles);
tslintRulesFiles.forEach(function(ruleFile, i) {
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false, /*noOutFile*/ true, /*generateDeclarations*/ false, path.join(builtLocalDirectory, "tslint"));
compileFile(tslintRulesOutFiles[i], [ruleFile], [ruleFile], [], /*useBuiltCompiler*/ false,
{ noOutFile: true, generateDeclarations: false, outDir: path.join(builtLocalDirectory, "tslint")});
});
function getLinterOptions() {
@@ -886,6 +905,7 @@ function getLinterOptions() {
function lintFileContents(options, path, contents) {
var ll = new Linter(path, contents, options);
console.log("Linting '" + path + "'.")
return ll.lint();
}
@@ -904,20 +924,36 @@ function lintFileAsync(options, path, cb) {
});
}
var servicesLintTargets = [
"navigateTo.ts",
"outliningElementsCollector.ts",
"patternMatcher.ts",
"services.ts",
"shims.ts",
"jsTyping.ts"
].map(function (s) {
return path.join(servicesDirectory, s);
});
var lintTargets = compilerSources
.concat(harnessCoreSources)
.concat(serverCoreSources);
.concat(serverCoreSources)
.concat(tslintRulesFiles)
.concat(servicesLintTargets);
desc("Runs tslint on the compiler sources");
task("lint", ["build-rules"], function() {
var lintOptions = getLinterOptions();
var failed = 0;
for (var i in lintTargets) {
var result = lintFile(lintOptions, lintTargets[i]);
if (result.failureCount > 0) {
console.log(result.output);
fail('Linter errors.', result.failureCount);
failed += result.failureCount;
}
}
if (failed > 0) {
fail('Linter errors.', failed);
}
});
/**
@@ -934,7 +970,7 @@ function lintWatchFile(filename) {
if (event !== "change") {
return;
}
if (!lintSemaphores[filename]) {
lintSemaphores[filename] = true;
lintFileAsync(getLinterOptions(), filename, function(err, result) {
+2 -2
View File
@@ -1,6 +1,6 @@
[![Build Status](https://travis-ci.org/Microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript)
[![npm version](https://badge.fury.io/js/typescript.svg)](http://badge.fury.io/js/typescript)
[![Downloads](http://img.shields.io/npm/dm/TypeScript.svg)](https://npmjs.org/package/typescript)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/TypeScript.svg)](https://www.npmjs.com/package/typescript)
# TypeScript
+9
View File
@@ -0,0 +1,9 @@
# Read This!
This directory contains miscellaneous documentation such as the TypeScript language specification and logo.
If you are looking for more introductory material, you might want to take a look at the [TypeScript Handbook](https://github.com/Microsoft/TypeScript-Handbook).
# Spec Contributions
The specification is first authored as a Microsoft Word (docx) file and then generated into Markdown and PDF formats.
Due to the binary format of docx files, and the merging difficulties that may come with it, it is preferred that **any suggestions or problems found in the spec should be [filed as issues](https://github.com/Microsoft/TypeScript/issues/new)** rather than sent as pull requests.
Binary file not shown.
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
# The TypeScript Handbook
The contents of the TypeScript Handbook can be read from [its GitHub repository](https://github.com/Microsoft/TypeScript-Handbook).
Issues and pull requests should be directed there.
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+210 -112
View File
@@ -1,8 +1,8 @@
# TypeScript Language Specification
Version 1.6
Version 1.8
August, 2015
January, 2016
<br/>
@@ -58,8 +58,8 @@ TypeScript is a trademark of Microsoft Corporation.
* [3.6 Type Parameters](#3.6)
* [3.6.1 Type Parameter Lists](#3.6.1)
* [3.6.2 Type Argument Lists](#3.6.2)
* [3.6.3 This-types](#3.6.3)
* [3.7 Named Types](#3.7)
* [3.7.1 Instance Types](#3.7.1)
* [3.8 Specifying Types](#3.8)
* [3.8.1 Predefined Types](#3.8.1)
* [3.8.2 Type References](#3.8.2)
@@ -71,6 +71,7 @@ TypeScript is a trademark of Microsoft Corporation.
* [3.8.8 Function Type Literals](#3.8.8)
* [3.8.9 Constructor Type Literals](#3.8.9)
* [3.8.10 Type Queries](#3.8.10)
* [3.8.11 This-Type References](#3.8.11)
* [3.9 Specifying Members](#3.9)
* [3.9.1 Property Signatures](#3.9.1)
* [3.9.2 Call Signatures](#3.9.2)
@@ -158,7 +159,8 @@ TypeScript is a trademark of Microsoft Corporation.
* [6.5 Generic Functions](#6.5)
* [6.6 Code Generation](#6.6)
* [6.7 Generator Functions](#6.7)
* [6.8 Type Guard Functions](#6.8)
* [6.8 Asynchronous Functions](#6.8)
* [6.9 Type Guard Functions](#6.9)
* [7 Interfaces](#7)
* [7.1 Interface Declarations](#7.1)
* [7.2 Declaration Merging](#7.2)
@@ -184,9 +186,10 @@ TypeScript is a trademark of Microsoft Corporation.
* [8.4.3 Member Accessor Declarations](#8.4.3)
* [8.4.4 Dynamic Property Declarations](#8.4.4)
* [8.5 Index Member Declarations](#8.5)
* [8.6 Code Generation](#8.6)
* [8.6.1 Classes Without Extends Clauses](#8.6.1)
* [8.6.2 Classes With Extends Clauses](#8.6.2)
* [8.6 Decorators](#8.6)
* [8.7 Code Generation](#8.7)
* [8.7.1 Classes Without Extends Clauses](#8.7.1)
* [8.7.2 Classes With Extends Clauses](#8.7.2)
* [9 Enums](#9)
* [9.1 Enum Declarations](#9.1)
* [9.2 Enum Members](#9.2)
@@ -238,9 +241,9 @@ TypeScript is a trademark of Microsoft Corporation.
JavaScript applications such as web e-mail, maps, document editing, and collaboration tools are becoming an increasingly important part of the everyday computing. We designed TypeScript to meet the needs of the JavaScript programming teams that build and maintain large JavaScript programs. TypeScript helps programming teams to define interfaces between software components and to gain insight into the behavior of existing JavaScript libraries. TypeScript also enables teams to reduce naming conflicts by organizing their code into dynamically-loadable modules. TypeScript's optional type system enables JavaScript programmers to use highly-productive development tools and practices: static checking, symbol-based navigation, statement completion, and code re-factoring.
TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 6 (ES6) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development.
TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax. Every JavaScript program is also a TypeScript program. The TypeScript compiler performs only file-local transformations on TypeScript programs and does not re-order variables declared in TypeScript. This leads to JavaScript output that closely matches the TypeScript input. TypeScript does not transform variable names, making tractable the direct debugging of emitted JavaScript. TypeScript optionally provides source maps, enabling source-level debugging. TypeScript tools typically emit JavaScript upon file save, preserving the test, edit, refresh cycle commonly used in JavaScript development.
TypeScript syntax includes all features of ECMAScript 6 (ES6), including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code.
TypeScript syntax includes all features of ECMAScript 2015, including classes and modules, and provides the ability to translate these features into ECMAScript 3 or 5 compliant code.
Classes enable programmers to express common object-oriented patterns in a standard way, making features like inheritance more readable and interoperable. Modules enable programmers to organize their code into components while avoiding naming conflicts. The TypeScript compiler provides module code generation options that support either static or dynamic loading of module contents.
@@ -262,7 +265,7 @@ function f() {
To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screen shot.
/
&emsp;&emsp;![](images/image1.png)
In this example, the programmer benefits from type inference without providing type annotations. Some beneficial tools, however, do require the programmer to provide type annotations. In TypeScript, we can express a parameter requirement as in the following code fragment.
@@ -410,7 +413,7 @@ This signature denotes that a function may be passed as the parameter of the '$'
A typical client would not need to add any additional typing but could just use a community-supplied typing to discover (through statement completion with documentation tips) and verify (through static checking) correct use of the library, as in the following screen shot.
/
&emsp;&emsp;![](images/image2.png)
Section [3.3](#3.3) provides additional information about object types.
@@ -474,7 +477,7 @@ Section [4.23](#4.23) provides additional information about contextually typed e
## <a name="1.6"/>1.6 Classes
JavaScript practice has two very common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 6 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.)
JavaScript practice has two very common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms. Libraries such as 'prototype.js' are typical of this practice. TypeScript's namespaces are a formalization of the module pattern. (The term "module pattern" is somewhat unfortunate now that ECMAScript 2015 formally supports modules in a manner different from what the module pattern prescribes. For this reason, TypeScript uses the term "namespace" for its formalization of the module pattern.)
This section and the namespace section below will show how TypeScript emits consistent, idiomatic JavaScript when emitting ECMAScript 3 or 5 compliant code for classes and namespaces. The goal of TypeScript's translation is to emit exactly what a programmer would type when implementing a class or namespace unaided by a tool. This section will also describe how TypeScript infers a type for each class declaration. We'll start with a simple BankAccount class.
@@ -627,7 +630,7 @@ An important goal of TypeScript is to provide accurate and straightforward types
JavaScript programming interfaces often include functions whose behavior is discriminated by a string constant passed to the function. The Document Object Model makes heavy use of this pattern. For example, the following screen shot shows that the 'createElement' method of the 'document' object has multiple signatures, some of which identify the types returned when specific strings are passed into the method.
/
&emsp;&emsp;![](images/image3.png)
The following code fragment uses this feature. Because the 'span' variable is inferred to have the type 'HTMLSpanElement', the code can reference without static error the 'isMultiline' property of 'span'.
@@ -638,7 +641,7 @@ span.isMultiLine = false; // OK: HTMLSpanElement has isMultiline property
In the following screen shot, a programming tool combines information from overloading on string parameters with contextual typing to infer that the type of the variable 'e' is 'MouseEvent' and that therefore 'e' has a 'clientX' property.
/
&emsp;&emsp;![](images/image4.png)
Section [3.9.2.4](#3.9.2.4) provides details on how to use string literals in function signatures.
@@ -773,13 +776,13 @@ In this case, the compiler assumes that the namespace object resides in global v
## <a name="1.11"/>1.11 Modules
TypeScript also supports ECMAScript 6 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 6 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD).
TypeScript also supports ECMAScript 2015 modules, which are files that contain top-level *export* and *import* directives. For this type of module the TypeScript compiler can emit both ECMAScript 2015 compliant code and down-level ECMAScript 3 or 5 compliant code for a variety of module loading systems, including CommonJS, Asynchronous Module Definition (AMD), and Universal Module Definition (UMD).
<br/>
# <a name="2"/>2 Basic Concepts
The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification.
The remainder of this document is the formal specification of the TypeScript programming language and is intended to be read as an adjunct to the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition). This document describes the syntactic grammar added by TypeScript along with the compile-time processing and type checking performed by the TypeScript compiler, but it only minimally discusses the run-time behavior of programs since that is covered by the ECMAScript specification.
## <a name="2.1"/>2.1 Grammar Conventions
@@ -866,7 +869,7 @@ A property name can be any identifier (including a reserved word), a string lite
### <a name="2.2.3"/>2.2.3 Computed Property Names
ECMAScript 6 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form
ECMAScript 2015 permits object literals and classes to declare members with computed property names. A computed property name specifies an expression that computes the actual property name at run-time. Because the final property name isn't known at compile-time, TypeScript can only perform limited checks for entities declared with computed property names. However, a subset of computed property names known as ***well-known symbols*** can be used anywhere a *PropertyName* is expected, including property names within types. A computed property name is a well-known symbol if it is of the form
```TypeScript
[ Symbol . xxx ]
@@ -884,6 +887,8 @@ interface Iterable<T> {
}
```
*TODO: Update to reflect treatment of [computed property names with literal expressions](https://github.com/Microsoft/TypeScript/pull/5535)*.
## <a name="2.3"/>2.3 Declarations
Declarations introduce names in their associated ***declaration spaces***. A name must be unique in its declaration space and can denote a ***value***, a ***type***, or a ***namespace***, or some combination thereof. Effectively, a single name can have as many as three distinct meanings. For example:
@@ -913,7 +918,7 @@ Declarations introduce the following meanings for the name they declare:
* A variable, parameter, function, generator, member variable, member function, member accessor, or enum member declaration introduces a value meaning.
* An interface, type alias, or type parameter declaration introduces a type meaning.
* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class instance type).
* A class declaration introduces a value meaning (the constructor function) and a type meaning (the class type).
* An enum declaration introduces a value meaning (the enum instance) and a type meaning (the enum type).
* A namespace declaration introduces a namespace meaning (the type and namespace container) and, if the namespace is instantiated (section [10.1](#10.1)), a value meaning (the namespace instance).
* An import or export declaration introduces the meaning(s) of the imported or exported entity.
@@ -996,7 +1001,9 @@ When an identifier is resolved as a *TypeName* (section [3.8.2](#3.8.2)), only n
When an identifier is resolved as a *NamespaceName* (section [3.8.2](#3.8.2)), only names in scope with a namespace meaning are considered and other names are ignored.
Note that class members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`.
*TODO: [Include specific rules for alias resolution](https://github.com/Microsoft/TypeScript/issues/3158)*.
Note that class and interface members are never directly in scope—they can only be accessed by applying the dot ('.') operator to a class or interface instance. This even includes members of the current instance in a constructor or member function, which are accessed by applying the dot operator to `this`.
As the rules above imply, locally declared entities in a namespace are closer in scope than exported entities declared in other namespace declarations for the same namespace. For example:
@@ -1121,7 +1128,7 @@ var c = abc.charAt(2); // Property of String interface
The Symbol primitive type corresponds to the similarly named JavaScript primitive type and represents unique tokens that may be used as keys for object properties.
The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 6 environments.
The `symbol` keyword references the Symbol primitive type. Symbol values are obtained using the global object 'Symbol' which has a number of methods and properties and can be invoked as a function. In particular, the global object 'Symbol' defines a number of well-known symbols ([2.2.3](#2.2.3)) that can be used in a manner similar to identifiers. Note that the 'Symbol' object is available only in ECMAScript 2015 environments.
For purposes of determining type relationships (section [3.11](#3.11)) and accessing properties (section [4.13](#4.13)), the Symbol primitive type behaves as an object type with the same properties as the global interface type 'Symbol'.
@@ -1186,6 +1193,8 @@ Specialized signatures (section [3.9.2.4](#3.9.2.4)) permit string literals to b
All string literal types are subtypes of the String primitive type.
*TODO: Update to reflect [expanded support for string literal types](https://github.com/Microsoft/TypeScript/pull/5185)*.
## <a name="3.3"/>3.3 Object Types
Object types are composed from properties, call signatures, construct signatures, and index signatures, collectively called members.
@@ -1323,7 +1332,7 @@ x = "hello"; // Ok
x = 42; // Ok
x = test; // Error, boolean not assignable
x = test ? 5 : "five"; // Ok
x = test ? 0 : false; // Error, number | boolean not asssignable
x = test ? 0 : false; // Error, number | boolean not assignable
```
it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`:
@@ -1352,7 +1361,7 @@ var b = x.b; // b has type number
var c = x.c; // Error, no property c in union type
```
Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'A' has a property 'c'.
Note that 'x.a' has a union type because the type of 'a' is different in 'A' and 'B', whereas 'x.b' simply has type number because that is the type of 'b' in both 'A' and 'B'. Also note that there is no property 'x.c' because only 'B' has a property 'c'.
When used as a contextual type (section [4.23](#4.23)), a union type has those members that are present in any of its constituent types, with types that are unions of the respective members in the constituent types. Specifically, a union type used as a contextual type has the apparent members defined in section [3.11.1](#3.11.1), except that a particular member need only be present in one or more constituent types instead of all constituent types.
@@ -1437,7 +1446,7 @@ Type parameter names must be unique. A compile-time error occurs if two or more
The scope of a type parameter extends over the entire declaration with which the type parameter list is associated, with the exception of static member declarations in classes.
Each type parameter has an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Omitting a constraint or specifying type `any` as the constraint corresponds to specifying the empty object type `{}`. Type parameters declared in a particular type parameter list may not be referenced in constraints in that type parameter list.
A type parameter may have an associated type parameter ***constraint*** that establishes an upper bound for type arguments. Type parameters may be referenced in type parameter constraints within the same type parameter list, including even constraint declarations that occur to the left of the type parameter.
The ***base constraint*** of a type parameter *T* is defined as follows:
@@ -1448,15 +1457,21 @@ The ***base constraint*** of a type parameter *T* is defined as follows:
In the example
```TypeScript
interface G<T, U extends Function> {
f<V extends U>(x: V): V;
}
interface G<T, U extends V, V extends Function> { }
```
the base constraint of 'T' is the empty object type, and the base constraint of 'U' and 'V' is 'Function'.
the base constraint of 'T' is the empty object type and the base constraint of 'U' and 'V' is 'Function'.
For purposes of determining type relationships (section [3.11](#3.11)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)), type parameters appear to have the members of their base constraint, but no other members.
It is an error for a type parameter to directly or indirectly be a constraint for itself. For example, both of the following declarations are invalid:
```TypeScript
interface A<T extends T> { }
interface B<T extends U, U extends T> { }
```
### <a name="3.6.2"/>3.6.2 Type Argument Lists
A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list of type arguments enclosed in angle brackets and separated by commas. Similarly, a call (section [4.15](#4.15)) to a generic function may explicitly include a type argument list instead of relying on type inference.
@@ -1471,7 +1486,7 @@ A type reference (section [3.8.2](#3.8.2)) to a generic type must include a list
&emsp;&emsp;*TypeArgument:*
&emsp;&emsp;&emsp;*Type*
Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument is required to ***satisfy*** the constraint of its corresponding type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters.
Type arguments correspond one-to-one with type parameters of the generic type or function being referenced. A type argument list is required to specify exactly one type argument for each corresponding type parameter, and each type argument for a constrained type parameter is required to ***satisfy*** the constraint of that type parameter. A type argument satisfies a type parameter constraint if the type argument is assignable to (section [3.11.4](#3.11.4)) the constraint type once type arguments are substituted for type parameters.
Given the declaration
@@ -1483,6 +1498,33 @@ a type reference of the form 'G&lt;A, B>' places no requirements on 'A' but requ
The process of substituting type arguments for type parameters in a generic type or generic signature is known as ***instantiating*** the generic type or signature. Instantiation of a generic type or signature can fail if the supplied type arguments do not satisfy the constraints of their corresponding type parameters.
### <a name="3.6.3"/>3.6.3 This-types
Every class and interface has a ***this-type*** that represents the actual type of instances of the class or interface within the declaration of the class or interface. The this-type is referenced using the keyword `this` in a type position. Within instance methods and constructors of a class, the type of the expression `this` (section [4.2](#4.2)) is the this-type of the class.
Classes and interfaces support inheritance and therefore the instance represented by `this` in a method isn't necessarily an instance of the containing class—it may in fact be an instance of a derived class or interface. To model this relationship, the this-type of a class or interface is classified as a type parameter. Unlike other type parameters, it is not possible to explicitly pass a type argument for a this-type. Instead, in a type reference to a class or interface type, the type reference *itself* is implicitly passed as a type argument for the this-type. For example:
```TypeScript
class A {
foo() {
return this;
}
}
class B extends A {
bar() {
return this;
}
}
let b: B;
let x = b.foo().bar(); // Fluent pattern works, type of x is B
```
In the declaration of `b` above, the type reference `B` is itself passed as a type argument for B's this-type. Thus, the referenced type is an instantiation of class `B` where all occurrences of the type `this` are replaced with `B`, and for that reason the `foo` method of `B` actually returns `B` (as opposed to `A`).
The this-type of a given class or interface type *C* implicitly has a constraint consisting of a type reference to *C* with *C*'s own type parameters passed as type arguments and with that type reference passed as the type argument for the this-type.
## <a name="3.7"/>3.7 Named Types
Classes, interfaces, enums, and type aliases are ***named types*** that are introduced through class declarations (section [8.1](#8.1)), interface declarations (section [7.1](#7.1)), enum declarations ([9.1](#9.1)), and type alias declarations (section [3.10](#3.10)). Classes, interfaces, and type aliases may have type parameters and are then called ***generic types***. Conversely, named types without type parameters are called ***non-generic types***.
@@ -1511,21 +1553,6 @@ is indistinguishable from the type
{ first: string; second: Entity; }
```
### <a name="3.7.1"/>3.7.1 Instance Types
Each class and interface has an associated actual type known as the ***instance type***. For a non-generic class or interface, the instance type is simply a type reference to the class or interface. For a generic class or interface, the instance type is an instantiation of the generic type where each of the type arguments is the corresponding type parameter. Since the instance type uses the type parameters it can be used only where the type parameters are in scope—that is, inside the declaration of the class or interface. Within the constructor and instance member functions of a class, the type of `this` is the instance type of the class.
The following example illustrates the concept of an instance type:
```TypeScript
class G<T> { // Introduce type parameter T
self: G<T>; // Use T as type argument to form instance type
f() {
this.self = this; // self and this are both of type G<T>
}
}
```
## <a name="3.8"/>3.8 Specifying Types
Types are specified either by referencing their keyword or name, or by writing object type literals, array type literals, tuple type literals, function type literals, constructor type literals, or type queries.
@@ -1550,7 +1577,8 @@ Types are specified either by referencing their keyword or name, or by writing o
&emsp;&emsp;&emsp;*ObjectType*
&emsp;&emsp;&emsp;*ArrayType*
&emsp;&emsp;&emsp;*TupleType*
&emsp;&emsp;&emsp;*TypeQuery*
&emsp;&emsp;&emsp;*TypeQuery*
&emsp;&emsp;&emsp;*ThisType*
&emsp;&emsp;*ParenthesizedType:*
&emsp;&emsp;&emsp;`(`&emsp;*Type*&emsp;`)`
@@ -1711,7 +1739,7 @@ A union type literal is written as a sequence of types separated by vertical bar
&emsp;&emsp;*UnionType:*
&emsp;&emsp;&emsp;*UnionOrIntersectionOrPrimaryType*&emsp;`|`&emsp;*IntersectionOrPrimaryType*
A union typle literal references a union type (section [3.4](#3.4)).
A union type literal references a union type (section [3.4](#3.4)).
### <a name="3.8.7"/>3.8.7 Intersection Type Literals
@@ -1720,7 +1748,7 @@ An intersection type literal is written as a sequence of types separated by ampe
&emsp;&emsp;*IntersectionType:*
&emsp;&emsp;&emsp;*IntersectionOrPrimaryType*&emsp;`&`&emsp;*PrimaryType*
An intersection typle literal references an intersection type (section [3.5](#3.5)).
An intersection type literal references an intersection type (section [3.5](#3.5)).
### <a name="3.8.8"/>3.8.8 Function Type Literals
@@ -1804,6 +1832,41 @@ var h: () => typeof h;
Here, 'g' and 'g.x' have the same recursive type, and likewise 'h' and 'h()' have the same recursive type.
### <a name="3.8.11"/>3.8.11 This-Type References
The `this` keyword is used to reference the this-type (section [3.6.3](#3.6.3)) of a class or interface.
&emsp;&emsp;*ThisType:*
&emsp;&emsp;&emsp;`this`
The meaning of a *ThisType* depends on the closest enclosing *FunctionDeclaration*, *FunctionExpression*, *PropertyDefinition*, *ClassElement*, or *TypeMember*, known as the root declaration of the *ThisType*, as follows:
* When the root declaration is an instance member or constructor of a class, the *ThisType* references the this-type of that class.
* When the root declaration is a member of an interface type, the *ThisType* references the this-type of that interface.
* Otherwise, the *ThisType* is an error.
Note that in order to avoid ambiguities it is not possible to reference the this-type of a class or interface in a nested object type literal. In the example
```TypeScript
interface ListItem {
getHead(): this;
getTail(): this;
getHeadAndTail(): { head: this, tail: this }; // Error
}
```
the `this` references on the last line are in error because their root declarations are not members of a class or interface. The recommended way to reference the this-type of an outer class or interface in an object type literal is to declare an intermediate generic type and pass `this` as a type argument. For example:
```TypeScript
type HeadAndTail<T> = { head: T, tail: T };
interface ListItem {
getHead(): this;
getTail(): this;
getHeadAndTail(): HeadAndTail<this>;
}
```
## <a name="3.9"/>3.9 Specifying Members
The members of an object type literal (section [3.8.3](#3.8.3)) are specified as a combination of property, call, construct, index, and method signatures.
@@ -1931,6 +1994,8 @@ A parameter can be marked optional by following its name or binding pattern with
*TODO: Update to reflect [binding parameter cannot be optional in implementation signature](https://github.com/Microsoft/TypeScript/issues/2797)*.
*TODO: Update to reflect [required parameters support initializers](https://github.com/Microsoft/TypeScript/pull/4022)*.
#### <a name="3.9.2.3"/>3.9.2.3 Return Type
If present, a call signature's return type annotation specifies the type of the value computed and returned by a call operation. A `void` return type annotation is used to indicate that a function has no return value.
@@ -2122,8 +2187,9 @@ Types in TypeScript have identity, subtype, supertype, and assignment compatibil
The ***apparent members*** of a type are the members observed in subtype, supertype, and assignment compatibility relationships, as well as in the type checking of property accesses (section [4.13](#4.13)), `new` operations (section [4.14](#4.14)), and function calls (section [4.15](#4.15)). The apparent members of a type are determined as follows:
* The apparent members of the primitive types Number, Boolean, and String are the apparent members of the global interface types 'Number', 'Boolean', and 'String' respectively.
* The apparent members of an enum type are the apparent members of the global interface type 'Number'.
* The apparent members of the primitive type Number and all enum types are the apparent members of the global interface type 'Number'.
* The apparent members of the primitive type Boolean are the apparent members of the global interface type 'Boolean'.
* The apparent members of the primitive type String and all string literal types are the apparent members of the global interface type 'String'.
* The apparent members of a type parameter are the apparent members of the constraint (section [3.6.1](#3.6.1)) of that type parameter.
* The apparent members of an object type *T* are the combination of the following:
* The declared and/or inherited members of *T*.
@@ -2239,7 +2305,7 @@ Types are required to be assignment compatible in certain circumstances, such as
* *S* or *T* is the Any type.
* *S* is the Undefined type.
* *S* is the Null type and *T* is not the Undefined type.
* *S* or *T* is an enum type and* *the other is the primitive type Number.
* *S* or *T* is an enum type and the other is the primitive type Number.
* *S* is a string literal type and *T* is the primitive type String.
* *S* is a union type and each constituent type of *S* is assignable to *T*.
* *S* is an intersection type and at least one constituent type of *S* is assignable to *T*.
@@ -2258,8 +2324,8 @@ Types are required to be assignment compatible in certain circumstances, such as
* *M* has a rest parameter or the number of non-optional parameters in *N* is less than or equal to the total number of parameters in *M*,
* for parameter positions that are present in both signatures, each parameter type in *N* is assignable to or from the corresponding parameter type in *M*, and
* the result type of *M* is Void, or the result type of *N* is assignable to that of *M*.
* *M* is a string index signature of type *U* and *S* has an apparent string index signature of a type that is assignable to *U*.
* *M* is a numeric index signature of type *U* and *S* has an apparent string or numeric index signature of a type that is assignable to *U*.
* *M* is a string index signature of type *U*, and *U* is the Any type or *S* has an apparent string index signature of a type that is assignable to *U*.
* *M* is a numeric index signature of type *U*, and *U* is the Any type or *S* has an apparent string or numeric index signature of a type that is assignable to *U*.
When comparing call or construct signatures, parameter names are ignored and rest parameters correspond to an unbounded expansion of optional parameters of the rest parameter element type.
@@ -2366,6 +2432,8 @@ In certain contexts, inferences for a given set of type parameters are made *fro
When comparing call or construct signatures, signatures in *S* correspond to signatures of the same kind in *T* pairwise in declaration order. If *S* and *T* have different numbers of a given kind of signature, the excess *first* signatures in declaration order of the longer list are ignored.
*TODO: Update to reflect [improved union and intersection type inference](https://github.com/Microsoft/TypeScript/pull/5738)*.
### <a name="3.11.8"/>3.11.8 Recursive Types
Classes and interfaces can reference themselves in their internal structure, in effect creating recursive types with infinite nesting. For example, the type
@@ -2443,7 +2511,7 @@ Expressions are classified as ***values*** or ***references***. References are t
The type of `this` in an expression depends on the location in which the reference takes place:
* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the class instance type of the containing class.
* In a constructor, instance member function, instance member accessor, or instance member variable initializer, `this` is of the this-type (section [3.6.3](#3.6.3)) of the containing class.
* In a static member function or static member accessor, the type of `this` is the constructor function type of the containing class.
* In a function declaration or a function expression, `this` is of type Any.
* In the global namespace, `this` is of type Any.
@@ -2569,6 +2637,8 @@ The resulting type an array literal expression is determined as follows:
A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs.
*TODO: The compiler currently doesn't support applying the spread operator to a string (to spread the individual characters of a string into a string array). This will eventually be allowed, but only when the code generation target is ECMAScript 2015 or later*.
*TODO: Document spreading an [iterator](https://github.com/Microsoft/TypeScript/pull/2498) into an array literal*.
The rules above mean that an array literal is always of an array type, unless it is contextually typed by a tuple-like type. For example
@@ -2619,7 +2689,7 @@ A super call invokes the constructor of the base class on the instance reference
The type of a super call expression is Void.
The JavaScript code generated for a super call is specified in section [8.6.2](#8.6.2).
The JavaScript code generated for a super call is specified in section [8.7.2](#8.7.2).
### <a name="4.9.2"/>4.9.2 Super Property Access
@@ -2632,7 +2702,7 @@ Super property accesses are not permitted in other contexts, and it is not possi
Super property accesses are typically used to access overridden base class member functions from derived class member functions. For an example of this, see section [8.4.2](#8.4.2).
The JavaScript code generated for a super property access is specified in section [8.6.2](#8.6.2).
The JavaScript code generated for a super property access is specified in section [8.7.2](#8.7.2).
*TODO: Update section to include [bracket notation in super property access](https://github.com/Microsoft/TypeScript/issues/3970)*.
@@ -2777,7 +2847,7 @@ object . name
where *object* is an expression and *name* is an identifier (including, possibly, a reserved word), is used to access the property with the given name on the given object. A dot notation property access is processed as follows at compile-time:
* If *object* is of type Any, any *name* is permitted and the property access is of type Any.
* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the type of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2).
* Otherwise, if *name* denotes an accessible apparent property (section [3.11.1](#3.11.1)) in the widened type (section [3.12](#3.12)) of *object*, the property access is of the type of that property. Public members are always accessible, but private and protected members of a class have restricted accessibility, as described in [8.2.2](#8.2.2).
* Otherwise, the property access is invalid and a compile-time error occurs.
A bracket notation property access of the form
@@ -2892,7 +2962,7 @@ Given a signature &lt; *T<sub>1</sub>* , *T<sub>2</sub>* , … , *T<sub>n</sub>*
Type argument inference produces a set of candidate types for each type parameter. Given a type parameter *T* and set of candidate types, the actual inferred type argument is determined as follows:
* If the set of candidate argument types is empty, the inferred type argument for *T* is *T*'s constraint.
* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint.
* Otherwise, if at least one of the candidate types is a supertype of all of the other candidate types, let *C* denote the widened form (section [3.12](#3.12)) of the first such candidate type. If *C* satisfies *T*'s constraint, the inferred type argument for *T* is *C*. Otherwise, the inferred type argument for *T* is *T*'s constraint.
* Otherwise, if no candidate type is a supertype of all of the other candidate types, type inference has fails and no type argument is inferred for *T*.
In order to compute candidate types, the argument list is processed as follows:
@@ -3030,6 +3100,8 @@ if (shape instanceof Circle) {
}
```
*TODO: Document [as operator](https://github.com/Microsoft/TypeScript/pull/3564)*.
## <a name="4.17"/>4.17 JSX Expressions
*TODO: Document [JSX expressions](https://github.com/Microsoft/TypeScript/issues/3203)*.
@@ -3106,6 +3178,8 @@ These operators require their operands to be of type Any, the Number primitive t
|String||||||
|Other||||||
*TODO: Document the [exponentation operator](https://github.com/Microsoft/TypeScript/issues/4812)*.
### <a name="4.19.2"/>4.19.2 The + operator
The binary + operator requires both operands to be of the Number primitive type or an enum type, or at least one of the operands to be of type Any or the String primitive type. Operands of an enum type are treated as having the primitive type Number. If one operand is the `null` or `undefined` value, it is treated as having the type of the other operand. If both operands are of the Number primitive type, the result is of the Number primitive type. If one or both operands are of the String primitive type, the result is of the String primitive type. Otherwise, the result is of type Any.
@@ -3218,7 +3292,7 @@ is subject to the same requirements, and produces a value of the same type, as t
### <a name="4.21.1"/>4.21.1 Destructuring Assignment
A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 6 specification.
A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern as defined by the *AssignmentPattern* production in the ECMAScript 2015 specification.
In a destructuring assignment expression, the type of the expression on the right must be assignable to the assignment target on the left. An expression of type *S* is considered assignable to an assignment target *V* if one of the following is true:
@@ -3233,9 +3307,11 @@ In a destructuring assignment expression, the type of the expression on the righ
* *S* is a tuple-like type (section [3.3.3](#3.3.3)) with a property named *N* of a type that is assignable to the target given in *E*, where *N* is the numeric index of *E* in the array assignment pattern, or
* *S* is not a tuple-like type and the numeric index signature type of *S* is assignable to the target given in *E*.
*TODO: [Update to specify behavior when assignment element E is a rest element](https://github.com/Microsoft/TypeScript/issues/2713)*.
In an assignment property or element that includes a default value, the type of the default value must be assignable to the target given in the assignment property or element.
When the output target is ECMAScript 6 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment
When the output target is ECMAScript 2015 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment
```TypeScript
var x = 1;
@@ -3360,6 +3436,8 @@ In the rules above, when a narrowing operation would remove all constituent type
Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties. Also note that it is possible to defeat a type guard by calling a function that changes the type of the guarded variable.
*TODO: Document [user defined type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*.
In the example
```TypeScript
@@ -3432,7 +3510,7 @@ This chapter describes the static type checking TypeScript provides for JavaScri
## <a name="5.1"/>5.1 Blocks
Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 6 grammar).
Blocks are extended to include local interface, type alias, and enum declarations (classes are already included by the ECMAScript 2015 grammar).
&emsp;&emsp;*Declaration:* *( Modified )*
&emsp;&emsp;&emsp;…
@@ -3549,7 +3627,9 @@ The type *T* associated with a binding element is determined as follows:
When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element.
When the output target is ECMAScript 6 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code.
*TODO: Update rules to reflect [improved checking of destructuring with literal initializers](https://github.com/Microsoft/TypeScript/pull/4598)*.
When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code.
When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form
@@ -3805,7 +3885,7 @@ function g(x: number) {
the inferred return type for 'f' and 'g' is Any because the functions reference themselves through a cycle with no return type annotations. Adding an explicit return type 'number' to either breaks the cycle and causes the return type 'number' to be inferred for the other.
An explicitly typed function whose return type isn't the Void or the Any type must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement.
An explicitly typed function whose return type isn't the Void type, the Any type, or a union type containing the Void or Any type as a constituent must have at least one return statement somewhere in its body. An exception to this rule is if the function implementation consists of a single 'throw' statement.
The type of 'this' in a function implementation is the Any type.
@@ -3855,7 +3935,7 @@ The type of local introduced in a destructuring parameter declaration is determi
* Otherwise, if the parameter is a rest parameter, *T* is `any[]`.
* Otherwise, *T* is `any`.
When the output target is ECMAScript 6 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations.
When the output target is ECMAScript 2015 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations.
The example
@@ -3965,9 +4045,13 @@ where *Parameter* is the parameter name and *Default* is the default value expre
*TODO: Document [generator functions](https://github.com/Microsoft/TypeScript/issues/2873)*.
## <a name="6.8"/>6.8 Type Guard Functions
## <a name="6.8"/>6.8 Asynchronous Functions
*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007)*.
*TODO: Document [asynchronous functions](https://github.com/Microsoft/TypeScript/issues/1664)*.
## <a name="6.9"/>6.9 Type Guard Functions
*TODO: Document [type guard functions](https://github.com/Microsoft/TypeScript/issues/1007), including [this type predicates](https://github.com/Microsoft/TypeScript/pull/5906)*.
<br/>
@@ -4016,7 +4100,7 @@ The following constraints must be satisfied by an interface declaration or other
* An interface cannot declare a property with the same name as an inherited private or protected property.
* Inherited properties with the same name must be identical (section [3.11.2](#3.11.2)).
* All properties of the interface must satisfy the constraints implied by the index signatures of the interface as specified in section [3.9.4](#3.9.4).
* The instance type (section [3.7.1](#3.7.1)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references.
* The this-type (section [3.6.3](#3.6.3)) of the declared interface must be assignable (section [3.11.4](#3.11.4)) to each of the base type references.
An interface is permitted to inherit identical members from multiple base types and will in that case only contain one occurrence of each particular member.
@@ -4090,6 +4174,8 @@ interface Document {
Note that the members of the last interface declaration appear first in the merged declaration. Also note that the relative order of members declared in the same interface body is preserved.
*TODO: Document [class and interface declaration merging](https://github.com/Microsoft/TypeScript/pull/3333)*.
## <a name="7.3"/>7.3 Interfaces Extending Classes
When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. When a class containing private or protected members is the base type of an interface type, that interface type can only be implemented by that class or a descendant class. For example:
@@ -4193,13 +4279,13 @@ var Point: {
};
```
The context in which a class is referenced distinguishes between the class instance type and the constructor function. For example, in the assignment statement
The context in which a class is referenced distinguishes between the class type and the constructor function. For example, in the assignment statement
```TypeScript
var p: Point = new Point(10, 20);
```
the identifier 'Point' in the type annotation refers to the class instance type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object.
the identifier 'Point' in the type annotation refers to the class type, whereas the identifier 'Point' in the `new` expression refers to the constructor function object.
### <a name="8.1.1"/>8.1.1 Class Heritage Specification
@@ -4225,7 +4311,7 @@ The following constraints must be satisfied by the class heritage specification
* If present, the type reference specified in the `extends` clause must denote a class type. Furthermore, the *TypeName* part of the type reference is required to be a reference to the class constructor function when evaluated as an expression.
* A class declaration may not, directly or indirectly, specify a base class that originates in the same declaration. In other words a class cannot, directly or indirectly, be a base class of itself, regardless of type arguments.
* The instance type (section [3.7.1](#3.7.1)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause.
* The this-type (section [3.6.3](#3.6.3)) of the declared class must be assignable (section [3.11.4](#3.11.4)) to the base type reference and each of the type references listed in the `implements` clause.
* The constructor function type created by the class declaration must be assignable to the base class constructor function type, ignoring construct signatures.
The following example illustrates a situation in which the first rule above would be violated:
@@ -4266,7 +4352,7 @@ The members of a class consist of the members introduced through member declarat
Members are either ***instance members*** or ***static members***.
Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated instance type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the instance type (section [3.7.1](#3.7.1)) of the class.
Instance members are members of the class type (section [8.2.4](#8.2.4)) and its associated this-type. Within constructors, instance member functions, and instance member accessors, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of the class.
Static members are declared using the `static` modifier and are members of the constructor function type (section [8.2.5](#8.2.5)). Within static member functions and static member accessors, the type of `this` is the constructor function type.
@@ -4280,7 +4366,7 @@ Public property members can be accessed everywhere without restrictions.
Private property members can be accessed only within their declaring class. Specifically, a private member *M* declared in a class *C* can be accessed only within the class body of *C*.
Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments.
Protected property members can be accessed only within their declaring class and classes derived from their declaring class, and a protected instance property member must be accessed *through* an instance of the enclosing class or a subclass thereof. Specifically, a protected member *M* declared in a class *C* can be accessed only within the class body of *C* or the class body of a class derived from *C*. Furthermore, when a protected instance member *M* is accessed in a property access *E*`.`*M* within the body of a class *D*, the type of *E* is required to be *D* or a type that directly or indirectly has *D* as a base type, regardless of type arguments.
Private and protected accessibility is enforced only at compile-time and serves as no more than an *indication of intent*. Since JavaScript provides no mechanism to create private and protected properties on an object, it is not possible to enforce the private and protected modifiers in dynamic code at run-time. For example, private and protected accessibility can be defeated by changing an object's static type to Any and accessing the member dynamically.
@@ -4326,14 +4412,14 @@ An index member in a derived class is said to override an index member in a base
### <a name="8.2.4"/>8.2.4 Class Types
A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and member functions of a class, the type of `this` is the instance type (section [3.7.1](#3.7.1)) of this class type. The class type has the following members:
A class declaration declares a new named type (section [3.7](#3.7)) called a class type. Within the constructor and instance member functions of a class, the type of `this` is the this-type (section [3.6.3](#3.6.3)) of that class type. The class type has the following members:
* A property for each instance member variable declaration in the class body.
* A property of a function type for each instance member function declaration in the class body.
* A property for each uniquely named instance member accessor declaration in the class body.
* A property for each constructor parameter declared with a `public`, `private`, or `protected` modifier.
* An index signature for each instance index member declaration in the class body.
* All base class instance type property or index members that are not overridden in the class.
* All base class instance property or index members that are not overridden in the class.
All instance property members (including those that are private or protected) of a class must satisfy the constraints implied by the index members of the class as specified in section [3.9.4](#3.9.4).
@@ -4353,7 +4439,7 @@ class B extends A {
}
```
the instance type of 'A' is
the class type of 'A' is equivalent to
```TypeScript
interface A {
@@ -4363,7 +4449,7 @@ interface A {
}
```
and the instance type of 'B' is
and the class type of 'B' is equivalent to
```TypeScript
interface B {
@@ -4374,16 +4460,16 @@ interface B {
}
```
Note that static declarations in a class do not contribute to the class type and its instance type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'.
Note that static declarations in a class do not contribute to the class type—rather, static declarations introduce properties on the constructor function object. Also note that the declaration of 'g' in 'B' overrides the member inherited from 'A'.
### <a name="8.2.5"/>8.2.5 Constructor Function Types
The type of the constructor function introduced by a class declaration is called the constructor function type. The constructor function type has the following members:
* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class and returning the instance type of the class.
* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class and returning the instance type of the class.
* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class and returning the instance type of the class.
* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class and returning the instance type of the class.
* If the class contains no constructor declaration and has no base class, a single construct signature with no parameters, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
* If the class contains no constructor declaration and has a base class, a set of construct signatures with the same parameters as those of the base class constructor function type following substitution of type parameters with the type arguments specified in the base class type reference, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
* If the class contains a constructor declaration with no overloads, a construct signature with the parameter list of the constructor implementation, having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
* If the class contains a constructor declaration with overloads, a set of construct signatures with the parameter lists of the overloads, all having the same type parameters as the class (if any) and returning an instantiation of the class type with those type parameters passed as type arguments.
* A property for each static member variable declaration in the class body.
* A property of a function type for each static member function declaration in the class body.
* A property for each uniquely named static member accessor declaration in the class body.
@@ -4428,7 +4514,7 @@ var TwoArrays: {
}
```
Note that the construct signatures in the constructor function types have the same type parameters as their class and return the instance type of their class. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type.
Note that each construct signature in the constructor function types has the same type parameters as its class and returns an instantiation of its class with those type parameters passed as type arguments. Also note that when a derived class doesn't declare a constructor, type arguments from the base class reference are substituted before construct signatures are propagated from the base constructor function type to the derived constructor function type.
## <a name="8.3"/>8.3 Constructor Declarations
@@ -4446,7 +4532,7 @@ When a class has constructor overloads, the overloads determine the construct si
When a class has both constructor overloads and a constructor implementation, the overloads must precede the implementation and all of the declarations must be consecutive with no intervening grammatical elements.
The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the instance type of the class.
The function body of a constructor is permitted to contain return statements. If return statements specify expressions, those expressions must be of types that are assignable to the this-type (section [3.6.3](#3.6.3)) of the class.
The type parameters of a generic class are in scope and accessible in a constructor declaration.
@@ -4478,6 +4564,8 @@ class Point {
}
```
A parameter property declaration may declare an optional parameter (by including a question mark or a default value), but the property introduced by such a declaration is always considered a required property (section [3.3.6](#3.3.6)).
### <a name="8.3.2"/>8.3.2 Super Calls
Super calls (section [4.9.1](#4.9.1)) are used to call the constructor of the base class. A super call consists of the keyword `super` followed by an argument list enclosed in parentheses. For example:
@@ -4524,7 +4612,7 @@ Property member declarations can be member variable declarations, member functio
&emsp;&emsp;&emsp;*MemberFunctionDeclaration*
&emsp;&emsp;&emsp;*MemberAccessorDeclaration*
Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class instance type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name.
Member declarations without a `static` modifier are called instance member declarations. Instance property member declarations declare properties in the class type (section [8.2.4](#8.2.4)), and must specify names that are unique among all instance property member and parameter property declarations in the containing class, with the exception that instance get and set accessor declarations may pairwise specify the same name.
Member declarations with a `static` modifier are called static member declarations. Static property member declarations declare properties in the constructor function type (section [8.2.5](#8.2.5)), and must specify names that are unique among all static property member declarations in the containing class, with the exception that static get and set accessor declarations may pairwise specify the same name.
@@ -4549,7 +4637,7 @@ class Point {
}
```
The class instance type 'Point' has the members:
The class type 'Point' has the members:
```TypeScript
interface Point {
@@ -4578,7 +4666,7 @@ A member variable declaration declares an instance member variable or a static m
The type associated with a member variable declaration is determined in the same manner as an ordinary variable declaration (see section [5.2](#5.2)).
An instance member variable declaration introduces a member in the class instance type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the class instance type.
An instance member variable declaration introduces a member in the class type and optionally initializes a property on instances of the class. Initializers in instance member variable declarations are executed once for every new instance of the class and are equivalent to assignments to properties of `this` in the constructor. In an initializer expression for an instance member variable, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class.
A static member variable declaration introduces a property in the constructor function type and optionally initializes a property on the constructor function object. Initializers in static member variable declarations are executed once when the containing script or module is loaded.
@@ -4625,7 +4713,7 @@ A member function declaration is processed in the same manner as an ordinary fun
All declarations for the same member function must specify the same accessibility (public, private, or protected) and kind (instance or static).
An instance member function declaration declares a property in the class instance type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the class instance type.
An instance member function declaration declares a property in the class type and assigns a function object to a property on the prototype object of the class. In the body of an instance member function declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class.
A static member function declaration declares a property in the constructor function type and assigns a function object to a property on the constructor function object. In the body of a static member function declaration, the type of `this` is the constructor function type.
@@ -4691,23 +4779,23 @@ Get and set accessors are processed in the same manner as in an object literal (
Accessors for the same member name must specify the same accessibility.
An instance member accessor declaration declares a property in the class instance type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the class instance type.
An instance member accessor declaration declares a property in the class type and defines a property on the prototype object of the class with a get or set accessor. In the body of an instance member accessor declaration, `this` is of the this-type (section [3.6.3](#3.6.3)) of the class.
A static member accessor declaration declares a property in the constructor function type and defines a property on the constructor function object of the class with a get or set accessor. In the body of a static member accessor declaration, the type of `this` is the constructor function type.
Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.6.1](#8.6.1).
Get and set accessors are emitted as calls to 'Object.defineProperty' in the generated JavaScript, as described in section [8.7.1](#8.7.1).
### <a name="8.4.4"/>8.4.4 Dynamic Property Declarations
If the *PropertyName* of a property member declaration is a computed property name that doesn't denote a well-known symbol ([2.2.3](#2.2.3)), the construct is considered a ***dynamic property declaration***. The following rules apply to dynamic property declarations:
* A dynamic property declaration does not introduce a property in the class instance type or constructor function type.
* A dynamic property declaration does not introduce a property in the class type or constructor function type.
* The property name expression of a dynamic property assignment must be of type Any or the String, Number, or Symbol primitive type.
* The name associated with a dynamic property declarations is considered to be a numeric property name if the property name expression is of type Any or the Number primitive type.
## <a name="8.5"/>8.5 Index Member Declarations
An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class instance type.
An index member declaration introduces an index signature (section [3.9.4](#3.9.4)) in the class type.
&emsp;&emsp;*IndexMemberDeclaration:*
&emsp;&emsp;&emsp;*IndexSignature*&emsp;`;`
@@ -4720,11 +4808,15 @@ It is not possible to declare index members for the static side of a class.
Note that it is seldom meaningful to include a string index signature in a class because it constrains all instance properties of the class. However, numeric index signatures can be useful to control the element type when a class is used in an array-like manner.
## <a name="8.6"/>8.6 Code Generation
## <a name="8.6"/>8.6 Decorators
When the output target is ECMAScript 6 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section.
*TODO: Document [decorators](https://github.com/Microsoft/TypeScript/issues/2249)*.
### <a name="8.6.1"/>8.6.1 Classes Without Extends Clauses
## <a name="8.7"/>8.7 Code Generation
When the output target is ECMAScript 2015 or higher, type parameters, implements clauses, accessibility modifiers, and member variable declarations are removed in the emitted code, but otherwise class declarations are emitted as written. When the output target is ECMAScript 3 or 5, more comprehensive rewrites are performed, as described in this section.
### <a name="8.7.1"/>8.7.1 Classes Without Extends Clauses
A class with no `extends` clause generates JavaScript equivalent to the following:
@@ -4828,7 +4920,7 @@ where *MemberName* is the name of the member accessor, *GetAccessorStatements* i
where *MemberName* is the name of the static variable, and *InitializerExpression* is the code generated for the initializer expression.
### <a name="8.6.2"/>8.6.2 Classes With Extends Clauses
### <a name="8.7.2"/>8.7.2 Classes With Extends Clauses
A class with an `extends` clause generates JavaScript equivalent to the following:
@@ -5396,7 +5488,7 @@ This copies a reference to the entity into a property on the namespace instance.
# <a name="11"/>11 Scripts and Modules
TypeScript implements support for ECMAScript 6 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems.
TypeScript implements support for ECMAScript 2015 modules and supports down-level code generation targeting CommonJS, AMD, and other module systems.
## <a name="11.1"/>11.1 Programs and Source Files
@@ -5424,7 +5516,7 @@ When a TypeScript program is compiled, all of the program's source files are pro
The TypeScript compiler automatically determines a source file's dependencies and includes those dependencies in the program being compiled. The determination is made from "reference comments" and module import declarations as follows:
* A comment of the form /// &lt;reference path="…"/> adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
* A comment of the form /// &lt;reference path="…"/> that occurs before the first token in a source file adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
* A module import declaration that specifies a relative module name (section [11.3.1](#11.3.1)) resolves the name relative to the directory of the containing source file. If a source file with the resulting path and file extension '.ts' exists, that file is added as a dependency. Otherwise, if a source file with the resulting path and file extension '.d.ts' exists, that file is added as a dependency.
* A module import declaration that specifies a top-level module name (section [11.3.1](#11.3.1)) resolves the name in a host dependent manner (typically by resolving the name relative to a module name space root or searching for the name in a series of directories). If a source file with extension '.ts' or '.d.ts' corresponding to the reference is located, that file is added as a dependency.
@@ -5539,7 +5631,7 @@ TypeScript supports multiple patterns of JavaScript code generation for modules:
* CommonJS. This format is used by server frameworks such as node.js.
* AMD (Asynchronous Module Definition). This format is used by asynchronous module loaders such as RequireJS.
* UMD (Universal Module Definition). A variation of the AMD format that allows modules to also be loaded by CommonJS loaders.
* System. This format is used to represent ECMAScript 6 semantics with high fidelity in down-level environments.
* System. This format is used to represent ECMAScript 2015 semantics with high fidelity in down-level environments.
The desired module code generation pattern is selected through a compiler option and does not affect the TypeScript source code. Indeed, it is possible to author modules that can be compiled for use both on the server side (e.g. using node.js) and on the client side (using an AMD compliant loader) with no changes to the TypeScript source code.
@@ -5620,7 +5712,7 @@ An import require declaration of the form
import m = require("mod");
```
is equivalent to the ECMAScript 6 import declaration
is equivalent to the ECMAScript 2015 import declaration
```TypeScript
import * as m from "mod";
@@ -5828,16 +5920,17 @@ The 'main' and 'log' example from section [11.3](#11.3) above generates the foll
File main.js:
```TypeScript
var log = require("./log");
log.message("hello");
var log_1 = require("./log");
log_1.message("hello");
```
File log.js:
```TypeScript
exports.message = function(s) {
function message(s) {
console.log(s);
}
}
exports.message = message;
```
A module import declaration is represented in the generated JavaScript as a variable initialized by a call to the 'require' function provided by the module system host. A variable declaration and 'require' call is emitted for a particular imported module only if the imported module, or a local alias (section [10.3](#10.3)) that references the imported module, is referenced as a *PrimaryExpression* somewhere in the body of the importing module. If an imported module is referenced only as a *NamespaceName* or *TypeQueryExpression*, nothing is emitted.
@@ -5850,15 +5943,15 @@ File geometry.ts:
export interface Point { x: number; y: number };
export function point(x: number, y: number): Point {
return { x: x, y: y };
return { x, y };
}
```
File game.ts:
```TypeScript
import g = require("./geometry");
var p = g.point(10, 20);
import * as g from "./geometry";
let p = g.point(10, 20);
```
The 'game' module references the imported 'geometry' module in an expression (through its alias 'g') and a 'require' call is therefore included in the emitted JavaScript:
@@ -5871,8 +5964,8 @@ var p = g.point(10, 20);
Had the 'game' module instead been written to only reference 'geometry' in a type position
```TypeScript
import g = require("./geometry");
var p: g.Point = { x: 10, y: 20 };
import * as g from "./geometry";
let p: g.Point = { x: 10, y: 20 };
```
the emitted JavaScript would have no dependency on the 'geometry' module and would simply be
@@ -5890,8 +5983,8 @@ The "main" and "log" example from above generates the following JavaScript code
File main.js:
```TypeScript
define(["require", "exports", "./log"], function(require, exports, log) {
log.message("hello");
define(["require", "exports", "./log"], function(require, exports, log_1) {
log_1.message("hello");
}
```
@@ -5899,9 +5992,10 @@ File log.js:
```TypeScript
define(["require", "exports"], function(require, exports) {
exports.message = function(s) {
function message(s) {
console.log(s);
}
exports.message = message;
}
```
@@ -5957,7 +6051,7 @@ Ambient function declarations cannot specify a function bodies and do not permit
### <a name="12.1.3"/>12.1.3 Ambient Class Declarations
An ambient class declaration declares a class instance type and a constructor function in the containing declaration space.
An ambient class declaration declares a class type and a constructor function in the containing declaration space.
&emsp;&emsp;*AmbientClassDeclaration:*
&emsp;&emsp;&emsp;`class`&emsp;*BindingIdentifier*&emsp;*TypeParameters<sub>opt</sub>*&emsp;*ClassHeritage*&emsp;`{`&emsp;*AmbientClassBody*&emsp;`}`
@@ -6057,7 +6151,7 @@ declare module "io" {
# <a name="A"/>A Grammar
This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar.
This appendix contains a summary of the grammar found in the main document. As described in section [2.1](#2.1), the TypeScript grammar is a superset of the grammar defined in the [ECMAScript 2015 Language Specification](http://www.ecma-international.org/ecma-262/6.0/) (specifically, the ECMA-262 Standard, 6th Edition) and this appendix lists only productions that are new or modified from the ECMAScript grammar.
## <a name="A.1"/>A.1 Types
@@ -6104,7 +6198,8 @@ This appendix contains a summary of the grammar found in the main document. As d
&emsp;&emsp;&emsp;*ObjectType*
&emsp;&emsp;&emsp;*ArrayType*
&emsp;&emsp;&emsp;*TupleType*
&emsp;&emsp;&emsp;*TypeQuery*
&emsp;&emsp;&emsp;*TypeQuery*
&emsp;&emsp;&emsp;*ThisType*
&emsp;&emsp;*ParenthesizedType:*
&emsp;&emsp;&emsp;`(`&emsp;*Type*&emsp;`)`
@@ -6179,6 +6274,9 @@ This appendix contains a summary of the grammar found in the main document. As d
&emsp;&emsp;&emsp;*IdentifierReference*
&emsp;&emsp;&emsp;*TypeQueryExpression*&emsp;`.`&emsp;*IdentifierName*
&emsp;&emsp;*ThisType:*
&emsp;&emsp;&emsp;`this`
&emsp;&emsp;*PropertySignature:*
&emsp;&emsp;&emsp;*PropertyName*&emsp;`?`*<sub>opt</sub>*&emsp;*TypeAnnotation<sub>opt</sub>*
+6
View File
@@ -0,0 +1,6 @@
# The TypeScript Wiki
To read the wiki, [visit the wiki on GitHub](https://github.com/Microsoft/TypeScript/wiki).
To contribute by filing an issue or sending a pull request, [visit the wiki repository](https://github.com/Microsoft/TypeScript-wiki).
+27
View File
@@ -0,0 +1,27 @@
<!--
Thank you for contributing to TypeScript! Please review this checklist
before submitting your issue.
[ ] Many common issues and suggestions are addressed in the FAQ
https://github.com/Microsoft/TypeScript/wiki/FAQ
[ ] Search for duplicates before logging new issues
https://github.com/Microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue
[ ] Questions are best asked and answered at Stack Overflow
http://stackoverflow.com/questions/tagged/typescript
For bug reports, please include the information below.
__________________________________________________________ -->
**TypeScript Version:**
1.7.5 / 1.8.0-beta / nightly (1.9.0-dev.20160217)
**Code**
```ts
// A self-contained demonstration of the problem follows...
```
**Expected behavior:**
**Actual behavior:**
+4 -3
View File
@@ -1,4 +1,5 @@
# Read this!
# Read This!
These files are not meant to be edited by hand.
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
**These files are not meant to be edited by hand.**
If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory.
Running `jake LKG` will then appropriately update the files in this directory.
+239 -157
View File
File diff suppressed because it is too large Load Diff
+298 -198
View File
File diff suppressed because it is too large Load Diff
+5344
View File
File diff suppressed because it is too large Load Diff
+324 -191
View File
File diff suppressed because it is too large Load Diff
+85 -34
View File
@@ -538,6 +538,7 @@ interface AudioContext extends EventTarget {
destination: AudioDestinationNode;
listener: AudioListener;
sampleRate: number;
state: string;
createAnalyser(): AnalyserNode;
createBiquadFilter(): BiquadFilterNode;
createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;
@@ -594,6 +595,8 @@ interface AudioNode extends EventTarget {
numberOfOutputs: number;
connect(destination: AudioNode, output?: number, input?: number): void;
disconnect(output?: number): void;
disconnect(destination: AudioNode, output?: number, input?: number): void;
disconnect(destination: AudioParam, output?: number): void;
}
declare var AudioNode: {
@@ -1471,7 +1474,7 @@ interface Console {
select(element: Element): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(): void;
trace(message?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
}
@@ -1730,9 +1733,9 @@ interface DataTransferItemList {
length: number;
add(data: File): DataTransferItem;
clear(): void;
item(index: number): File;
item(index: number): DataTransferItem;
remove(index: number): void;
[index: number]: File;
[index: number]: DataTransferItem;
}
declare var DataTransferItemList: {
@@ -2275,6 +2278,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Gets or sets the version attribute specified in the declaration of an XML document.
*/
xmlVersion: string;
currentScript: HTMLScriptElement;
adoptNode(source: Node): Node;
captureEvents(): void;
clear(): void;
@@ -2784,6 +2788,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param content The text and HTML tags to write.
*/
writeln(...content: string[]): void;
createElement(tagName: "picture"): HTMLPictureElement;
getElementsByTagName(tagname: "picture"): NodeListOf<HTMLPictureElement>;
addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -2990,6 +2996,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
tagName: string;
id: string;
className: string;
innerHTML: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@@ -3185,7 +3192,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
removeAttributeNode(oldAttr: Attr): Attr;
requestFullscreen(): void;
requestPointerLock(): void;
setAttribute(name?: string, value?: string): void;
setAttribute(name: string, value: string): void;
setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void;
setAttributeNode(newAttr: Attr): Attr;
setAttributeNodeNS(newAttr: Attr): Attr;
@@ -3194,6 +3201,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
webkitRequestFullScreen(): void;
webkitRequestFullscreen(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
matches(selector: string): boolean;
getElementsByTagName(tagname: "picture"): NodeListOf<HTMLPictureElement>;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -3983,6 +3992,7 @@ interface HTMLCanvasElement extends HTMLElement {
* @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image.
*/
toDataURL(type?: string, ...args: any[]): string;
toBlob(): Blob;
}
declare var HTMLCanvasElement: {
@@ -4178,7 +4188,6 @@ interface HTMLElement extends Element {
title: string;
blur(): void;
click(): void;
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
insertAdjacentElement(position: string, insertedElement: Element): Element;
@@ -5728,7 +5737,7 @@ interface HTMLMediaElement extends HTMLElement {
* Gets or sets the current playback position, in seconds.
*/
preload: string;
readyState: any;
readyState: number;
/**
* Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked.
*/
@@ -6352,7 +6361,7 @@ interface HTMLSelectElement extends HTMLElement {
* Sets or retrieves the name of the object.
*/
name: string;
options: HTMLSelectElement;
options: HTMLCollection;
/**
* When present, marks an element that can't be submitted without a value.
*/
@@ -6385,6 +6394,7 @@ interface HTMLSelectElement extends HTMLElement {
* Returns whether an element will successfully validate based on forms validation rules and constraints.
*/
willValidate: boolean;
selectedOptions: HTMLCollection;
/**
* Adds an element to the areas, controlRange, or options collection.
* @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.
@@ -6638,19 +6648,19 @@ interface HTMLTableElement extends HTMLElement {
/**
* Creates an empty caption element in the table.
*/
createCaption(): HTMLElement;
createCaption(): HTMLTableCaptionElement;
/**
* Creates an empty tBody element in the table.
*/
createTBody(): HTMLElement;
createTBody(): HTMLTableSectionElement;
/**
* Creates an empty tFoot element in the table.
*/
createTFoot(): HTMLElement;
createTFoot(): HTMLTableSectionElement;
/**
* Returns the tHead element object if successful, or null otherwise.
*/
createTHead(): HTMLElement;
createTHead(): HTMLTableSectionElement;
/**
* Deletes the caption element and its contents from the table.
*/
@@ -6672,7 +6682,7 @@ interface HTMLTableElement extends HTMLElement {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
insertRow(index?: number): HTMLElement;
insertRow(index?: number): HTMLTableRowElement;
}
declare var HTMLTableElement: {
@@ -6723,7 +6733,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment {
* Creates a new cell in the table row, and adds the cell to the cells collection.
* @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.
*/
insertCell(index?: number): HTMLElement;
insertCell(index?: number): HTMLTableCellElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6750,7 +6760,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
insertRow(index?: number): HTMLElement;
insertRow(index?: number): HTMLTableRowElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -7103,7 +7113,7 @@ interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
source: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
delete(): IDBRequest;
@@ -7137,11 +7147,11 @@ interface IDBDatabase extends EventTarget {
objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: string;
version: number;
close(): void;
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -7164,10 +7174,11 @@ declare var IDBFactory: {
}
interface IDBIndex {
keyPath: string;
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
@@ -7198,13 +7209,14 @@ declare var IDBKeyRange: {
interface IDBObjectStore {
indexNames: DOMStringList;
keyPath: string;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
@@ -7239,7 +7251,7 @@ interface IDBRequest extends EventTarget {
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
source: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -7288,7 +7300,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
data: number[];
data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -7852,7 +7864,7 @@ declare var MediaQueryList: {
interface MediaSource extends EventTarget {
activeSourceBuffers: SourceBufferList;
duration: number;
readyState: number;
readyState: string;
sourceBuffers: SourceBufferList;
addSourceBuffer(type: string): SourceBuffer;
endOfStream(error?: number): void;
@@ -8086,6 +8098,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
vibrate(pattern: number | number[]): boolean;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -8126,6 +8139,7 @@ interface Node extends EventTarget {
normalize(): void;
removeChild(oldChild: Node): Node;
replaceChild(newChild: Node, oldChild: Node): Node;
contains(node: Node): boolean;
ATTRIBUTE_NODE: number;
CDATA_SECTION_NODE: number;
COMMENT_NODE: number;
@@ -10424,11 +10438,14 @@ declare var SVGViewElement: {
}
interface SVGZoomAndPan {
zoomAndPan: number;
}
declare var SVGZoomAndPan: {
SVG_ZOOMANDPAN_DISABLE: number;
SVG_ZOOMANDPAN_MAGNIFY: number;
SVG_ZOOMANDPAN_UNKNOWN: number;
}
declare var SVGZoomAndPan: SVGZoomAndPan;
interface SVGZoomEvent extends UIEvent {
newScale: number;
@@ -10579,17 +10596,16 @@ declare var Storage: {
}
interface StorageEvent extends Event {
key: string;
newValue: any;
oldValue: any;
storageArea: Storage;
url: string;
initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void;
key?: string;
oldValue?: string;
newValue?: string;
storageArea?: Storage;
}
declare var StorageEvent: {
prototype: StorageEvent;
new(): StorageEvent;
new (type: string, eventInitDict?: StorageEventInit): StorageEvent;
}
interface StyleMedia {
@@ -12187,7 +12203,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
msMatchMedia(mediaQuery: string): MediaQueryList;
msRequestAnimationFrame(callback: FrameRequestCallback): number;
msWriteProfilerMark(profilerMarkName: string): void;
open(url?: string, target?: string, features?: string, replace?: boolean): any;
open(url?: string, target?: string, features?: string, replace?: boolean): Window;
postMessage(message: any, targetOrigin: string, ports?: any): void;
print(): void;
prompt(message?: string, _default?: string): string;
@@ -12789,6 +12805,24 @@ interface XMLHttpRequestEventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface StorageEventInit extends EventInit {
key?: string;
oldValue?: string;
newValue?: string;
url: string;
storageArea?: Storage;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface NodeListOf<TNode extends Node> extends NodeList {
length: number;
item(index: number): TNode;
@@ -12824,6 +12858,23 @@ interface ProgressEventInit extends EventInit {
total?: number;
}
interface HTMLTemplateElement extends HTMLElement {
content: DocumentFragment;
}
declare var HTMLTemplateElement: {
prototype: HTMLTemplateElement;
new(): HTMLTemplateElement;
}
interface HTMLPictureElement extends HTMLElement {
}
declare var HTMLPictureElement: {
prototype: HTMLPictureElement;
new(): HTMLPictureElement;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@@ -12857,7 +12908,7 @@ interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(): void;
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
@@ -13020,7 +13071,7 @@ declare function msCancelRequestAnimationFrame(handle: number): void;
declare function msMatchMedia(mediaQuery: string): MediaQueryList;
declare function msRequestAnimationFrame(callback: FrameRequestCallback): number;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function open(url?: string, target?: string, features?: string, replace?: boolean): any;
declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window;
declare function postMessage(message: any, targetOrigin: string, ports?: any): void;
declare function print(): void;
declare function prompt(message?: string, _default?: string): string;
+384 -233
View File
File diff suppressed because it is too large Load Diff
+18829
View File
File diff suppressed because it is too large Load Diff
+23 -11
View File
@@ -286,7 +286,7 @@ interface Console {
select(element: any): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(): void;
trace(message?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
}
@@ -492,7 +492,7 @@ interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
source: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
delete(): IDBRequest;
@@ -526,11 +526,11 @@ interface IDBDatabase extends EventTarget {
objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: string;
version: number;
close(): void;
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -553,10 +553,11 @@ declare var IDBFactory: {
}
interface IDBIndex {
keyPath: string;
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
@@ -587,13 +588,14 @@ declare var IDBKeyRange: {
interface IDBObjectStore {
indexNames: DOMStringList;
keyPath: string;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
@@ -628,7 +630,7 @@ interface IDBRequest extends EventTarget {
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
source: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -677,7 +679,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
data: number[];
data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -1109,6 +1111,16 @@ interface WorkerUtils extends Object, WindowBase64 {
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
@@ -1165,7 +1177,7 @@ interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(): void;
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
+9356 -6583
View File
File diff suppressed because it is too large Load Diff
+10475 -7669
View File
File diff suppressed because it is too large Load Diff
+409 -246
View File
File diff suppressed because it is too large Load Diff
+13134 -9582
View File
File diff suppressed because it is too large Load Diff
+409 -246
View File
File diff suppressed because it is too large Load Diff
+13134 -9582
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "1.8.0",
"version": "1.9.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@@ -35,7 +35,8 @@
"browserify": "latest",
"istanbul": "latest",
"mocha-fivemat-progress-reporter": "latest",
"tslint": "latest",
"tslint": "next",
"typescript": "next",
"tsd": "latest"
},
"scripts": {
+16
View File
@@ -0,0 +1,16 @@
<!--
Thank you for submitting a pull request!
Here's a checklist you might find useful.
[ ] There is an associated issue that is labelled
'Bug' or 'Accepting PRs' or is in the Community milestone
[ ] Code is up-to-date with the `master` branch
[ ] You've successfully run `jake runtests` locally
[ ] You've signed the CLA
[ ] There are new or updated unit tests validating the change
Refer to CONTRIBUTING.MD for more details.
https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md
-->
Fixes #
+5 -2
View File
@@ -76,8 +76,11 @@ module Commands {
fs.mkdirSync(directoryPath);
}
}
function normalizeSlashes(path: string): string {
return path.replace(/\\/g, "/");
}
function transalatePath(outputFolder:string, path: string): string {
return outputFolder + directorySeparator + path.replace(":", "");
return normalizeSlashes(outputFolder + directorySeparator + path.replace(":", ""));
}
function fileExists(path: string): boolean {
return fs.existsSync(path);
@@ -86,7 +89,7 @@ module Commands {
var filename = transalatePath(outputFolder, f.path);
ensureDirectoriesExist(getDirectoryPath(filename));
console.log("writing filename: " + filename);
fs.writeFile(filename, f.result.contents, (err) => { });
fs.writeFileSync(filename, f.result.contents);
});
console.log("Command: tsc ");
+11 -8
View File
@@ -1,6 +1,5 @@
/// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING_FACTORY = (name: string, currently: string) => `Tag boolean argument as '${name}' (currently '${currently}')`;
@@ -19,7 +18,7 @@ class BooleanTriviaWalker extends Lint.RuleWalker {
visitCallExpression(node: ts.CallExpression) {
super.visitCallExpression(node);
if (node.arguments) {
if (node.arguments) {
const targetCallSignature = this.checker.getResolvedSignature(node);
if (!!targetCallSignature) {
const targetParameters = targetCallSignature.getParameters();
@@ -27,7 +26,9 @@ class BooleanTriviaWalker extends Lint.RuleWalker {
for (let index = 0; index < targetParameters.length; index++) {
const param = targetParameters[index];
const arg = node.arguments[index];
if (!(arg && param)) continue;
if (!(arg && param)) {
continue;
}
const argType = this.checker.getContextualType(arg);
if (argType && (argType.getFlags() & ts.TypeFlags.Boolean)) {
@@ -37,14 +38,16 @@ class BooleanTriviaWalker extends Lint.RuleWalker {
let triviaContent: string;
const ranges = ts.getLeadingCommentRanges(arg.getFullText(), 0);
if (ranges && ranges.length === 1 && ranges[0].kind === ts.SyntaxKind.MultiLineCommentTrivia) {
triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); //+/-2 to remove /**/
triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); // +/-2 to remove /**/
}
if (triviaContent !== param.getName()) {
const paramName = param.getName();
if (triviaContent !== paramName && triviaContent !== paramName + ":") {
this.addFailure(this.createFailure(arg.getStart(source), arg.getWidth(source), Rule.FAILURE_STRING_FACTORY(param.getName(), triviaContent)));
}
}
}
}
}
}
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
/// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
const OPTION_CATCH = "check-catch";
const OPTION_ELSE = "check-else";
+20
View File
@@ -0,0 +1,20 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Don't use the 'in' keyword - use 'hasProperty' to check for key presence instead";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new InWalker(sourceFile, this.getOptions()));
}
}
class InWalker extends Lint.RuleWalker {
visitNode(node: ts.Node) {
super.visitNode(node);
if (node.kind === ts.SyntaxKind.InKeyword && node.parent && node.parent.kind === ts.SyntaxKind.BinaryExpression) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
}
}
@@ -0,0 +1,37 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static POSTFIX_FAILURE_STRING = "Don't use '++' or '--' postfix operators outside statements or for loops.";
public static PREFIX_FAILURE_STRING = "Don't use '++' or '--' prefix operators.";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new IncrementDecrementWalker(sourceFile, this.getOptions()));
}
}
class IncrementDecrementWalker extends Lint.RuleWalker {
visitPostfixUnaryExpression(node: ts.PostfixUnaryExpression) {
super.visitPostfixUnaryExpression(node);
if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator == ts.SyntaxKind.MinusMinusToken) {
this.visitIncrementDecrement(node);
}
}
visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression) {
super.visitPrefixUnaryExpression(node);
if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator == ts.SyntaxKind.MinusMinusToken) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.PREFIX_FAILURE_STRING));
}
}
visitIncrementDecrement(node: ts.UnaryExpression) {
if (node.parent && (node.parent.kind === ts.SyntaxKind.ExpressionStatement ||
node.parent.kind === ts.SyntaxKind.ForStatement)) {
return;
}
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.POSTFIX_FAILURE_STRING));
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
/// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
+16 -14
View File
@@ -1,5 +1,5 @@
/// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
@@ -85,12 +85,12 @@ class PreferConstWalker extends Lint.RuleWalker {
visitBinaryExpression(node: ts.BinaryExpression) {
if (isAssignmentOperator(node.operatorToken.kind)) {
this.visitLHSExpressions(node.left);
this.visitLeftHandSideExpression(node.left);
}
super.visitBinaryExpression(node);
}
private visitLHSExpressions(node: ts.Expression) {
private visitLeftHandSideExpression(node: ts.Expression) {
while (node.kind === ts.SyntaxKind.ParenthesizedExpression) {
node = (node as ts.ParenthesizedExpression).expression;
}
@@ -101,23 +101,25 @@ class PreferConstWalker extends Lint.RuleWalker {
this.visitBindingLiteralExpression(node as (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression));
}
}
private visitBindingLiteralExpression(node: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) {
if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) {
const pattern = node as ts.ObjectLiteralExpression;
for (const element of pattern.properties) {
if (element.name.kind === ts.SyntaxKind.Identifier) {
this.markAssignment(element.name as ts.Identifier)
const kind = element.kind;
if (kind === ts.SyntaxKind.ShorthandPropertyAssignment) {
this.markAssignment((element as ts.ShorthandPropertyAssignment).name);
}
else if (isBindingPattern(element.name)) {
this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern);
else if (kind === ts.SyntaxKind.PropertyAssignment) {
this.visitLeftHandSideExpression((element as ts.PropertyAssignment).initializer);
}
}
}
else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) {
const pattern = node as ts.ArrayLiteralExpression;
for (const element of pattern.elements) {
this.visitLHSExpressions(element);
this.visitLeftHandSideExpression(element);
}
}
}
@@ -145,7 +147,7 @@ class PreferConstWalker extends Lint.RuleWalker {
private visitAnyUnaryExpression(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression) {
if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) {
this.visitLHSExpressions(node.operand);
this.visitLeftHandSideExpression(node.operand);
}
}
@@ -211,12 +213,12 @@ class PreferConstWalker extends Lint.RuleWalker {
}
}
private collectNameIdentifiers(value: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
private collectNameIdentifiers(declaration: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map<DeclarationUsages>) {
if (node.kind === ts.SyntaxKind.Identifier) {
table[(node as ts.Identifier).text] = {declaration: value, usages: 0};
table[(node as ts.Identifier).text] = { declaration, usages: 0 };
}
else {
this.collectBindingPatternIdentifiers(value, node as ts.BindingPattern, table);
this.collectBindingPatternIdentifiers(declaration, node as ts.BindingPattern, table);
}
}
+4 -4
View File
@@ -1,5 +1,5 @@
/// <reference path="../../node_modules/tslint/typings/typescriptServices.d.ts" />
/// <reference path="../../node_modules/tslint/lib/tslint.d.ts" />
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
@@ -13,10 +13,10 @@ export class Rule extends Lint.Rules.AbstractRule {
class TypeOperatorSpacingWalker extends Lint.RuleWalker {
public visitNode(node: ts.Node) {
if (node.kind === ts.SyntaxKind.UnionType || node.kind === ts.SyntaxKind.IntersectionType) {
let types = (<ts.UnionOrIntersectionTypeNode>node).types;
const types = (<ts.UnionOrIntersectionTypeNode>node).types;
let expectedStart = types[0].end + 2; // space, | or &
for (let i = 1; i < types.length; i++) {
let currentType = types[i];
const currentType = types[i];
if (expectedStart !== currentType.pos || currentType.getLeadingTriviaWidth() !== 1) {
const failure = this.createFailure(currentType.pos, currentType.getWidth(), Rule.FAILURE_STRING);
this.addFailure(failure);
-235
View File
@@ -1,235 +0,0 @@
// word2md - Word to Markdown conversion tool
//
// word2md converts a Microsoft Word document to Markdown formatted text. The tool uses the
// Word Automation APIs to start an instance of Word and access the contents of the document
// being converted. The tool must be run using the cscript.exe script host and requires Word
// to be installed on the target machine. The name of the document to convert must be specified
// as a command line argument and the resulting Markdown is written to standard output. The
// tool recognizes the specific Word styles used in the TypeScript Language Specification.
var sys = (function () {
var fileStream = new ActiveXObject("ADODB.Stream");
fileStream.Type = 2 /*text*/;
var binaryStream = new ActiveXObject("ADODB.Stream");
binaryStream.Type = 1 /*binary*/;
var args = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
args: args,
createObject: function (typeName) { return new ActiveXObject(typeName); },
write: function (s) {
WScript.StdOut.Write(s);
},
writeFile: function (fileName, data) {
fileStream.Open();
binaryStream.Open();
try {
// Write characters in UTF-8 encoding
fileStream.Charset = "utf-8";
fileStream.WriteText(data);
// We don't want the BOM, skip it by setting the starting location to 3 (size of BOM).
fileStream.Position = 3;
fileStream.CopyTo(binaryStream);
binaryStream.SaveToFile(fileName, 2 /*overwrite*/);
}
finally {
binaryStream.Close();
fileStream.Close();
}
}
};
})();
function convertDocumentToMarkdown(doc) {
var result = "";
var lastStyle;
var lastInTable;
var tableColumnCount;
var tableCellIndex;
var columnAlignment = [];
function setProperties(target, properties) {
for (var name in properties) {
if (properties.hasOwnProperty(name)) {
var value = properties[name];
if (typeof value === "object") {
setProperties(target[name], value);
}
else {
target[name] = value;
}
}
}
}
function findReplace(findText, findOptions, replaceText, replaceOptions) {
var find = doc.range().find;
find.clearFormatting();
setProperties(find, findOptions);
var replace = find.replacement;
replace.clearFormatting();
setProperties(replace, replaceOptions);
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
function fixHyperlinks() {
var count = doc.hyperlinks.count;
for (var i = 0; i < count; i++) {
var hyperlink = doc.hyperlinks.item(i + 1);
var address = hyperlink.address;
if (address && address.length > 0) {
var textToDisplay = hyperlink.textToDisplay;
hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
}
}
}
function write(s) {
result += s;
}
function writeTableHeader() {
for (var i = 0; i < tableColumnCount - 1; i++) {
switch (columnAlignment[i]) {
case 1:
write("|:---:");
break;
case 2:
write("|---:");
break;
default:
write("|---");
}
}
write("|\n");
}
function trimEndFormattingMarks(text) {
var i = text.length;
while (i > 0 && text.charCodeAt(i - 1) < 0x20)
i--;
return text.substr(0, i);
}
function writeBlockEnd() {
switch (lastStyle) {
case "Code":
write("```\n\n");
break;
case "List Paragraph":
case "Table":
case "TOC":
write("\n");
break;
}
}
function writeParagraph(p) {
var text = p.range.text;
var style = p.style.nameLocal;
var inTable = p.range.tables.count > 0;
var level = 1;
var sectionBreak = text.indexOf("\x0C") >= 0;
text = trimEndFormattingMarks(text);
if (inTable) {
style = "Table";
}
else if (style.match(/\s\d$/)) {
level = +style.substr(style.length - 1);
style = style.substr(0, style.length - 2);
}
if (lastStyle && style !== lastStyle) {
writeBlockEnd();
}
switch (style) {
case "Heading":
case "Appendix":
var section = p.range.listFormat.listString;
write("####".substr(0, level) + ' <a name="' + section + '"/>' + section + " " + text + "\n\n");
break;
case "Normal":
if (text.length) {
write(text + "\n\n");
}
break;
case "List Paragraph":
write(" ".substr(0, p.range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n");
break;
case "Grammar":
write("&emsp;&emsp;" + text.replace(/\s\s\s/g, "&emsp;").replace(/\x0B/g, " \n&emsp;&emsp;&emsp;") + "\n\n");
break;
case "Code":
if (lastStyle !== "Code") {
write("```TypeScript\n");
}
else {
write("\n");
}
write(text.replace(/\x0B/g, " \n") + "\n");
break;
case "Table":
if (!lastInTable) {
tableColumnCount = p.range.tables.item(1).columns.count + 1;
tableCellIndex = 0;
}
if (tableCellIndex < tableColumnCount) {
columnAlignment[tableCellIndex] = p.alignment;
}
write("|" + text);
tableCellIndex++;
if (tableCellIndex % tableColumnCount === 0) {
write("\n");
if (tableCellIndex === tableColumnCount) {
writeTableHeader();
}
}
break;
case "TOC Heading":
write("## " + text + "\n\n");
break;
case "TOC":
var strings = text.split("\t");
write(" ".substr(0, level * 2 - 2) + "* [" + strings[0] + " " + strings[1] + "](#" + strings[0] + ")\n");
break;
}
if (sectionBreak) {
write("<br/>\n\n");
}
lastStyle = style;
lastInTable = inTable;
}
function writeDocument() {
var title = doc.builtInDocumentProperties.item(1) + "";
if (title.length) {
write("# " + title + "\n\n");
}
for (var p = doc.paragraphs.first; p; p = p.next()) {
writeParagraph(p);
}
writeBlockEnd();
}
findReplace("<", {}, "&lt;", {});
findReplace("&lt;", { style: "Code" }, "<", {});
findReplace("&lt;", { style: "Code Fragment" }, "<", {});
findReplace("&lt;", { style: "Terminal" }, "<", {});
findReplace("", { font: { subscript: true } }, "<sub>^&</sub>", { font: { subscript: false } });
findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ });
findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } });
findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } });
doc.fields.toggleShowCodes();
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
fixHyperlinks();
writeDocument();
result = result.replace(/\x85/g, "\u2026");
result = result.replace(/\x96/g, "\u2013");
result = result.replace(/\x97/g, "\u2014");
return result;
}
function main(args) {
if (args.length !== 2) {
sys.write("Syntax: word2md <inputfile> <outputfile>\n");
return;
}
var app = sys.createObject("Word.Application");
var doc = app.documents.open(args[0]);
sys.writeFile(args[1], convertDocumentToMarkdown(doc));
doc.close(false);
app.quit();
}
main(sys.args);
//# sourceMappingURL=file:///c:/ts/scripts/word2md.js.map
+22 -5
View File
@@ -72,6 +72,9 @@ module Word {
listFormat: ListFormat;
tables: Tables;
text: string;
textRetrievalMode: {
includeHiddenText: boolean;
}
words: Ranges;
}
@@ -258,13 +261,27 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
function writeParagraph(p: Word.Paragraph) {
var text = p.range.text;
var range = p.range;
var text = range.text;
var style = p.style.nameLocal;
var inTable = p.range.tables.count > 0;
var inTable = range.tables.count > 0;
var level = 1;
var sectionBreak = text.indexOf("\x0C") >= 0;
text = trimEndFormattingMarks(text);
if (text === "/") {
// An inline image shows up in the text as a "/". When we see a paragraph
// consisting of nothing but "/", we check to see if the paragraph contains
// hidden text and, if so, emit that instead. The hidden text is assumed to
// contain an appropriate markdown image link.
range.textRetrievalMode.includeHiddenText = true;
var fullText = range.text;
range.textRetrievalMode.includeHiddenText = false;
if (text !== fullText) {
text = "&emsp;&emsp;" + fullText.substr(1);
}
}
if (inTable) {
style = "Table";
}
@@ -280,7 +297,7 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
case "Heading":
case "Appendix":
var section = p.range.listFormat.listString;
var section = range.listFormat.listString;
write("####".substr(0, level) + ' <a name="' + section + '"/>' + section + " " + text + "\n\n");
break;
@@ -291,7 +308,7 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
break;
case "List Paragraph":
write(" ".substr(0, p.range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n");
write(" ".substr(0, range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n");
break;
case "Grammar":
@@ -310,7 +327,7 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
case "Table":
if (!lastInTable) {
tableColumnCount = p.range.tables.item(1).columns.count + 1;
tableColumnCount = range.tables.item(1).columns.count + 1;
tableCellIndex = 0;
}
if (tableCellIndex < tableColumnCount) {
+329 -47
View File
@@ -1,3 +1,4 @@
/// <reference path="utilities.ts"/>
/// <reference path="parser.ts"/>
/* @internal */
@@ -6,12 +7,12 @@ namespace ts {
export const enum ModuleInstanceState {
NonInstantiated = 0,
Instantiated = 1,
ConstEnumOnly = 2
Instantiated = 1,
ConstEnumOnly = 2
}
const enum Reachability {
Unintialized = 1 << 0,
Uninitialized = 1 << 0,
Reachable = 1 << 1,
Unreachable = 1 << 2,
ReportedUnreachable = 1 << 3
@@ -116,6 +117,12 @@ namespace ts {
let labelIndexMap: Map<number>;
let implicitLabels: number[];
// state used for emit helpers
let hasClassExtends: boolean;
let hasAsyncFunctions: boolean;
let hasDecorators: boolean;
let hasParameterDecorators: boolean;
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
// not depending on if we see "use strict" in certain places (or if we hit a class/namespace).
@@ -130,6 +137,7 @@ namespace ts {
options = opts;
inStrictMode = !!file.externalModuleIndicator;
classifiableNames = {};
Symbol = objectAllocator.getSymbolConstructor();
if (!file.locals) {
@@ -138,6 +146,8 @@ namespace ts {
file.classifiableNames = classifiableNames;
}
file = undefined;
options = undefined;
parent = undefined;
container = undefined;
blockScopeContainer = undefined;
@@ -147,6 +157,10 @@ namespace ts {
labelStack = undefined;
labelIndexMap = undefined;
implicitLabels = undefined;
hasClassExtends = false;
hasAsyncFunctions = false;
hasDecorators = false;
hasParameterDecorators = false;
}
return bindSourceFile;
@@ -174,20 +188,30 @@ namespace ts {
symbol.members = {};
}
if (symbolFlags & SymbolFlags.Value && !symbol.valueDeclaration) {
symbol.valueDeclaration = node;
}
if (symbolFlags & SymbolFlags.Value) {
const valueDeclaration = symbol.valueDeclaration;
if (!valueDeclaration ||
(valueDeclaration.kind !== node.kind && valueDeclaration.kind === SyntaxKind.ModuleDeclaration)) {
// other kinds of value declarations take precedence over modules
symbol.valueDeclaration = node;
}
}
}
// Should not be called on a declaration with a computed property name,
// unless it is a well known Symbol.
function getDeclarationName(node: Declaration): string {
if (node.name) {
if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {
return `"${(<LiteralExpression>node.name).text}"`;
if (isAmbientModule(node)) {
return isGlobalScopeAugmentation(<ModuleDeclaration>node) ? "__global" : `"${(<LiteralExpression>node.name).text}"`;
}
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>node.name).expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteral(nameExpression.kind)) {
return (<LiteralExpression>nameExpression).text;
}
Debug.assert(isWellKnownSymbolSyntactically(nameExpression));
return getPropertyNameForKnownSymbolName((<PropertyAccessExpression>nameExpression).name.text);
}
@@ -208,9 +232,34 @@ namespace ts {
return "__export";
case SyntaxKind.ExportAssignment:
return (<ExportAssignment>node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
switch (getSpecialPropertyAssignmentKind(node)) {
case SpecialPropertyAssignmentKind.ModuleExports:
// module.exports = ...
return "export=";
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
// exports.x = ... or this.y = ...
return ((node as BinaryExpression).left as PropertyAccessExpression).name.text;
case SpecialPropertyAssignmentKind.PrototypeProperty:
// className.prototype.methodName = ...
return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text;
}
Debug.fail("Unknown binary declaration kind");
break;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
return node.flags & NodeFlags.Default ? "default" : undefined;
case SyntaxKind.JSDocFunctionType:
return isJSDocConstructSignature(node) ? "__new" : "__call";
case SyntaxKind.Parameter:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType);
let functionType = <JSDocFunctionType>node.parent;
let index = indexOf(functionType.parameters, node);
return "p" + index;
}
}
@@ -230,6 +279,7 @@ namespace ts {
Debug.assert(!hasDynamicName(node));
const isDefaultExport = node.flags & NodeFlags.Default;
// The exported symbol for an export default function/class node is always named "default"
const name = isDefaultExport && parent ? "default" : getDeclarationName(node);
@@ -319,7 +369,12 @@ namespace ts {
// 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
// but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
// when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
if (hasExportModifier || container.flags & NodeFlags.ExportContext) {
// NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
if (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) {
const exportKind =
(symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) |
(symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) |
@@ -339,7 +394,7 @@ namespace ts {
// the getLocalNameOfContainer function in the type checker to validate that the local name
// used for a container is unique.
function bindChildren(node: Node) {
// Before we recurse into a node's chilren, we first save the existing parent, container
// Before we recurse into a node's children, we first save the existing parent, container
// and block-container. Then after we pop out of processing the children, we restore
// these saved values.
const saveParent = parent;
@@ -364,7 +419,7 @@ namespace ts {
// Finally, if this is a block-container, then we clear out any existing .locals object
// it may contain within it. This happens in incremental scenarios. Because we can be
// reusing a node from a previous compilation, that node may have had 'locals' created
// for it. We must clear this so we don't accidently move any stale data forward from
// for it. We must clear this so we don't accidentally move any stale data forward from
// a previous compilation.
const containerFlags = getContainerFlags(node);
if (containerFlags & ContainerFlags.IsContainer) {
@@ -376,7 +431,6 @@ namespace ts {
addToContainerChain(container);
}
else if (containerFlags & ContainerFlags.IsBlockScopedContainer) {
blockScopeContainer = node;
blockScopeContainer.locals = undefined;
@@ -394,6 +448,9 @@ namespace ts {
// reset all reachability check related flags on node (for incremental scenarios)
flags &= ~NodeFlags.ReachabilityCheckFlags;
// reset all emit helper flags on node (for incremental scenarios)
flags &= ~NodeFlags.EmitHelperFlags;
if (kind === SyntaxKind.InterfaceDeclaration) {
seenThisKeyword = false;
}
@@ -411,6 +468,10 @@ namespace ts {
labelStack = labelIndexMap = implicitLabels = undefined;
}
if (isInJavaScriptFile(node) && node.jsDocComment) {
bind(node.jsDocComment);
}
bindReachableStatement(node);
if (currentReachabilityState === Reachability.Reachable && isFunctionLikeKind(kind) && nodeIsPresent((<FunctionLikeDeclaration>node).body)) {
@@ -424,6 +485,21 @@ namespace ts {
flags = seenThisKeyword ? flags | NodeFlags.ContainsThis : flags & ~NodeFlags.ContainsThis;
}
if (kind === SyntaxKind.SourceFile) {
if (hasClassExtends) {
flags |= NodeFlags.HasClassExtends;
}
if (hasDecorators) {
flags |= NodeFlags.HasDecorators;
}
if (hasParameterDecorators) {
flags |= NodeFlags.HasParamDecorators;
}
if (hasAsyncFunctions) {
flags |= NodeFlags.HasAsyncFunctions;
}
}
node.flags = flags;
if (saveState) {
@@ -441,7 +517,7 @@ namespace ts {
/**
* Returns true if node and its subnodes were successfully traversed.
* Returning false means that node was not examined and caller needs to dive into the node himself.
* Returning false means that node was not examined and caller needs to dive into the node himself.
*/
function bindReachableStatement(node: Node): void {
if (checkUnreachable(node)) {
@@ -551,7 +627,7 @@ namespace ts {
}
function bindIfStatement(n: IfStatement): void {
// denotes reachability state when entering 'thenStatement' part of the if statement:
// denotes reachability state when entering 'thenStatement' part of the if statement:
// i.e. if condition is false then thenStatement is unreachable
const ifTrueState = n.expression.kind === SyntaxKind.FalseKeyword ? Reachability.Unreachable : currentReachabilityState;
// denotes reachability state when entering 'elseStatement':
@@ -610,7 +686,7 @@ namespace ts {
// post catch/finally state is reachable if
// - post try state is reachable - control flow can fall out of try block
// - post catch state is reachable - control flow can fall out of catch block
currentReachabilityState = or(postTryState, postCatchState);
currentReachabilityState = n.catchClause ? or(postTryState, postCatchState) : postTryState;
}
function bindSwitchStatement(n: SwitchStatement): void {
@@ -624,7 +700,7 @@ namespace ts {
const hasDefault = forEach(n.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause);
// post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case
// post switch state is unreachable if switch is exhaustive (has a default case ) and does not have fallthrough from the last case
const postSwitchState = hasDefault && currentReachabilityState !== Reachability.Reachable ? Reachability.Unreachable : preSwitchState;
popImplicitLabel(postSwitchLabel, postSwitchState);
@@ -633,10 +709,14 @@ namespace ts {
function bindCaseBlock(n: CaseBlock): void {
const startState = currentReachabilityState;
for (const clause of n.clauses) {
for (let i = 0; i < n.clauses.length; i++) {
const clause = n.clauses[i];
currentReachabilityState = startState;
bind(clause);
if (clause.statements.length && currentReachabilityState === Reachability.Reachable && options.noFallthroughCasesInSwitch) {
if (clause.statements.length &&
i !== n.clauses.length - 1 && // allow fallthrough from the last case
currentReachabilityState === Reachability.Reachable &&
options.noFallthroughCasesInSwitch) {
errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch);
}
}
@@ -659,8 +739,9 @@ namespace ts {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.TypeLiteral:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.TypeLiteral:
case SyntaxKind.JSDocRecordType:
return ContainerFlags.IsContainer;
case SyntaxKind.CallSignature:
@@ -673,6 +754,7 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionType:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
@@ -690,7 +772,7 @@ namespace ts {
case SyntaxKind.Block:
// do not treat blocks directly inside a function as a block-scoped-container.
// Locals that reside in this block should go to the function locals. Othewise 'x'
// Locals that reside in this block should go to the function locals. Otherwise 'x'
// would not appear to be a redeclaration of a block scoped local in the following
// example:
//
@@ -746,6 +828,7 @@ namespace ts {
case SyntaxKind.TypeLiteral:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.JSDocRecordType:
// Interface/Object-types always have their children added to the 'members' of
// their container. They are only accessible through an instance of their
// container, and are never in scope otherwise (even inside the body of the
@@ -766,6 +849,7 @@ namespace ts {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.TypeAliasDeclaration:
// All the children of these container types are never visible through another
// symbol (i.e. through another symbol's 'exports' or 'members'). Instead,
@@ -814,8 +898,16 @@ namespace ts {
function bindModuleDeclaration(node: ModuleDeclaration) {
setExportContextFlag(node);
if (node.name.kind === SyntaxKind.StringLiteral) {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
if (isAmbientModule(node)) {
if (node.flags & NodeFlags.Export) {
errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
if (isExternalModuleAugmentation(node)) {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes);
}
else {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
}
}
else {
const state = getModuleInstanceState(node);
@@ -844,7 +936,7 @@ namespace ts {
}
}
function bindFunctionOrConstructorType(node: SignatureDeclaration) {
function bindFunctionOrConstructorType(node: SignatureDeclaration): void {
// For a given function symbol "<...>(...) => T" we want to generate a symbol identical
// to the one we would get for: { <...>(...): T }
//
@@ -875,7 +967,7 @@ namespace ts {
const identifier = <Identifier>prop.name;
// ECMA-262 11.1.5 Object Initialiser
// ECMA-262 11.1.5 Object Initializer
// If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
// a.This production is contained in strict code and IsDataDescriptor(previous) is true and
// IsDataDescriptor(propId.descriptor) is true.
@@ -919,7 +1011,7 @@ namespace ts {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
}
// fall through.
// fall through.
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = {};
@@ -1029,7 +1121,7 @@ namespace ts {
}
function checkStrictModeNumericLiteral(node: LiteralExpression) {
if (inStrictMode && node.flags & NodeFlags.OctalLiteral) {
if (inStrictMode && node.isOctalLiteral) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
}
}
@@ -1069,7 +1161,7 @@ namespace ts {
return "__" + indexOf((<SignatureDeclaration>node.parent).parameters, node);
}
function bind(node: Node) {
function bind(node: Node): void {
if (!node) {
return;
}
@@ -1140,14 +1232,37 @@ namespace ts {
// Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
// string to contain unicode escapes (as per ES5).
return nodeText === "\"use strict\"" || nodeText === "'use strict'";
return nodeText === '"use strict"' || nodeText === "'use strict'";
}
function bindWorker(node: Node) {
switch (node.kind) {
/* Strict mode checks */
case SyntaxKind.Identifier:
return checkStrictModeIdentifier(<Identifier>node);
case SyntaxKind.BinaryExpression:
if (isInJavaScriptFile(node)) {
const specialKind = getSpecialPropertyAssignmentKind(node);
switch (specialKind) {
case SpecialPropertyAssignmentKind.ExportsProperty:
bindExportsPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ModuleExports:
bindModuleExportsAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.PrototypeProperty:
bindPrototypePropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ThisProperty:
bindThisPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.None:
// Nothing to do
break;
default:
Debug.fail("Unknown special property assignment kind");
}
}
return checkStrictModeBinaryExpression(<BinaryExpression>node);
case SyntaxKind.CatchClause:
return checkStrictModeCatchClause(<CatchClause>node);
@@ -1161,10 +1276,11 @@ namespace ts {
return checkStrictModePrefixUnaryExpression(<PrefixUnaryExpression>node);
case SyntaxKind.WithStatement:
return checkStrictModeWithStatement(<WithStatement>node);
case SyntaxKind.ThisKeyword:
case SyntaxKind.ThisType:
seenThisKeyword = true;
return;
case SyntaxKind.TypePredicate:
return checkTypePredicate(node as TypePredicateNode);
case SyntaxKind.TypeParameter:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
case SyntaxKind.Parameter:
@@ -1174,12 +1290,14 @@ namespace ts {
return bindVariableDeclarationOrBindingElement(<VariableDeclaration | BindingElement>node);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.JSDocRecordMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property | ((<PropertyDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
case SyntaxKind.EnumMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
@@ -1193,8 +1311,7 @@ namespace ts {
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Method | ((<MethodDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None),
isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes);
case SyntaxKind.FunctionDeclaration:
checkStrictModeFunctionName(<FunctionDeclaration>node);
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
return bindFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.Constructor:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None);
case SyntaxKind.GetAccessor:
@@ -1203,16 +1320,24 @@ namespace ts {
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.JSDocFunctionType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
case SyntaxKind.TypeLiteral:
case SyntaxKind.JSDocRecordType:
return bindAnonymousDeclaration(<TypeLiteralNode>node, SymbolFlags.TypeLiteral, "__type");
case SyntaxKind.ObjectLiteralExpression:
return bindObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
checkStrictModeFunctionName(<FunctionExpression>node);
const bindingName = (<FunctionExpression>node).name ? (<FunctionExpression>node).name.text : "__function";
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, bindingName);
return bindFunctionExpression(<FunctionExpression>node);
case SyntaxKind.CallExpression:
if (isInJavaScriptFile(node)) {
bindCallExpression(<CallExpression>node);
}
break;
// Members of classes, interfaces, and modules
case SyntaxKind.ClassExpression:
case SyntaxKind.ClassDeclaration:
return bindClassLikeDeclaration(<ClassLikeDeclaration>node);
@@ -1224,11 +1349,15 @@ namespace ts {
return bindEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.ModuleDeclaration:
return bindModuleDeclaration(<ModuleDeclaration>node);
// Imports and exports
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.NamespaceImport:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
case SyntaxKind.GlobalModuleExportDeclaration:
return bindGlobalModuleExportDeclaration(<GlobalModuleExportDeclaration>node);
case SyntaxKind.ImportClause:
return bindImportClause(<ImportClause>node);
case SyntaxKind.ExportDeclaration:
@@ -1240,19 +1369,35 @@ namespace ts {
}
}
function checkTypePredicate(node: TypePredicateNode) {
const { parameterName, type } = node;
if (parameterName && parameterName.kind === SyntaxKind.Identifier) {
checkStrictModeIdentifier(parameterName as Identifier);
}
if (parameterName && parameterName.kind === SyntaxKind.ThisType) {
seenThisKeyword = true;
}
bind(type);
}
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (isExternalModule(file)) {
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`);
bindSourceFileAsExternalModule();
}
}
function bindExportAssignment(node: ExportAssignment) {
function bindSourceFileAsExternalModule() {
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName) }"`);
}
function bindExportAssignment(node: ExportAssignment | BinaryExpression) {
const boundExpression = node.kind === SyntaxKind.ExportAssignment ? (<ExportAssignment>node).expression : (<BinaryExpression>node).right;
if (!container.symbol || !container.symbol.exports) {
// Export assignment in some sort of block construct
bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node));
}
else if (node.expression.kind === SyntaxKind.Identifier) {
else if (boundExpression.kind === SyntaxKind.Identifier && node.kind === SyntaxKind.ExportAssignment) {
// An export default clause with an identifier exports all meanings of that identifier
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.Alias, SymbolFlags.PropertyExcludes | SymbolFlags.AliasExcludes);
}
@@ -1262,6 +1407,33 @@ namespace ts {
}
}
function bindGlobalModuleExportDeclaration(node: GlobalModuleExportDeclaration) {
if (node.modifiers && node.modifiers.length) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Modifiers_cannot_appear_here));
}
if (node.parent.kind !== SyntaxKind.SourceFile) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_at_top_level));
return;
}
else {
const parent = node.parent as SourceFile;
if (!isExternalModule(parent)) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
if (!parent.isDeclarationFile) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
}
file.symbol.globalExports = file.symbol.globalExports || {};
declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
}
function bindExportDeclaration(node: ExportDeclaration) {
if (!container.symbol || !container.symbol.exports) {
// Export * in some sort of block construct
@@ -1279,7 +1451,81 @@ namespace ts {
}
}
function setCommonJsModuleIndicator(node: Node) {
if (!file.commonJsModuleIndicator) {
file.commonJsModuleIndicator = node;
bindSourceFileAsExternalModule();
}
}
function bindExportsPropertyAssignment(node: BinaryExpression) {
// When we create a property via 'exports.foo = bar', the 'exports.foo' property access
// expression is the declaration
setCommonJsModuleIndicator(node);
declareSymbol(file.symbol.exports, file.symbol, <PropertyAccessExpression>node.left, SymbolFlags.Property | SymbolFlags.Export, SymbolFlags.None);
}
function bindModuleExportsAssignment(node: BinaryExpression) {
// 'module.exports = expr' assignment
setCommonJsModuleIndicator(node);
declareSymbol(file.symbol.exports, file.symbol, node, SymbolFlags.Property | SymbolFlags.Export | SymbolFlags.ValueModule, SymbolFlags.None);
}
function bindThisPropertyAssignment(node: BinaryExpression) {
// Declare a 'member' in case it turns out the container was an ES5 class
if (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) {
container.symbol.members = container.symbol.members || {};
// It's acceptable for multiple 'this' assignments of the same identifier to occur
declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property);
}
}
function bindPrototypePropertyAssignment(node: BinaryExpression) {
// We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function.
// Look up the function in the local scope, since prototype assignments should
// follow the function declaration
const leftSideOfAssignment = node.left as PropertyAccessExpression;
const classPrototype = leftSideOfAssignment.expression as PropertyAccessExpression;
const constructorFunction = classPrototype.expression as Identifier;
// Fix up parent pointers since we're going to use these nodes before we bind into them
leftSideOfAssignment.parent = node;
constructorFunction.parent = classPrototype;
classPrototype.parent = leftSideOfAssignment;
const funcSymbol = container.locals[constructorFunction.text];
if (!funcSymbol || !(funcSymbol.flags & SymbolFlags.Function)) {
return;
}
// Set up the members collection if it doesn't exist already
if (!funcSymbol.members) {
funcSymbol.members = {};
}
// Declare the method/property
declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
function bindCallExpression(node: CallExpression) {
// We're only inspecting call expressions to detect CommonJS modules, so we can skip
// this check if we've already seen the module indicator
if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteral*/false)) {
setCommonJsModuleIndicator(node);
}
}
function bindClassLikeDeclaration(node: ClassLikeDeclaration) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (getClassExtendsHeritageClauseElement(node) !== undefined) {
hasClassExtends = true;
}
if (nodeIsDecorated(node)) {
hasDecorators = true;
}
}
if (node.kind === SyntaxKind.ClassDeclaration) {
bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes);
}
@@ -1349,6 +1595,13 @@ namespace ts {
}
function bindParameter(node: ParameterDeclaration) {
if (!isDeclarationFile(file) &&
!isInAmbientContext(node) &&
nodeIsDecorated(node)) {
hasDecorators = true;
hasParameterDecorators = true;
}
if (inStrictMode) {
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
@@ -1364,16 +1617,45 @@ namespace ts {
// If this is a property-parameter, then also declare the property symbol into the
// containing class.
if (node.flags & NodeFlags.AccessibilityModifier &&
node.parent.kind === SyntaxKind.Constructor &&
isClassLike(node.parent.parent)) {
if (isParameterPropertyDeclaration(node)) {
const classDeclaration = <ClassLikeDeclaration>node.parent.parent;
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
}
function bindFunctionDeclaration(node: FunctionDeclaration) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (isAsyncFunctionLike(node)) {
hasAsyncFunctions = true;
}
}
checkStrictModeFunctionName(<FunctionDeclaration>node);
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
function bindFunctionExpression(node: FunctionExpression) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (isAsyncFunctionLike(node)) {
hasAsyncFunctions = true;
}
}
checkStrictModeFunctionName(<FunctionExpression>node);
const bindingName = (<FunctionExpression>node).name ? (<FunctionExpression>node).name.text : "__function";
return bindAnonymousDeclaration(<FunctionExpression>node, SymbolFlags.Function, bindingName);
}
function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (isAsyncFunctionLike(node)) {
hasAsyncFunctions = true;
}
if (nodeIsDecorated(node)) {
hasDecorators = true;
}
}
return hasDynamicName(node)
? bindAnonymousDeclaration(node, symbolFlags, "__computed")
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
@@ -1387,14 +1669,14 @@ namespace ts {
if (hasProperty(labelIndexMap, name.text)) {
return false;
}
labelIndexMap[name.text] = labelStack.push(Reachability.Unintialized) - 1;
labelIndexMap[name.text] = labelStack.push(Reachability.Uninitialized) - 1;
return true;
}
function pushImplicitLabel(): number {
initializeReachabilityStateIfNecessary();
const index = labelStack.push(Reachability.Unintialized) - 1;
const index = labelStack.push(Reachability.Uninitialized) - 1;
implicitLabels.push(index);
return index;
}
@@ -1424,7 +1706,7 @@ namespace ts {
}
function setCurrentStateAtLabel(innerMergedState: Reachability, outerState: Reachability, label: Identifier): void {
if (innerMergedState === Reachability.Unintialized) {
if (innerMergedState === Reachability.Uninitialized) {
if (label && !options.allowUnusedLabels) {
file.bindDiagnostics.push(createDiagnosticForNode(label, Diagnostics.Unused_label));
}
@@ -1445,7 +1727,7 @@ namespace ts {
return false;
}
const stateAtLabel = labelStack[index];
labelStack[index] = stateAtLabel === Reachability.Unintialized ? outerState : or(stateAtLabel, outerState);
labelStack[index] = stateAtLabel === Reachability.Uninitialized ? outerState : or(stateAtLabel, outerState);
return true;
}
@@ -1467,7 +1749,7 @@ namespace ts {
// unreachable code is reported if
// - user has explicitly asked about it AND
// - statement is in not ambient context (statements in ambient context is already an error
// - statement is in not ambient context (statements in ambient context is already an error
// so we should not report extras) AND
// - node is not variable statement OR
// - node is block scoped variable statement OR
+4085 -2123
View File
File diff suppressed because it is too large Load Diff
+288 -90
View File
@@ -17,6 +17,12 @@ namespace ts {
type: "boolean",
description: Diagnostics.Generates_corresponding_d_ts_file,
},
{
name: "declarationDir",
type: "string",
isFilePath: true,
paramType: Diagnostics.DIRECTORY,
},
{
name: "diagnostics",
type: "boolean",
@@ -52,7 +58,11 @@ namespace ts {
},
paramType: Diagnostics.KIND,
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
error: Diagnostics.Argument_for_jsx_must_be_preserve_or_react
},
{
name: "reactNamespace",
type: "string",
description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
},
{
name: "listFiles",
@@ -66,13 +76,14 @@ namespace ts {
name: "mapRoot",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
paramType: Diagnostics.LOCATION,
},
{
name: "module",
shortName: "m",
type: {
"none": ModuleKind.None,
"commonjs": ModuleKind.CommonJS,
"amd": ModuleKind.AMD,
"system": ModuleKind.System,
@@ -82,7 +93,6 @@ namespace ts {
},
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
paramType: Diagnostics.KIND,
error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es2015
},
{
name: "newLine",
@@ -90,9 +100,8 @@ namespace ts {
"crlf": NewLineKind.CarriageReturnLineFeed,
"lf": NewLineKind.LineFeed
},
description: Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
paramType: Diagnostics.NEWLINE,
error: Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF
},
{
name: "noEmit",
@@ -174,8 +183,8 @@ namespace ts {
name: "rootDir",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
paramType: Diagnostics.LOCATION,
description: Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
{
name: "isolatedModules",
@@ -190,7 +199,7 @@ namespace ts {
name: "sourceRoot",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
description: Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
paramType: Diagnostics.LOCATION,
},
{
@@ -219,9 +228,8 @@ namespace ts {
"es6": ScriptTarget.ES6,
"es2015": ScriptTarget.ES2015,
},
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental,
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
paramType: Diagnostics.VERSION,
error: Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES2015
},
{
name: "version",
@@ -250,10 +258,9 @@ namespace ts {
name: "moduleResolution",
type: {
"node": ModuleResolutionKind.NodeJs,
"classic": ModuleResolutionKind.Classic
"classic": ModuleResolutionKind.Classic,
},
description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
error: Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic,
description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
},
{
name: "allowUnusedLabels",
@@ -279,6 +286,80 @@ namespace ts {
name: "forceConsistentCasingInFileNames",
type: "boolean",
description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
},
{
name: "baseUrl",
type: "string",
isFilePath: true,
description: Diagnostics.Base_directory_to_resolve_non_absolute_module_names
},
{
// this option can only be specified in tsconfig.json
// use type = object to copy the value as-is
name: "paths",
type: "object",
isTSConfigOnly: true
},
{
// this option can only be specified in tsconfig.json
// use type = object to copy the value as-is
name: "rootDirs",
type: "list",
isTSConfigOnly: true,
element: {
name: "rootDirs",
type: "string",
isFilePath: true
}
},
{
name: "traceModuleResolution",
type: "boolean",
description: Diagnostics.Enable_tracing_of_the_module_resolution_process
},
{
name: "allowJs",
type: "boolean",
description: Diagnostics.Allow_javascript_files_to_be_compiled
},
{
name: "allowSyntheticDefaultImports",
type: "boolean",
description: Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
},
{
name: "noImplicitUseStrict",
type: "boolean",
description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
},
{
name: "strictNullChecks",
type: "boolean",
description: Diagnostics.Enable_strict_null_checks
}
];
/* @internal */
export let typingOptionDeclarations: CommandLineOption[] = [
{
name: "enableAutoDiscovery",
type: "boolean",
},
{
name: "include",
type: "list",
element: {
name: "include",
type: "string"
}
},
{
name: "exclude",
type: "list",
element: {
name: "exclude",
type: "string"
}
}
];
@@ -308,6 +389,16 @@ namespace ts {
return optionNameMapCache;
}
/* @internal */
export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic {
const namesOfType: string[] = [];
forEachKey(opt.type, key => {
namesOfType.push(` '${key}'`);
});
return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType);
}
export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine {
const options: CompilerOptions = {};
const fileNames: string[] = [];
@@ -324,7 +415,8 @@ namespace ts {
function parseStrings(args: string[]) {
let i = 0;
while (i < args.length) {
let s = args[i++];
let s = args[i];
i++;
if (s.charCodeAt(0) === CharacterCodes.at) {
parseResponseFile(s.slice(1));
}
@@ -339,31 +431,37 @@ namespace ts {
if (hasProperty(optionNameMap, s)) {
const opt = optionNameMap[s];
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
if (opt.isTSConfigOnly) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name));
}
else {
// Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
if (!args[i] && opt.type !== "boolean") {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i++]);
break;
case "boolean":
options[opt.name] = true;
break;
case "string":
options[opt.name] = args[i++] || "";
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
let map = <Map<number>>opt.type;
let key = (args[i++] || "").toLowerCase();
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
}
switch (opt.type) {
case "number":
options[opt.name] = parseInt(args[i]);
i++;
break;
case "boolean":
options[opt.name] = true;
break;
case "string":
options[opt.name] = args[i] || "";
i++;
break;
case "list":
options[opt.name] = parseListTypeOption(<CommandLineOptionOfListType>opt, args[i]);
i++;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
options[opt.name] = parseCustomTypeOption(<CommandLineOptionOfCustomType>opt, args[i]);
i++;
break;
}
}
}
else {
@@ -373,6 +471,29 @@ namespace ts {
else {
fileNames.push(s);
}
function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string) {
const key = (value || "").trim().toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
return map[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
function parseListTypeOption(opt: CommandLineOptionOfListType, value: string): (string | number)[] {
const values = (value || "").trim().split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
case "string":
return ts.map(values, v => v || "");
default:
return filter(map(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v)), v => !!v);
}
}
}
}
@@ -440,7 +561,6 @@ namespace ts {
}
}
/**
* Remove the comments from a json like text.
* Comments can be single line comments (starting with # or //) or multiline comments using / * * /
@@ -466,7 +586,6 @@ namespace ts {
return output;
}
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
@@ -474,19 +593,25 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine {
const { options, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath);
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string): ParsedCommandLine {
const errors: Diagnostic[] = [];
const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const options = extend(existingOptions, compilerOptions);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
const fileNames = getFileNames(errors);
return {
options,
fileNames: getFileNames(),
fileNames,
typingOptions,
errors
};
function getFileNames(): string[] {
function getFileNames(errors: Diagnostic[]): string[] {
let fileNames: string[] = [];
if (hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
if (isArray(json["files"])) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
else {
@@ -494,36 +619,96 @@ namespace ts {
}
}
else {
const exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
const sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
const name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
const baseName = name.substr(0, name.length - ".d.ts".length);
if (!contains(sysFiles, baseName + ".tsx") && !contains(sysFiles, baseName + ".ts")) {
fileNames.push(name);
}
}
else if (fileExtensionIs(name, ".ts")) {
if (!contains(sysFiles, name + "x")) {
fileNames.push(name);
}
}
else {
fileNames.push(name);
const filesSeen: Map<boolean> = {};
let exclude: string[] = [];
if (isArray(json["exclude"])) {
exclude = json["exclude"];
}
else {
// by default exclude node_modules, and any specificied output directory
exclude = ["node_modules"];
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
}
}
exclude = map(exclude, normalizeSlashes);
const supportedExtensions = getSupportedExtensions(options);
Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick");
// Get files of supported extensions in their order of resolution
for (const extension of supportedExtensions) {
const filesInDirWithExtension = host.readDirectory(basePath, extension, exclude);
for (const fileName of filesInDirWithExtension) {
// .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension,
// lets pick them when its turn comes up
if (extension === ".ts" && fileExtensionIs(fileName, ".d.ts")) {
continue;
}
// Skip over any minified JavaScript files (ending in ".min.js")
if (/\.min\.js$/.test(fileName)) {
continue;
}
// If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files)
// do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation
if (extension === ".d.ts" || (options.allowJs && contains(supportedJavascriptExtensions, extension))) {
const baseName = fileName.substr(0, fileName.length - extension.length);
if (hasProperty(filesSeen, baseName + ".ts") || hasProperty(filesSeen, baseName + ".tsx")) {
continue;
}
}
filesSeen[fileName] = true;
fileNames.push(fileName);
}
}
}
if (hasProperty(json, "excludes") && !hasProperty(json, "exclude")) {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
return fileNames;
}
}
export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { options: CompilerOptions, errors: Diagnostic[] } {
const options: CompilerOptions = {};
export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
const errors: Diagnostic[] = [];
const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
const errors: Diagnostic[] = [];
const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
function convertCompilerOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions {
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {};
convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
function convertTypingOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions {
const options: TypingOptions = getBaseFileName(configFileName) === "jsconfig.json"
? { enableAutoDiscovery: true, include: [], exclude: [] }
: { enableAutoDiscovery: false, include: [], exclude: [] };
convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors);
return options;
}
function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
if (!jsonOptions) {
return { options, errors };
return ;
}
const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name);
@@ -531,37 +716,50 @@ namespace ts {
for (const id in jsonOptions) {
if (hasProperty(optionNameMap, id)) {
const opt = optionNameMap[id];
const optType = opt.type;
let value = jsonOptions[id];
const expectedType = typeof optType === "string" ? optType : "string";
if (typeof value === expectedType) {
if (typeof optType !== "string") {
const key = value.toLowerCase();
if (hasProperty(optType, key)) {
value = optType[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
value = 0;
}
}
if (opt.isFilePath) {
value = normalizePath(combinePaths(basePath, value));
if (value === "") {
value = ".";
}
}
options[opt.name] = value;
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType));
}
defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, id));
errors.push(createCompilerDiagnostic(diagnosticMessage, id));
}
}
}
return { options, errors };
function convertJsonOption(opt: CommandLineOption, value: any, basePath: string, errors: Diagnostic[]): CompilerOptionsValue {
const optType = opt.type;
const expectedType = typeof optType === "string" ? optType : "string";
if (optType === "list" && isArray(value)) {
return convertJsonOptionOfListType(<CommandLineOptionOfListType>opt, value, basePath, errors);
}
else if (typeof value === expectedType) {
if (typeof optType !== "string") {
return convertJsonOptionOfCustomType(<CommandLineOptionOfCustomType>opt, value, errors);
}
else {
if (opt.isFilePath) {
value = normalizePath(combinePaths(basePath, value));
if (value === "") {
value = ".";
}
}
}
return value;
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType));
}
}
function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = value.toLowerCase();
if (hasProperty(opt.type, key)) {
return opt.type[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: any[], basePath: string, errors: Diagnostic[]): any[] {
return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v);
}
}
+131 -51
View File
@@ -74,8 +74,6 @@ namespace ts {
GreaterThan = 1
}
export interface StringSet extends Map<any> { }
/**
* Iterates through 'array' by index and performs the callback on each element of array until the callback
* returns a truthy value, then returns that value.
@@ -244,9 +242,17 @@ namespace ts {
const count = array.length;
if (count > 0) {
let pos = 0;
let result = arguments.length <= 2 ? array[pos++] : initial;
let result: T | U;
if (arguments.length <= 2) {
result = array[pos];
pos++;
}
else {
result = initial;
}
while (pos < count) {
result = f(<U>result, array[pos++]);
result = f(<U>result, array[pos]);
pos++;
}
return <U>result;
}
@@ -260,9 +266,17 @@ namespace ts {
if (array) {
let pos = array.length - 1;
if (pos >= 0) {
let result = arguments.length <= 2 ? array[pos--] : initial;
let result: T | U;
if (arguments.length <= 2) {
result = array[pos];
pos--;
}
else {
result = initial;
}
while (pos >= 0) {
result = f(<U>result, array[pos--]);
result = f(<U>result, array[pos]);
pos--;
}
return <U>result;
}
@@ -276,6 +290,14 @@ namespace ts {
return hasOwnProperty.call(map, key);
}
export function getKeys<T>(map: Map<T>): string[] {
const keys: string[] = [];
for (const key in map) {
keys.push(key);
}
return keys;
}
export function getProperty<T>(map: Map<T>, key: string): T {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
}
@@ -297,8 +319,8 @@ namespace ts {
return <T>result;
}
export function extend<T1, T2>(first: Map<T1>, second: Map<T2>): Map<T1 & T2> {
const result: Map<T1 & T2> = {};
export function extend<T1 extends Map<{}>, T2 extends Map<{}>>(first: T1 , second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
for (const id in first) {
(result as any)[id] = first[id];
}
@@ -356,6 +378,33 @@ namespace ts {
return result;
}
/**
* Reduce the properties of a map.
*
* @param map The map to reduce
* @param callback An aggregation function that is called for each entry in the map
* @param initial The initial value for the reduction.
*/
export function reduceProperties<T, U>(map: Map<T>, callback: (aggregate: U, value: T, key: string) => U, initial: U): U {
let result = initial;
if (map) {
for (const key in map) {
if (hasProperty(map, key)) {
result = callback(result, map[key], String(key));
}
}
}
return result;
}
/**
* Tests whether a value is an array.
*/
export function isArray(value: any): value is any[] {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
export function memoize<T>(callback: () => T): () => T {
let value: T;
return () => {
@@ -410,6 +459,17 @@ namespace ts {
};
}
/* internal */
export function formatMessage(dummy: any, message: DiagnosticMessage): string {
let text = getLocaleSpecificMessage(message);
if (arguments.length > 2) {
text = formatStringFromArgs(text, arguments, 2);
}
return text;
}
export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: any[]): Diagnostic;
export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic {
let text = getLocaleSpecificMessage(message);
@@ -585,7 +645,9 @@ namespace ts {
return path.substr(0, rootLength) + normalized.join(directorySeparator);
}
export function getDirectoryPath(path: string) {
export function getDirectoryPath(path: Path): Path;
export function getDirectoryPath(path: string): string;
export function getDirectoryPath(path: string): any {
return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator)));
}
@@ -625,7 +687,7 @@ namespace ts {
}
function getNormalizedPathComponentsOfUrl(url: string) {
// Get root length of http://www.website.com/folder1/foler2/
// Get root length of http://www.website.com/folder1/folder2/
// In this example the root is: http://www.website.com/
// normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
@@ -653,7 +715,7 @@ namespace ts {
const indexOfNextSlash = url.indexOf(directorySeparator, rootLength);
if (indexOfNextSlash !== -1) {
// Found the "/" after the website.com so the root is length of http://www.website.com/
// and get components afetr the root normally like any other folder components
// and get components after the root normally like any other folder components
rootLength = indexOfNextSlash + 1;
return normalizedPathComponents(url, rootLength);
}
@@ -685,7 +747,8 @@ namespace ts {
}
// Find the component that differs
for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
let joinStartIndex: number;
for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
break;
}
@@ -714,7 +777,7 @@ namespace ts {
}
export function getBaseFileName(path: string) {
if (!path) {
if (path === undefined) {
return undefined;
}
const i = path.lastIndexOf(directorySeparator);
@@ -735,21 +798,47 @@ namespace ts {
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
export function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind {
// Using scriptKind as a condition handles both:
// - 'scriptKind' is unspecified and thus it is `undefined`
// - 'scriptKind' is set and it is `Unknown` (0)
// If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
// to get the ScriptKind from the file name. If it cannot be resolved
// from the file name then the default 'TS' script kind is returned.
return (scriptKind || getScriptKindFromFileName(fileName)) || ScriptKind.TS;
}
export function getScriptKindFromFileName(fileName: string): ScriptKind {
const ext = fileName.substr(fileName.lastIndexOf("."));
switch (ext.toLowerCase()) {
case ".js":
return ScriptKind.JS;
case ".jsx":
return ScriptKind.JSX;
case ".ts":
return ScriptKind.TS;
case ".tsx":
return ScriptKind.TSX;
default:
return ScriptKind.Unknown;
}
}
/**
* List of supported extensions in order of file resolution precedence.
*/
export const supportedExtensions = [".ts", ".tsx", ".d.ts"];
/**
* List of extensions that will be used to look for external modules.
* This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation,
* but still would like to load only TypeScript files as modules
*/
export const moduleFileExtensions = supportedExtensions;
export const supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"];
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
export function isSupportedSourceFileName(fileName: string) {
export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
}
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
if (!fileName) { return false; }
for (const extension of supportedExtensions) {
for (const extension of getSupportedExtensions(compilerOptions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
@@ -767,25 +856,9 @@ namespace ts {
return path;
}
const backslashOrDoubleQuote = /[\"\\]/g;
const escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
const escapedCharsMap: Map<string> = {
"\0": "\\0",
"\t": "\\t",
"\v": "\\v",
"\f": "\\f",
"\b": "\\b",
"\r": "\\r",
"\n": "\\n",
"\\": "\\\\",
"\"": "\\\"",
"\u2028": "\\u2028", // lineSeparator
"\u2029": "\\u2029", // paragraphSeparator
"\u0085": "\\u0085" // nextLine
};
export interface ObjectAllocator {
getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node;
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
@@ -804,17 +877,17 @@ namespace ts {
function Signature(checker: TypeChecker) {
}
function Node(kind: SyntaxKind, pos: number, end: number) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = NodeFlags.None;
this.parent = undefined;
}
export let objectAllocator: ObjectAllocator = {
getNodeConstructor: kind => {
function Node(pos: number, end: number) {
this.pos = pos;
this.end = end;
this.flags = NodeFlags.None;
this.parent = undefined;
}
Node.prototype = { kind };
return <any>Node;
},
getNodeConstructor: () => <any>Node,
getSourceFileConstructor: () => <any>Node,
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,
getSignatureConstructor: () => <any>Signature
@@ -846,7 +919,7 @@ namespace ts {
}
export function fail(message?: string): void {
Debug.assert(false, message);
Debug.assert(/*expression*/ false, message);
}
}
@@ -859,4 +932,11 @@ namespace ts {
}
return copiedList;
}
export function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string {
return useCaseSensitivefileNames
? ((fileName) => fileName)
: ((fileName) => fileName.toLowerCase());
}
}
File diff suppressed because it is too large Load Diff
+377 -61
View File
@@ -1,4 +1,4 @@
{
{
"Unterminated string literal.": {
"category": "Error",
"code": 1002
@@ -67,6 +67,10 @@
"category": "Error",
"code": 1023
},
"'readonly' modifier can only appear on a property declaration or index signature.": {
"category": "Error",
"code": 1024
},
"Accessibility modifier already seen.": {
"category": "Error",
"code": 1028
@@ -119,7 +123,7 @@
"category": "Error",
"code": 1043
},
"'{0}' modifier cannot appear on a module element.": {
"'{0}' modifier cannot appear on a module or namespace element.": {
"category": "Error",
"code": 1044
},
@@ -195,6 +199,10 @@
"category": "Error",
"code": 1063
},
"The return type of an async function or method must be the global Promise<T> type.": {
"category": "Error",
"code": 1064
},
"In ambient enum declarations member initializer must be constant expression.": {
"category": "Error",
"code": 1066
@@ -203,6 +211,14 @@
"category": "Error",
"code": 1068
},
"'{0}' modifier cannot appear on a type member.": {
"category": "Error",
"code": 1070
},
"'{0}' modifier cannot appear on an index signature.": {
"category": "Error",
"code": 1071
},
"A '{0}' modifier cannot be used with an import declaration.": {
"category": "Error",
"code": 1079
@@ -423,10 +439,6 @@
"category": "Error",
"code": 1144
},
"Modifiers not permitted on index signature members.": {
"category": "Error",
"code": 1145
},
"Declaration expected.": {
"category": "Error",
"code": 1146
@@ -435,7 +447,7 @@
"category": "Error",
"code": 1147
},
"Cannot compile modules unless the '--module' flag is provided.": {
"Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file.": {
"category": "Error",
"code": 1148
},
@@ -675,7 +687,7 @@
"category": "Error",
"code": 1218
},
"Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": {
"Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.": {
"category": "Error",
"code": 1219
},
@@ -767,7 +779,7 @@
"category": "Error",
"code": 1241
},
"'abstract' modifier can only appear on a class or method declaration.": {
"'abstract' modifier can only appear on a class, method, or property declaration.": {
"category": "Error",
"code": 1242
},
@@ -783,7 +795,22 @@
"category": "Error",
"code": 1245
},
"An interface property cannot have an initializer.": {
"category": "Error",
"code": 1246
},
"A type literal property cannot have an initializer.": {
"category": "Error",
"code": 1247
},
"A class member cannot have the '{0}' keyword.": {
"category": "Error",
"code": 1248
},
"A decorator can only decorate a method implementation, not an overload.": {
"category": "Error",
"code": 1249
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
@@ -804,6 +831,18 @@
"category": "Error",
"code": 1313
},
"Global module exports may only appear in module files.": {
"category": "Error",
"code": 1314
},
"Global module exports may only appear in declaration files.": {
"category": "Error",
"code": 1315
},
"Global module exports may only appear at top level.": {
"category": "Error",
"code": 1316
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -836,6 +875,10 @@
"category": "Error",
"code": 2307
},
"Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity.": {
"category": "Error",
"code": 2308
},
"An export assignment cannot be used in a module with other exported elements.": {
"category": "Error",
"code": 2309
@@ -852,7 +895,7 @@
"category": "Error",
"code": 2312
},
"Constraint of a type parameter cannot reference any type parameter from the same type parameter list.": {
"Type parameter '{0}' has a circular constraint.": {
"category": "Error",
"code": 2313
},
@@ -892,7 +935,7 @@
"category": "Error",
"code": 2322
},
"Type '{0}' is not comparable to type '{1}'.": {
"Cannot redeclare exported variable '{0}'.": {
"category": "Error",
"code": 2323
},
@@ -1060,6 +1103,10 @@
"category": "Error",
"code": 2365
},
"Function lacks ending return statement and return type does not include 'undefined'.": {
"category": "Error",
"code": 2366
},
"Type parameter name cannot be '{0}'": {
"category": "Error",
"code": 2368
@@ -1120,7 +1167,7 @@
"category": "Error",
"code": 2382
},
"Overload signatures must all be exported or not exported.": {
"Overload signatures must all be exported or non-exported.": {
"category": "Error",
"code": 2383
},
@@ -1176,6 +1223,10 @@
"category": "Error",
"code": 2396
},
"Declaration name conflicts with built-in global identifier '{0}'.": {
"category": "Error",
"code": 2397
},
"Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference.": {
"category": "Error",
"code": 2399
@@ -1248,10 +1299,6 @@
"category": "Error",
"code": 2417
},
"Type name '{0}' in extends clause does not reference constructor function for '{0}'.": {
"category": "Error",
"code": 2419
},
"Class '{0}' incorrectly implements interface '{1}'.": {
"category": "Error",
"code": 2420
@@ -1280,7 +1327,7 @@
"category": "Error",
"code": 2427
},
"All declarations of an interface must have identical type parameters.": {
"All declarations of '{0}' must have identical type parameters.": {
"category": "Error",
"code": 2428
},
@@ -1360,11 +1407,11 @@
"category": "Error",
"code": 2448
},
"The operand of an increment or decrement operator cannot be a constant.": {
"The operand of an increment or decrement operator cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2449
},
"Left-hand side of assignment expression cannot be a constant.": {
"Left-hand side of assignment expression cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2450
},
@@ -1380,6 +1427,10 @@
"category": "Error",
"code": 2453
},
"Variable '{0}' is used before being assigned.": {
"category": "Error",
"code": 2454
},
"Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'.": {
"category": "Error",
"code": 2455
@@ -1496,11 +1547,11 @@
"category": "Error",
"code": 2484
},
"The left-hand side of a 'for...of' statement cannot be a previously defined constant.": {
"The left-hand side of a 'for...of' statement cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2485
},
"The left-hand side of a 'for...in' statement cannot be a previously defined constant.": {
"The left-hand side of a 'for...in' statement cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2486
},
@@ -1604,7 +1655,7 @@
"category": "Error",
"code": 2511
},
"Overload signatures must all be abstract or not abstract.": {
"Overload signatures must all be abstract or non-abstract.": {
"category": "Error",
"code": 2512
},
@@ -1626,7 +1677,11 @@
},
"Cannot assign an abstract constructor type to a non-abstract constructor type.": {
"category": "Error",
"code":2517
"code": 2517
},
"A 'this'-based type guard is not compatible with a parameter-based type guard.": {
"category": "Error",
"code": 2518
},
"Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": {
"category": "Error",
@@ -1664,7 +1719,19 @@
"category": "Error",
"code": 2528
},
"JSX element attributes type '{0}' must be an object type.": {
"Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions.": {
"category": "Error",
"code": 2529
},
"Property '{0}' is incompatible with index signature.": {
"category": "Error",
"code": 2530
},
"Object is possibly 'null' or 'undefined'.": {
"category": "Error",
"code": 2531
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
},
@@ -1728,6 +1795,90 @@
"category": "Error",
"code": 2657
},
"Type '{0}' provides no match for the signature '{1}'": {
"category": "Error",
"code": 2658
},
"'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher.": {
"category": "Error",
"code": 2659
},
"'super' can only be referenced in members of derived classes or object literal expressions.": {
"category": "Error",
"code": 2660
},
"Cannot re-export name that is not defined in the module.": {
"category": "Error",
"code": 2661
},
"Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?": {
"category": "Error",
"code": 2662
},
"Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?": {
"category": "Error",
"code": 2663
},
"Invalid module name in augmentation, module '{0}' cannot be found.": {
"category": "Error",
"code": 2664
},
"Module augmentation cannot introduce new names in the top level scope.": {
"category": "Error",
"code": 2665
},
"Exports and export assignments are not permitted in module augmentations.": {
"category": "Error",
"code": 2666
},
"Imports are not permitted in module augmentations. Consider moving them to the enclosing external module.": {
"category": "Error",
"code": 2667
},
"'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible.": {
"category": "Error",
"code": 2668
},
"Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.": {
"category": "Error",
"code": 2669
},
"Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context.": {
"category": "Error",
"code": 2670
},
"Cannot augment module '{0}' because it resolves to a non-module entity.": {
"category": "Error",
"code": 2671
},
"Cannot assign a '{0}' constructor type to a '{1}' constructor type.": {
"category": "Error",
"code": 2672
},
"Constructor of class '{0}' is private and only accessible within the class declaration.": {
"category": "Error",
"code": 2673
},
"Constructor of class '{0}' is protected and only accessible within the class declaration.": {
"category": "Error",
"code": 2674
},
"Cannot extend a class '{0}'. Class constructor is marked as private.": {
"category": "Error",
"code": 2675
},
"Accessors must both be abstract or non-abstract.": {
"category": "Error",
"code": 2676
},
"A type predicate's type must be assignable to its parameter's type.": {
"category": "Error",
"code": 2677
},
"Type '{0}' is not comparable to type '{1}'.": {
"category": "Error",
"code": 2678
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2064,6 +2215,38 @@
"category": "Error",
"code": 5054
},
"Cannot write file '{0}' because it would overwrite input file.": {
"category": "Error",
"code": 5055
},
"Cannot write file '{0}' because it would be overwritten by multiple input files.": {
"category": "Error",
"code": 5056
},
"Cannot find a tsconfig.json file at the specified directory: '{0}'": {
"category": "Error",
"code": 5057
},
"The specified path does not exist: '{0}'": {
"category": "Error",
"code": 5058
},
"Invalid value for '--reactNamespace'. '{0}' is not a valid identifier.": {
"category": "Error",
"code": 5059
},
"Option 'paths' cannot be used without specifying '--baseUrl' option.": {
"category": "Error",
"code": 5060
},
"Pattern '{0}' can have at most one '*' character": {
"category": "Error",
"code": 5061
},
"Substitution '{0}' in pattern '{1}' in can have at most one '*' character": {
"category": "Error",
"code": 5062
},
"Concatenate and emit output to single file.": {
"category": "Message",
@@ -2073,11 +2256,11 @@
"category": "Message",
"code": 6002
},
"Specifies the location where debugger should locate map files instead of generated locations.": {
"Specify the location where debugger should locate map files instead of generated locations.": {
"category": "Message",
"code": 6003
},
"Specifies the location where debugger should locate TypeScript files instead of source locations.": {
"Specify the location where debugger should locate TypeScript files instead of source locations.": {
"category": "Message",
"code": 6004
},
@@ -2105,10 +2288,14 @@
"category": "Message",
"code": 6010
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": {
"category": "Message",
"code": 6015
},
"Allow default imports from modules with no default export. This does not affect code emit, just typechecking.": {
"category": "Message",
"code": 6011
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": {
"category": "Message",
"code": 6015
},
"Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'": {
"category": "Message",
"code": 6016
@@ -2193,14 +2380,10 @@
"category": "Error",
"code": 6045
},
"Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es2015'.": {
"Argument for '{0}' option must be: {1}": {
"category": "Error",
"code": 6046
},
"Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.": {
"category": "Error",
"code": 6047
},
"Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'.": {
"category": "Error",
"code": 6048
@@ -2237,7 +2420,7 @@
"category": "Message",
"code": 6056
},
"Specifies the root directory of input files. Use to control the output directory structure with --outDir.": {
"Specify the root directory of input files. Use to control the output directory structure with --outDir.": {
"category": "Message",
"code": 6058
},
@@ -2245,7 +2428,7 @@
"category": "Error",
"code": 6059
},
"Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"category": "Message",
"code": 6060
},
@@ -2253,15 +2436,10 @@
"category": "Message",
"code": 6061
},
"Argument for '--newLine' option must be 'CRLF' or 'LF'.": {
"Option '{0}' can only be specified in 'tsconfig.json' file.": {
"category": "Error",
"code": 6062
"code": 6064
},
"Argument for '--moduleResolution' option must be 'node' or 'classic'.": {
"category": "Error",
"code": 6063
},
"Enables experimental support for ES7 decorators.": {
"category": "Message",
"code": 6065
@@ -2274,7 +2452,7 @@
"category": "Message",
"code": 6068
},
"Specifies module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"category": "Message",
"code": 6069
},
@@ -2314,14 +2492,141 @@
"category": "Message",
"code": 6078
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
},
"Argument for '--jsx' must be 'preserve' or 'react'.": {
"Only 'amd' and 'system' modules are supported alongside --{0}.": {
"category": "Error",
"code": 6082
},
"Base directory to resolve non-absolute module names.": {
"category": "Message",
"code": 6081
"code": 6083
},
"Specify the object invoked for createElement and __spread when targeting 'react' JSX emit": {
"category": "Message",
"code": 6084
},
"Enable tracing of the module resolution process.": {
"category": "Message",
"code": 6085
},
"======== Resolving module '{0}' from '{1}'. ========": {
"category": "Message",
"code": 6086
},
"Explicitly specified module resolution kind: '{0}'.": {
"category": "Message",
"code": 6087
},
"Module resolution kind is not specified, using '{0}'.": {
"category": "Message",
"code": 6088
},
"======== Module name '{0}' was successfully resolved to '{1}'. ========": {
"category": "Message",
"code": 6089
},
"======== Module name '{0}' was not resolved. ========": {
"category": "Message",
"code": 6090
},
"'paths' option is specified, looking for a pattern to match module name '{0}'.": {
"category": "Message",
"code": 6091
},
"Module name '{0}', matched pattern '{1}'.": {
"category": "Message",
"code": 6092
},
"Trying substitution '{0}', candidate module location: '{1}'.": {
"category": "Message",
"code": 6093
},
"Resolving module name '{0}' relative to base url '{1}' - '{2}'.": {
"category": "Message",
"code": 6094
},
"Loading module as file / folder, candidate module location '{0}'.": {
"category": "Message",
"code": 6095
},
"File '{0}' does not exist.": {
"category": "Message",
"code": 6096
},
"File '{0}' exist - use it as a module resolution result.": {
"category": "Message",
"code": 6097
},
"Loading module '{0}' from 'node_modules' folder.": {
"category": "Message",
"code": 6098
},
"Found 'package.json' at '{0}'.": {
"category": "Message",
"code": 6099
},
"'package.json' does not have 'typings' field.": {
"category": "Message",
"code": 6100
},
"'package.json' has 'typings' field '{0}' that references '{1}'.": {
"category": "Message",
"code": 6101
},
"Allow javascript files to be compiled.": {
"category": "Message",
"code": 6102
},
"Option '{0}' should have array of strings as a value.": {
"category": "Error",
"code": 6103
},
"Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'.": {
"category": "Message",
"code": 6104
},
"Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'.": {
"category": "Message",
"code": 6105
},
"'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'": {
"category": "Message",
"code": 6106
},
"'rootDirs' option is set, using it to resolve relative module name '{0}'": {
"category": "Message",
"code": 6107
},
"Longest matching prefix for '{0}' is '{1}'": {
"category": "Message",
"code": 6108
},
"Loading '{0}' from the root dir '{1}', candidate location '{2}'": {
"category": "Message",
"code": 6109
},
"Trying other entries in 'rootDirs'": {
"category": "Message",
"code": 6110
},
"Module resolution using 'rootDirs' has failed": {
"category": "Message",
"code": 6111
},
"Do not emit 'use strict' directives in module output.": {
"category": "Message",
"code": 6112
},
"Enable strict null checks.": {
"category": "Message",
"code": 6113
},
"Unknown option 'excludes'. Did you mean 'exclude'?": {
"category": "Error",
"code": 6114
},
"Variable '{0}' implicitly has an '{1}' type.": {
@@ -2352,6 +2657,10 @@
"category": "Error",
"code": 7013
},
"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
@@ -2407,7 +2716,7 @@
"Not all code paths return a value.": {
"category": "Error",
"code": 7030
},
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@@ -2472,11 +2781,6 @@
"category": "Error",
"code": 8016
},
"'decorators' can only be used in a .ts file.": {
"category": "Error",
"code": 8017
},
"Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses.": {
"category": "Error",
"code": 9002
@@ -2506,15 +2810,27 @@
"code": 17004
},
"A constructor cannot contain a 'super' call when its class extends 'null'": {
"category": "Error",
"code": 17005
"category": "Error",
"code": 17005
},
"An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": {
"category": "Error",
"code": 17006
"category": "Error",
"code": 17006
},
"A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses.": {
"category": "Error",
"code": 17007
"category": "Error",
"code": 17007
},
"JSX element '{0}' has no corresponding closing tag.": {
"category": "Error",
"code": 17008
},
"'super' must be called before accessing 'this' in the constructor of a derived class.": {
"category": "Error",
"code": 17009
},
"Unknown typing option '{0}'.": {
"category": "Error",
"code": 17010
}
}
+1163 -1032
View File
File diff suppressed because it is too large Load Diff
+602 -466
View File
File diff suppressed because it is too large Load Diff
+917 -195
View File
File diff suppressed because it is too large Load Diff
+189 -43
View File
@@ -29,6 +29,7 @@ namespace ts {
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scanJSDocToken(): SyntaxKind;
scan(): SyntaxKind;
// Sets the text for the scanner to scan. An optional subrange starting point and length
// can be provided to have the scanner only scan a portion of the text.
@@ -42,6 +43,10 @@ namespace ts {
// is returned from this function.
lookAhead<T>(callback: () => T): T;
// Invokes the callback with the scanner set to scan the specified range. When the callback
// returns, the scanner is restored to the state it was in before scanRange was called.
scanRange<T>(start: number, length: number, callback: () => T): T;
// Invokes the provided callback. If the callback returns something falsy, then it restores
// the scanner to the state it was in immediately prior to invoking the callback. If the
// callback returns something truthy, then the scanner state is not rolled back. The result
@@ -93,7 +98,9 @@ namespace ts {
"private": SyntaxKind.PrivateKeyword,
"protected": SyntaxKind.ProtectedKeyword,
"public": SyntaxKind.PublicKeyword,
"readonly": SyntaxKind.ReadonlyKeyword,
"require": SyntaxKind.RequireKeyword,
"global": SyntaxKind.GlobalKeyword,
"return": SyntaxKind.ReturnKeyword,
"set": SyntaxKind.SetKeyword,
"static": SyntaxKind.StaticKeyword,
@@ -107,6 +114,7 @@ namespace ts {
"try": SyntaxKind.TryKeyword,
"type": SyntaxKind.TypeKeyword,
"typeof": SyntaxKind.TypeOfKeyword,
"undefined": SyntaxKind.UndefinedKeyword,
"var": SyntaxKind.VarKeyword,
"void": SyntaxKind.VoidKeyword,
"while": SyntaxKind.WhileKeyword,
@@ -288,7 +296,8 @@ namespace ts {
let pos = 0;
let lineStart = 0;
while (pos < text.length) {
const ch = text.charCodeAt(pos++);
const ch = text.charCodeAt(pos);
pos++;
switch (ch) {
case CharacterCodes.carriageReturn:
if (text.charCodeAt(pos) === CharacterCodes.lineFeed) {
@@ -425,6 +434,12 @@ namespace ts {
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): 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)) {
return pos;
}
// Keep in sync with couldStartTrivia
while (true) {
const ch = text.charCodeAt(pos);
@@ -497,7 +512,7 @@ namespace ts {
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
// a <<<<<<< or >>>>>>> marker then it is also followed by a space.
const mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text: string, pos: number) {
@@ -537,7 +552,7 @@ namespace ts {
}
else {
Debug.assert(ch === CharacterCodes.equals);
// Consume everything from the start of the mid-conlict marker to the start of the next
// Consume everything from the start of the mid-conflict marker to the start of the next
// end-conflict marker.
while (pos < len) {
const ch = text.charCodeAt(pos);
@@ -567,12 +582,12 @@ namespace ts {
}
/**
* Extract comments from text prefixing the token closest following `pos`.
* 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
* @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.
@@ -580,7 +595,7 @@ namespace ts {
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
let collecting = trailing || pos === 0;
while (true) {
while (pos < text.length) {
const ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
@@ -650,6 +665,8 @@ namespace ts {
}
return result;
}
return result;
}
export function getLeadingCommentRanges(text: string, pos: number): CommentRange[] {
@@ -679,6 +696,21 @@ namespace ts {
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
export function isIdentifier(name: string, languageVersion: ScriptTarget): boolean {
if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) {
return false;
}
for (let i = 1, n = name.length; i < n; i++) {
if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) {
return false;
}
}
return true;
}
// Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
@@ -725,6 +757,7 @@ namespace ts {
scanJsxIdentifier,
reScanJsxToken,
scanJsxToken,
scanJSDocToken,
scan,
setText,
setScriptTarget,
@@ -733,6 +766,7 @@ namespace ts {
setTextPos,
tryScan,
lookAhead,
scanRange,
};
function error(message: DiagnosticMessage, length?: number): void {
@@ -741,7 +775,7 @@ namespace ts {
}
}
function scanNumber(): number {
function scanNumber(): string {
const start = pos;
while (isDigit(text.charCodeAt(pos))) pos++;
if (text.charCodeAt(pos) === CharacterCodes.dot) {
@@ -761,7 +795,7 @@ namespace ts {
error(Diagnostics.Digit_expected);
}
}
return +(text.substring(start, end));
return "" + +(text.substring(start, end));
}
function scanOctalDigits(): number {
@@ -815,7 +849,8 @@ namespace ts {
}
function scanString(): string {
const quote = text.charCodeAt(pos++);
const quote = text.charCodeAt(pos);
pos++;
let result = "";
let start = pos;
while (true) {
@@ -925,7 +960,8 @@ namespace ts {
error(Diagnostics.Unexpected_end_of_text);
return "";
}
const ch = text.charCodeAt(pos++);
const ch = text.charCodeAt(pos);
pos++;
switch (ch) {
case CharacterCodes._0:
return "\0";
@@ -1174,7 +1210,8 @@ namespace ts {
}
return pos += 2, token = SyntaxKind.ExclamationEqualsToken;
}
return pos++, token = SyntaxKind.ExclamationToken;
pos++;
return token = SyntaxKind.ExclamationToken;
case CharacterCodes.doubleQuote:
case CharacterCodes.singleQuote:
tokenValue = scanString();
@@ -1185,7 +1222,8 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.PercentEqualsToken;
}
return pos++, token = SyntaxKind.PercentToken;
pos++;
return token = SyntaxKind.PercentToken;
case CharacterCodes.ampersand:
if (text.charCodeAt(pos + 1) === CharacterCodes.ampersand) {
return pos += 2, token = SyntaxKind.AmpersandAmpersandToken;
@@ -1193,11 +1231,14 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.AmpersandEqualsToken;
}
return pos++, token = SyntaxKind.AmpersandToken;
pos++;
return token = SyntaxKind.AmpersandToken;
case CharacterCodes.openParen:
return pos++, token = SyntaxKind.OpenParenToken;
pos++;
return token = SyntaxKind.OpenParenToken;
case CharacterCodes.closeParen:
return pos++, token = SyntaxKind.CloseParenToken;
pos++;
return token = SyntaxKind.CloseParenToken;
case CharacterCodes.asterisk:
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.AsteriskEqualsToken;
@@ -1208,7 +1249,8 @@ namespace ts {
}
return pos += 2, token = SyntaxKind.AsteriskAsteriskToken;
}
return pos++, token = SyntaxKind.AsteriskToken;
pos++;
return token = SyntaxKind.AsteriskToken;
case CharacterCodes.plus:
if (text.charCodeAt(pos + 1) === CharacterCodes.plus) {
return pos += 2, token = SyntaxKind.PlusPlusToken;
@@ -1216,9 +1258,11 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.PlusEqualsToken;
}
return pos++, token = SyntaxKind.PlusToken;
pos++;
return token = SyntaxKind.PlusToken;
case CharacterCodes.comma:
return pos++, token = SyntaxKind.CommaToken;
pos++;
return token = SyntaxKind.CommaToken;
case CharacterCodes.minus:
if (text.charCodeAt(pos + 1) === CharacterCodes.minus) {
return pos += 2, token = SyntaxKind.MinusMinusToken;
@@ -1226,16 +1270,18 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.MinusEqualsToken;
}
return pos++, token = SyntaxKind.MinusToken;
pos++;
return token = SyntaxKind.MinusToken;
case CharacterCodes.dot:
if (isDigit(text.charCodeAt(pos + 1))) {
tokenValue = "" + scanNumber();
tokenValue = scanNumber();
return token = SyntaxKind.NumericLiteral;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.dot && text.charCodeAt(pos + 2) === CharacterCodes.dot) {
return pos += 3, token = SyntaxKind.DotDotDotToken;
}
return pos++, token = SyntaxKind.DotToken;
pos++;
return token = SyntaxKind.DotToken;
case CharacterCodes.slash:
// Single-line comment
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
@@ -1293,7 +1339,8 @@ namespace ts {
return pos += 2, token = SyntaxKind.SlashEqualsToken;
}
return pos++, token = SyntaxKind.SlashToken;
pos++;
return token = SyntaxKind.SlashToken;
case CharacterCodes._0:
if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.X || text.charCodeAt(pos + 1) === CharacterCodes.x)) {
@@ -1343,12 +1390,14 @@ namespace ts {
case CharacterCodes._7:
case CharacterCodes._8:
case CharacterCodes._9:
tokenValue = "" + scanNumber();
tokenValue = scanNumber();
return token = SyntaxKind.NumericLiteral;
case CharacterCodes.colon:
return pos++, token = SyntaxKind.ColonToken;
pos++;
return token = SyntaxKind.ColonToken;
case CharacterCodes.semicolon:
return pos++, token = SyntaxKind.SemicolonToken;
pos++;
return token = SyntaxKind.SemicolonToken;
case CharacterCodes.lessThan:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
@@ -1374,7 +1423,8 @@ namespace ts {
text.charCodeAt(pos + 2) !== CharacterCodes.asterisk) {
return pos += 2, token = SyntaxKind.LessThanSlashToken;
}
return pos++, token = SyntaxKind.LessThanToken;
pos++;
return token = SyntaxKind.LessThanToken;
case CharacterCodes.equals:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
@@ -1395,7 +1445,8 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.greaterThan) {
return pos += 2, token = SyntaxKind.EqualsGreaterThanToken;
}
return pos++, token = SyntaxKind.EqualsToken;
pos++;
return token = SyntaxKind.EqualsToken;
case CharacterCodes.greaterThan:
if (isConflictMarkerTrivia(text, pos)) {
pos = scanConflictMarkerTrivia(text, pos, error);
@@ -1407,20 +1458,26 @@ namespace ts {
}
}
return pos++, token = SyntaxKind.GreaterThanToken;
pos++;
return token = SyntaxKind.GreaterThanToken;
case CharacterCodes.question:
return pos++, token = SyntaxKind.QuestionToken;
pos++;
return token = SyntaxKind.QuestionToken;
case CharacterCodes.openBracket:
return pos++, token = SyntaxKind.OpenBracketToken;
pos++;
return token = SyntaxKind.OpenBracketToken;
case CharacterCodes.closeBracket:
return pos++, token = SyntaxKind.CloseBracketToken;
pos++;
return token = SyntaxKind.CloseBracketToken;
case CharacterCodes.caret:
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.CaretEqualsToken;
}
return pos++, token = SyntaxKind.CaretToken;
pos++;
return token = SyntaxKind.CaretToken;
case CharacterCodes.openBrace:
return pos++, token = SyntaxKind.OpenBraceToken;
pos++;
return token = SyntaxKind.OpenBraceToken;
case CharacterCodes.bar:
if (text.charCodeAt(pos + 1) === CharacterCodes.bar) {
return pos += 2, token = SyntaxKind.BarBarToken;
@@ -1428,13 +1485,17 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.BarEqualsToken;
}
return pos++, token = SyntaxKind.BarToken;
pos++;
return token = SyntaxKind.BarToken;
case CharacterCodes.closeBrace:
return pos++, token = SyntaxKind.CloseBraceToken;
pos++;
return token = SyntaxKind.CloseBraceToken;
case CharacterCodes.tilde:
return pos++, token = SyntaxKind.TildeToken;
pos++;
return token = SyntaxKind.TildeToken;
case CharacterCodes.at:
return pos++, token = SyntaxKind.AtToken;
pos++;
return token = SyntaxKind.AtToken;
case CharacterCodes.backslash:
let cookedChar = peekUnicodeEscape();
if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
@@ -1443,7 +1504,8 @@ namespace ts {
return token = getIdentifierToken();
}
error(Diagnostics.Invalid_character);
return pos++, token = SyntaxKind.Unknown;
pos++;
return token = SyntaxKind.Unknown;
default:
if (isIdentifierStart(ch, languageVersion)) {
pos++;
@@ -1464,7 +1526,8 @@ namespace ts {
continue;
}
error(Diagnostics.Invalid_character);
return pos++, token = SyntaxKind.Unknown;
pos++;
return token = SyntaxKind.Unknown;
}
}
}
@@ -1481,10 +1544,12 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.GreaterThanGreaterThanEqualsToken;
}
return pos++, token = SyntaxKind.GreaterThanGreaterThanToken;
pos++;
return token = SyntaxKind.GreaterThanGreaterThanToken;
}
if (text.charCodeAt(pos) === CharacterCodes.equals) {
return pos++, token = SyntaxKind.GreaterThanEqualsToken;
pos++;
return token = SyntaxKind.GreaterThanEqualsToken;
}
}
return token;
@@ -1609,6 +1674,60 @@ namespace ts {
return token;
}
function scanJSDocToken(): SyntaxKind {
if (pos >= end) {
return token = SyntaxKind.EndOfFileToken;
}
startPos = pos;
// Eat leading whitespace
let ch = text.charCodeAt(pos);
while (pos < end) {
ch = text.charCodeAt(pos);
if (isWhiteSpace(ch)) {
pos++;
}
else {
break;
}
}
tokenPos = pos;
switch (ch) {
case CharacterCodes.at:
return pos += 1, token = SyntaxKind.AtToken;
case CharacterCodes.lineFeed:
case CharacterCodes.carriageReturn:
return pos += 1, token = SyntaxKind.NewLineTrivia;
case CharacterCodes.asterisk:
return pos += 1, token = SyntaxKind.AsteriskToken;
case CharacterCodes.openBrace:
return pos += 1, token = SyntaxKind.OpenBraceToken;
case CharacterCodes.closeBrace:
return pos += 1, token = SyntaxKind.CloseBraceToken;
case CharacterCodes.openBracket:
return pos += 1, token = SyntaxKind.OpenBracketToken;
case CharacterCodes.closeBracket:
return pos += 1, token = SyntaxKind.CloseBracketToken;
case CharacterCodes.equals:
return pos += 1, token = SyntaxKind.EqualsToken;
case CharacterCodes.comma:
return pos += 1, token = SyntaxKind.CommaToken;
}
if (isIdentifierStart(ch, ScriptTarget.Latest)) {
pos++;
while (isIdentifierPart(text.charCodeAt(pos), ScriptTarget.Latest) && pos < end) {
pos++;
}
return token = SyntaxKind.Identifier;
}
else {
return pos += 1, token = SyntaxKind.Unknown;
}
}
function speculationHelper<T>(callback: () => T, isLookahead: boolean): T {
const savePos = pos;
const saveStartPos = startPos;
@@ -1631,12 +1750,39 @@ namespace ts {
return result;
}
function scanRange<T>(start: number, length: number, callback: () => T): T {
const saveEnd = end;
const savePos = pos;
const saveStartPos = startPos;
const saveTokenPos = tokenPos;
const saveToken = token;
const savePrecedingLineBreak = precedingLineBreak;
const saveTokenValue = tokenValue;
const saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
const saveTokenIsUnterminated = tokenIsUnterminated;
setText(text, start, length);
const result = callback();
end = saveEnd;
pos = savePos;
startPos = saveStartPos;
tokenPos = saveTokenPos;
token = saveToken;
precedingLineBreak = savePrecedingLineBreak;
tokenValue = saveTokenValue;
hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape;
tokenIsUnterminated = saveTokenIsUnterminated;
return result;
}
function lookAhead<T>(callback: () => T): T {
return speculationHelper(callback, /*isLookahead:*/ true);
return speculationHelper(callback, /*isLookahead*/ true);
}
function tryScan<T>(callback: () => T): T {
return speculationHelper(callback, /*isLookahead:*/ false);
return speculationHelper(callback, /*isLookahead*/ false);
}
function setText(newText: string, start: number, length: number) {
+394
View File
@@ -0,0 +1,394 @@
/// <reference path="checker.ts"/>
/* @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(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void;
reset(): void;
}
let nullSourceMapWriter: SourceMapWriter;
// Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans
const defaultLastEncodedSourceMapSpan: SourceMapSpan = {
emittedLine: 1,
emittedColumn: 1,
sourceLine: 1,
sourceColumn: 1,
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 {
const compilerOptions = host.getCompilerOptions();
let currentSourceFile: SourceFile;
let sourceMapDir: string; // The directory in which sourcemap will be
let stopOverridingSpan = false;
let modifyLastSourcePos = false;
// Current source map file and its index in the sources list
let sourceMapSourceIndex: number;
// Last recorded and encoded spans
let lastRecordedSourceMapSpan: SourceMapSpan;
let lastEncodedSourceMapSpan: SourceMapSpan;
let lastEncodedNameIndex: number;
// Source map data
let sourceMapData: SourceMapData;
return {
getSourceMapData: () => sourceMapData,
setSourceFile,
emitPos,
emitStart,
emitEnd,
changeEmitSourcePos,
getText,
getSourceMappingURL,
initialize,
reset,
};
function initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) {
if (sourceMapData) {
reset();
}
currentSourceFile = undefined;
// Current source map file and its index in the sources list
sourceMapSourceIndex = -1;
// Last recorded and encoded spans
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan;
lastEncodedNameIndex = 0;
// Initialize source map data
sourceMapData = {
sourceMapFilePath: sourceMapFilePath,
jsSourceMappingURL: !compilerOptions.inlineSourceMap ? getBaseFileName(normalizeSlashes(sourceMapFilePath)) : undefined,
sourceMapFile: getBaseFileName(normalizeSlashes(filePath)),
sourceMapSourceRoot: compilerOptions.sourceRoot || "",
sourceMapSources: [],
inputSourceFileNames: [],
sourceMapNames: [],
sourceMapMappings: "",
sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined,
sourceMapDecodedMappings: []
};
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
// relative paths of the sources list in the sourcemap
sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot);
if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== CharacterCodes.slash) {
sourceMapData.sourceMapSourceRoot += directorySeparator;
}
if (compilerOptions.mapRoot) {
sourceMapDir = normalizeSlashes(compilerOptions.mapRoot);
if (!isBundledEmit) { // emitting single module file
Debug.assert(sourceFiles.length === 1);
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(sourceFiles[0], host, sourceMapDir));
}
if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) {
// The relative paths are relative to the common directory
sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true);
}
else {
sourceMapData.jsSourceMappingURL = combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL);
}
}
else {
sourceMapDir = getDirectoryPath(normalizePath(filePath));
}
}
function reset() {
currentSourceFile = undefined;
sourceMapDir = undefined;
sourceMapSourceIndex = undefined;
lastRecordedSourceMapSpan = undefined;
lastEncodedSourceMapSpan = undefined;
lastEncodedNameIndex = undefined;
sourceMapData = undefined;
}
function updateLastEncodedAndRecordedSpans() {
if (modifyLastSourcePos) {
// Reset the source pos
modifyLastSourcePos = false;
// Change Last recorded Map with last encoded emit line and character
lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine;
lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn;
// Pop sourceMapDecodedMappings to remove last entry
sourceMapData.sourceMapDecodedMappings.pop();
// Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan
// If the list is empty which indicates that we are at the beginning of the file,
// we have to reset it to default value (same value when we first initialize sourceMapWriter)
lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ?
sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] :
defaultLastEncodedSourceMapSpan;
// TODO: Update lastEncodedNameIndex
// Since we dont support this any more, lets not worry about it right now.
// When we start supporting nameIndex, we will get back to this
// Change the encoded source map
const sourceMapMappings = sourceMapData.sourceMapMappings;
let lenthToSet = sourceMapMappings.length - 1;
for (; lenthToSet >= 0; lenthToSet--) {
const currentChar = sourceMapMappings.charAt(lenthToSet);
if (currentChar === ",") {
// Separator for the entry found
break;
}
if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") {
// Last line separator found
break;
}
}
sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet));
}
}
// Encoding for sourcemap span
function encodeLastRecordedSourceMapSpan() {
if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) {
return;
}
let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
// Line/Comma delimiters
if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
// Emit comma to separate the entry
if (sourceMapData.sourceMapMappings) {
sourceMapData.sourceMapMappings += ",";
}
}
else {
// Emit line delimiters
for (let encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) {
sourceMapData.sourceMapMappings += ";";
}
prevEncodedEmittedColumn = 1;
}
// 1. Relative Column 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn);
// 2. Relative sourceIndex
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex);
// 3. Relative sourceLine 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine);
// 4. Relative sourceColumn 0 based
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn);
// 5. Relative namePosition 0 based
if (lastRecordedSourceMapSpan.nameIndex >= 0) {
Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this");
sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex);
lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex;
}
lastEncodedSourceMapSpan = lastRecordedSourceMapSpan;
sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan);
}
function emitPos(pos: number) {
if (pos === -1) {
return;
}
const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
// Convert the location to be one-based.
sourceLinePos.line++;
sourceLinePos.character++;
const emittedLine = writer.getLine();
const emittedColumn = writer.getColumn();
// If this location wasn't recorded or the location in source is going backwards, record the span
if (!lastRecordedSourceMapSpan ||
lastRecordedSourceMapSpan.emittedLine !== emittedLine ||
lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||
(lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&
(lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||
(lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {
// Encode the last recordedSpan before assigning new
encodeLastRecordedSourceMapSpan();
// New span
lastRecordedSourceMapSpan = {
emittedLine: emittedLine,
emittedColumn: emittedColumn,
sourceLine: sourceLinePos.line,
sourceColumn: sourceLinePos.character,
sourceIndex: sourceMapSourceIndex
};
stopOverridingSpan = false;
}
else if (!stopOverridingSpan) {
// Take the new pos instead since there is no change in emittedLine and column since last location
lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line;
lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character;
lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex;
}
updateLastEncodedAndRecordedSpans();
}
function getStartPos(range: TextRange) {
const rangeHasDecorators = !!(range as Node).decorators;
return range.pos !== -1 ? skipTrivia(currentSourceFile.text, rangeHasDecorators ? (range as Node).decorators.end : range.pos) : -1;
}
function emitStart(range: TextRange) {
emitPos(getStartPos(range));
}
function emitEnd(range: TextRange, stopOverridingEnd?: boolean) {
emitPos(range.end);
stopOverridingSpan = stopOverridingEnd;
}
function changeEmitSourcePos() {
Debug.assert(!modifyLastSourcePos);
modifyLastSourcePos = true;
}
function setSourceFile(sourceFile: SourceFile) {
currentSourceFile = sourceFile;
// Add the file to tsFilePaths
// If sourceroot option: Use the relative path corresponding to the common directory path
// otherwise source locations relative to map file location
const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
const source = getRelativePathToDirectoryOrUrl(sourcesDirectoryPath,
currentSourceFile.fileName,
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true);
sourceMapSourceIndex = indexOf(sourceMapData.sourceMapSources, source);
if (sourceMapSourceIndex === -1) {
sourceMapSourceIndex = sourceMapData.sourceMapSources.length;
sourceMapData.sourceMapSources.push(source);
// The one that can be used from program to get the actual source file
sourceMapData.inputSourceFileNames.push(sourceFile.fileName);
if (compilerOptions.inlineSources) {
sourceMapData.sourceMapSourcesContent.push(sourceFile.text);
}
}
}
function getText() {
encodeLastRecordedSourceMapSpan();
return stringify({
version: 3,
file: sourceMapData.sourceMapFile,
sourceRoot: sourceMapData.sourceMapSourceRoot,
sources: sourceMapData.sourceMapSources,
names: sourceMapData.sourceMapNames,
mappings: sourceMapData.sourceMapMappings,
sourcesContent: sourceMapData.sourceMapSourcesContent,
});
}
function getSourceMappingURL() {
if (compilerOptions.inlineSourceMap) {
// Encode the sourceMap into the sourceMap url
const base64SourceMapText = convertToBase64(getText());
return sourceMapData.jsSourceMappingURL = `data:application/json;base64,${base64SourceMapText}`;
}
else {
return sourceMapData.jsSourceMappingURL;
}
}
}
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64FormatEncode(inValue: number) {
if (inValue < 64) {
return base64Chars.charAt(inValue);
}
throw TypeError(inValue + ": not a 64 based value");
}
function base64VLQFormatEncode(inValue: number) {
// Add a new least significant bit that has the sign of the value.
// if negative number the least significant bit that gets added to the number has value 1
// else least significant bit value that gets added is 0
// eg. -1 changes to binary : 01 [1] => 3
// +1 changes to binary : 01 [0] => 2
if (inValue < 0) {
inValue = ((-inValue) << 1) + 1;
}
else {
inValue = inValue << 1;
}
// Encode 5 bits at a time starting from least significant bits
let encodedStr = "";
do {
let currentDigit = inValue & 31; // 11111
inValue = inValue >> 5;
if (inValue > 0) {
// There are still more digits to decode, set the msb (6th bit)
currentDigit = currentDigit | 32;
}
encodedStr = encodedStr + base64FormatEncode(currentDigit);
} while (inValue > 0);
return encodedStr;
}
}
+207 -32
View File
@@ -1,6 +1,9 @@
/// <reference path="core.ts"/>
namespace ts {
export type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
export type DirectoryWatcherCallback = (directoryName: string) => void;
export interface System {
args: string[];
newLine: string;
@@ -8,8 +11,8 @@ namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: string, callback: (path: string, removed?: boolean) => void): FileWatcher;
watchDirectory?(path: string, callback: (path: string) => void, recursive?: boolean): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
@@ -23,14 +26,19 @@ namespace ts {
interface WatchedFile {
fileName: string;
callback: (fileName: string, removed?: boolean) => void;
mtime: Date;
callback: FileWatcherCallback;
mtime?: Date;
}
export interface FileWatcher {
close(): void;
}
export interface DirectoryWatcher extends FileWatcher {
directoryName: string;
referenceCount: number;
}
declare var require: any;
declare var module: any;
declare var process: any;
@@ -47,6 +55,25 @@ namespace ts {
constructor(o: any);
}
declare var ChakraHost: {
args: string[];
currentDirectory: string;
executingFile: string;
newLine?: string;
useCaseSensitiveFileNames?: boolean;
echo(s: string): void;
quit(exitCode?: number): void;
fileExists(path: string): boolean;
directoryExists(path: string): boolean;
createDirectory(path: string): void;
resolvePath(path: string): string;
readFile(path: string): string;
writeFile(path: string, contents: string): void;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
};
export var sys: System = (function () {
function getWScriptSystem(): System {
@@ -194,15 +221,15 @@ namespace ts {
}
};
}
function getNodeSystem(): System {
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
const _tty = require("tty");
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
function createWatchedFileSet(interval = 2500, chunkSize = 30) {
function createPollingWatchedFileSet(interval = 2500, chunkSize = 30) {
let watchedFiles: WatchedFile[] = [];
let nextFileToCheck = 0;
let watchTimer: any;
@@ -251,7 +278,7 @@ namespace ts {
}, interval);
}
function addFile(fileName: string, callback: (fileName: string, removed?: boolean) => void): WatchedFile {
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
const file: WatchedFile = {
fileName,
callback,
@@ -278,10 +305,92 @@ namespace ts {
};
}
function createWatchedFileSet() {
const dirWatchers: Map<DirectoryWatcher> = {};
// One file can have multiple watchers
const fileWatcherCallbacks: Map<FileWatcherCallback[]> = {};
return { addFile, removeFile };
function reduceDirWatcherRefCountForFile(fileName: string) {
const dirName = getDirectoryPath(fileName);
if (hasProperty(dirWatchers, dirName)) {
const watcher = dirWatchers[dirName];
watcher.referenceCount -= 1;
if (watcher.referenceCount <= 0) {
watcher.close();
delete dirWatchers[dirName];
}
}
}
function addDirWatcher(dirPath: string): void {
if (hasProperty(dirWatchers, dirPath)) {
const watcher = dirWatchers[dirPath];
watcher.referenceCount += 1;
return;
}
const watcher: DirectoryWatcher = _fs.watch(
dirPath,
{ persistent: true },
(eventName: string, relativeFileName: string) => fileEventHandler(eventName, relativeFileName, dirPath)
);
watcher.referenceCount = 1;
dirWatchers[dirPath] = watcher;
return;
}
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
if (hasProperty(fileWatcherCallbacks, filePath)) {
fileWatcherCallbacks[filePath].push(callback);
}
else {
fileWatcherCallbacks[filePath] = [callback];
}
}
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
addFileWatcherCallback(fileName, callback);
addDirWatcher(getDirectoryPath(fileName));
return { fileName, callback };
}
function removeFile(watchedFile: WatchedFile) {
removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback);
reduceDirWatcherRefCountForFile(watchedFile.fileName);
}
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
if (hasProperty(fileWatcherCallbacks, filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks[filePath]);
if (newCallbacks.length === 0) {
delete fileWatcherCallbacks[filePath];
}
else {
fileWatcherCallbacks[filePath] = newCallbacks;
}
}
}
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: string) {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
const fileName = typeof relativeFileName !== "string"
? undefined
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
// Some applications save a working file via rename operations
if ((eventName === "change" || eventName === "rename") && hasProperty(fileWatcherCallbacks, fileName)) {
for (const fileCallback of fileWatcherCallbacks[fileName]) {
fileCallback(fileName);
}
}
}
}
// REVIEW: for now this implementation uses polling.
// The advantage of polling is that it works reliably
// on all os and with network mounted files.
// For 90 referenced files, the average time to detect
// For 90 referenced files, the average time to detect
// changes is 2*msInterval (by default 5 seconds).
// The overhead of this is .04 percent (1/2500) with
// average pause of < 1 millisecond (and max
@@ -291,18 +400,19 @@ namespace ts {
// changes for large reference sets? If so, do we want
// to increase the chunk size or decrease the interval
// time dynamically to match the large reference set?
const pollingWatchedFileSet = createPollingWatchedFileSet();
const watchedFileSet = createWatchedFileSet();
function isNode4OrLater(): Boolean {
return parseInt(process.version.charAt(1)) >= 4;
}
function isNode4OrLater(): boolean {
return parseInt(process.version.charAt(1)) >= 4;
}
const platform: string = _os.platform();
// win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive
const useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
function readFile(fileName: string, encoding?: string): string {
if (!_fs.existsSync(fileName)) {
if (!fileExists(fileName)) {
return undefined;
}
const buffer = _fs.readFileSync(fileName);
@@ -350,7 +460,33 @@ namespace ts {
}
function getCanonicalPath(path: string): string {
return useCaseSensitiveFileNames ? path.toLowerCase() : path;
return useCaseSensitiveFileNames ? path : path.toLowerCase();
}
const enum FileSystemEntryKind {
File,
Directory
}
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {
try {
const stat = _fs.statSync(path);
switch (entryKind) {
case FileSystemEntryKind.File: return stat.isFile();
case FileSystemEntryKind.Directory: return stat.isDirectory();
}
}
catch (e) {
return false;
}
}
function fileExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.File);
}
function directoryExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.Directory);
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
@@ -362,6 +498,11 @@ namespace ts {
const files = _fs.readdirSync(path || ".").sort();
const directories: string[] = [];
for (const current of files) {
// This is necessary because on some file system node fails to exclude
// "." and "..". See https://github.com/nodejs/node/issues/4002
if (current === "." || current === "..") {
continue;
}
const name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
const stat = _fs.statSync(name);
@@ -391,33 +532,37 @@ namespace ts {
readFile,
writeFile,
watchFile: (fileName, callback) => {
// Node 4.0 stablized the `fs.watch` function on Windows which avoids polling
// Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling
// and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
if (isNode4OrLater()) {
// Note: in node the callback of fs.watch is given only the relative file name as a parameter
return _fs.watch(fileName, (eventName: string, relativeFileName: string) => callback(fileName));
}
const watchedFile = watchedFileSet.addFile(fileName, callback);
const watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet;
const watchedFile = watchSet.addFile(fileName, callback);
return {
close: () => watchedFileSet.removeFile(watchedFile)
close: () => watchSet.removeFile(watchedFile)
};
},
watchDirectory: (path, callback, recursive) => {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
watchDirectory: (directoryName, callback, recursive) => {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) {
options = { persistent: true, recursive: !!recursive };
}
else {
options = { persistent: true };
}
return _fs.watch(
path,
{ persistent: true, recursive: !!recursive },
directoryName,
options,
(eventName: string, relativeFileName: string) => {
// In watchDirectory we only care about adding and removing files (when event name is
// "rename"); changes made within files are handled by corresponding fileWatchers (when
// event name is "change")
if (eventName === "rename") {
// When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? relativeFileName : normalizePath(ts.combinePaths(path, relativeFileName)));
callback(!relativeFileName ? relativeFileName : normalizePath(combinePaths(directoryName, relativeFileName)));
};
}
);
@@ -425,12 +570,8 @@ namespace ts {
resolvePath: function (path: string): string {
return _path.resolve(path);
},
fileExists(path: string): boolean {
return _fs.existsSync(path);
},
directoryExists(path: string) {
return _fs.existsSync(path) && _fs.statSync(path).isDirectory();
},
fileExists,
directoryExists,
createDirectory(directoryName: string) {
if (!this.directoryExists(directoryName)) {
_fs.mkdirSync(directoryName);
@@ -454,6 +595,37 @@ namespace ts {
}
};
}
function getChakraSystem(): System {
return {
newLine: ChakraHost.newLine || "\r\n",
args: ChakraHost.args,
useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames,
write: ChakraHost.echo,
readFile(path: string, encoding?: string) {
// encoding is automatically handled by the implementation in ChakraHost
return ChakraHost.readFile(path);
},
writeFile(path: string, data: string, writeByteOrderMark?: boolean) {
// If a BOM is required, emit one
if (writeByteOrderMark) {
data = "\uFEFF" + data;
}
ChakraHost.writeFile(path, data);
},
resolvePath: ChakraHost.resolvePath,
fileExists: ChakraHost.fileExists,
directoryExists: ChakraHost.directoryExists,
createDirectory: ChakraHost.createDirectory,
getExecutingFilePath: () => ChakraHost.executingFile,
getCurrentDirectory: () => ChakraHost.currentDirectory,
readDirectory: ChakraHost.readDirectory,
exit: ChakraHost.quit,
};
}
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
@@ -462,6 +634,9 @@ namespace ts {
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
else if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else {
return undefined; // Unsupported host
}
+71 -37
View File
@@ -115,7 +115,7 @@ namespace ts {
const gutterStyleSequence = "\u001b[100;30m";
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const elipsis = "...";
const ellipsis = "...";
const categoryFormatMap: Map<string> = {
[DiagnosticCategory.Warning]: yellowForegroundEscapeSequence,
[DiagnosticCategory.Error]: redForegroundEscapeSequence,
@@ -139,7 +139,7 @@ namespace ts {
const hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
let gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(elipsis.length, gutterWidth);
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
output += sys.newLine;
@@ -147,7 +147,7 @@ namespace ts {
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
output += formatAndReset(padLeft(elipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine;
output += formatAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine;
i = lastLine - 1;
}
@@ -240,6 +240,11 @@ namespace ts {
return typeof JSON === "object" && typeof JSON.parse === "function";
}
function isWatchSet(options: CompilerOptions) {
// Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}
export function executeCommandLine(args: string[]): void {
const commandLine = parseCommandLine(args);
let configFileName: string; // Configuration file name (if any)
@@ -280,7 +285,7 @@ namespace ts {
}
if (commandLine.options.version) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Version_0, ts.version), /* compilerHost */ undefined);
printVersion();
return sys.exit(ExitStatus.Success);
}
@@ -295,15 +300,30 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
configFileName = normalizePath(combinePaths(commandLine.options.project, "tsconfig.json"));
if (commandLine.fileNames.length !== 0) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
const fileOrDirectory = normalizePath(commandLine.options.project);
if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) {
configFileName = combinePaths(fileOrDirectory, "tsconfig.json");
if (!sys.fileExists(configFileName)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
}
else {
configFileName = fileOrDirectory;
if (!sys.fileExists(configFileName)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
}
}
else if (commandLine.fileNames.length === 0 && isJSONSupported()) {
const searchPath = normalizePath(sys.getCurrentDirectory());
configFileName = findConfigFile(searchPath);
configFileName = findConfigFile(searchPath, sys.fileExists);
}
if (commandLine.fileNames.length === 0 && !configFileName) {
@@ -312,20 +332,20 @@ namespace ts {
return sys.exit(ExitStatus.Success);
}
// Firefox has Object.prototype.watch
if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) {
if (isWatchSet(commandLine.options)) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (configFileName) {
configFileWatcher = sys.watchFile(configFileName, configFileChanged);
const configFilePath = toPath(configFileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
configFileWatcher = sys.watchFile(configFilePath, configFileChanged);
}
if (sys.watchDirectory && configFileName) {
const directory = ts.getDirectoryPath(configFileName);
directoryWatcher = sys.watchDirectory(
// When the configFileName is just "tsconfig.json", the watched directory should be
// the current direcotry; if there is a given "project" parameter, then the configFileName
// When the configFileName is just "tsconfig.json", the watched directory should be
// the current directory; if there is a given "project" parameter, then the configFileName
// is an absolute file name.
directory == "" ? "." : directory,
watchedDirectoryChanged, /*recursive*/ true);
@@ -346,15 +366,30 @@ namespace ts {
return;
}
}
if (!cachedConfigFileText) {
const error = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName);
reportDiagnostics([error], /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
const result = parseConfigFileTextToJson(configFileName, cachedConfigFileText);
const configObject = result.config;
const configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName));
if (!configObject) {
reportDiagnostics([result.error], /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
const configParseResult = parseJsonConfigFileContent(configObject, sys, getNormalizedAbsolutePath(getDirectoryPath(configFileName), sys.getCurrentDirectory()), commandLine.options, configFileName);
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
if (isWatchSet(configParseResult.options) && !sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
return configParseResult;
}
@@ -365,7 +400,7 @@ namespace ts {
if (configFileName) {
const configParseResult = parseConfigFile();
rootFileNames = configParseResult.fileNames;
compilerOptions = extend(commandLine.options, configParseResult.options);
compilerOptions = configParseResult.options;
}
else {
rootFileNames = commandLine.fileNames;
@@ -388,7 +423,7 @@ namespace ts {
const compileResult = compile(rootFileNames, compilerOptions, compilerHost);
if (!compilerOptions.watch) {
if (!isWatchSet(compilerOptions)) {
return sys.exit(compileResult.exitStatus);
}
@@ -414,9 +449,10 @@ namespace ts {
}
// Use default host function
const sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
if (sourceFile && compilerOptions.watch) {
if (sourceFile && isWatchSet(compilerOptions) && sys.watchFile) {
// Attach a file watcher
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
const filePath = toPath(sourceFile.fileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
sourceFile.fileWatcher = sys.watchFile(filePath, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
}
return sourceFile;
}
@@ -458,7 +494,7 @@ namespace ts {
}
function watchedDirectoryChanged(fileName: string) {
if (fileName && !ts.isSupportedSourceFileName(fileName)) {
if (fileName && !ts.isSupportedSourceFileName(fileName, compilerOptions)) {
return;
}
@@ -562,30 +598,21 @@ namespace ts {
}
}
reportDiagnostics(diagnostics, compilerHost);
// If the user doesn't want us to emit, then we're done at this point.
if (compilerOptions.noEmit) {
return diagnostics.length
? ExitStatus.DiagnosticsPresent_OutputsSkipped
: ExitStatus.Success;
}
// Otherwise, emit and report any errors we ran into.
const emitOutput = program.emit();
reportDiagnostics(emitOutput.diagnostics, compilerHost);
diagnostics = diagnostics.concat(emitOutput.diagnostics);
// If the emitter didn't emit anything, then pass that value along.
if (emitOutput.emitSkipped) {
reportDiagnostics(sortAndDeduplicateDiagnostics(diagnostics), compilerHost);
if (emitOutput.emitSkipped && diagnostics.length > 0) {
// If the emitter didn't emit anything, then pass that value along.
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
// The emitter emitted something, inform the caller if that happened in the presence
// of diagnostics or not.
if (diagnostics.length > 0 || emitOutput.diagnostics.length > 0) {
else if (diagnostics.length > 0) {
// The emitter emitted something, inform the caller if that happened in the presence
// of diagnostics or not.
return ExitStatus.DiagnosticsPresent_OutputsGenerated;
}
return ExitStatus.Success;
}
}
@@ -691,14 +718,19 @@ namespace ts {
else {
const compilerOptions = extend(options, defaultInitCompilerOptions);
const configurations: any = {
compilerOptions: serializeCompilerOptions(compilerOptions),
exclude: ["node_modules"]
compilerOptions: serializeCompilerOptions(compilerOptions)
};
if (fileNames && fileNames.length) {
// only set the files property if we have at least one file
configurations.files = fileNames;
}
else {
configurations.exclude = ["node_modules"];
if (compilerOptions.outDir) {
configurations.exclude.push(compilerOptions.outDir);
}
}
sys.writeFile(file, JSON.stringify(configurations, undefined, 4));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* compilerHost */ undefined);
@@ -712,7 +744,9 @@ namespace ts {
for (const name in options) {
if (hasProperty(options, name)) {
const value = options[name];
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
const value = <string | number | boolean>options[name];
switch (name) {
case "init":
case "watch":
+1 -2
View File
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
@@ -8,9 +7,9 @@
"sourceMap": true
},
"files": [
"types.ts",
"core.ts",
"sys.ts",
"types.ts",
"diagnosticInformationMap.generated.ts",
"scanner.ts",
"parser.ts",
+584 -190
View File
File diff suppressed because it is too large Load Diff
+599 -232
View File
File diff suppressed because it is too large Load Diff
+58 -48
View File
@@ -40,89 +40,92 @@ class CompilerBaselineRunner extends RunnerBase {
this.basePath += "/" + this.testSuiteName;
}
private makeUnitName(name: string, root: string) {
return ts.isRootedDiskPath(name) ? name : ts.combinePaths(root, name);
};
public checkTestCodeOutput(fileName: string) {
describe("compiler tests for " + fileName, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let justName: string;
let content: string;
let testCaseContent: { settings: Harness.TestCaseParser.CompilerSettings; testUnitData: Harness.TestCaseParser.TestUnitData[]; };
let units: Harness.TestCaseParser.TestUnitData[];
let tcSettings: Harness.TestCaseParser.CompilerSettings;
let lastUnit: Harness.TestCaseParser.TestUnitData;
let rootDir: string;
let harnessSettings: Harness.TestCaseParser.CompilerSettings;
let hasNonDtsFiles: boolean;
let result: Harness.Compiler.CompilerResult;
let program: ts.Program;
let options: ts.CompilerOptions;
// equivalent to the files that will be passed on the command line
let toBeCompiled: { unitName: string; content: string }[];
let toBeCompiled: Harness.Compiler.TestFile[];
// equivalent to other files on the file system not directly passed to the compiler (ie things that are referenced by other files)
let otherFiles: { unitName: string; content: string }[];
let harnessCompiler: Harness.Compiler.HarnessCompiler;
let otherFiles: Harness.Compiler.TestFile[];
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ""); // strips the fileName from the path.
content = Harness.IO.readFile(fileName);
testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
units = testCaseContent.testUnitData;
tcSettings = testCaseContent.settings;
const content = Harness.IO.readFile(fileName);
const rootDir = fileName.indexOf("conformance") === -1 ? "tests/cases/compiler/" : ts.getDirectoryPath(fileName) + "/";
const testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName, rootDir);
const units = testCaseContent.testUnitData;
harnessSettings = testCaseContent.settings;
let tsConfigOptions: ts.CompilerOptions;
if (testCaseContent.tsConfig) {
assert.equal(testCaseContent.tsConfig.fileNames.length, 0, `list of files in tsconfig is not currently supported`);
tsConfigOptions = ts.clone(testCaseContent.tsConfig.options);
}
else {
const baseUrl = harnessSettings["baseUrl"];
if (baseUrl !== undefined && !ts.isRootedDiskPath(baseUrl)) {
harnessSettings["baseUrl"] = ts.getNormalizedAbsolutePath(baseUrl, rootDir);
}
}
lastUnit = units[units.length - 1];
rootDir = lastUnit.originalFilePath.indexOf("conformance") === -1 ? "tests/cases/compiler/" : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf("/")) + "/";
harnessCompiler = Harness.Compiler.getCompiler();
hasNonDtsFiles = ts.forEach(units, unit => !ts.fileExtensionIs(unit.name, ".d.ts"));
// We need to assemble the list of input files for the compiler and other related files on the 'filesystem' (ie in a multi-file test)
// If the last file in a test uses require or a triple slash reference we'll assume all other files will be brought in via references,
// otherwise, assume all files are just meant to be in the same compilation session without explicit references to one another.
toBeCompiled = [];
otherFiles = [];
if (/require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
toBeCompiled.push({ unitName: rootDir + lastUnit.name, content: lastUnit.content });
if (testCaseContent.settings["noImplicitReferences"] || /require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content });
units.forEach(unit => {
if (unit.name !== lastUnit.name) {
otherFiles.push({ unitName: rootDir + unit.name, content: unit.content });
otherFiles.push({ unitName: this.makeUnitName(unit.name, rootDir), content: unit.content });
}
});
}
else {
toBeCompiled = units.map(unit => {
return { unitName: rootDir + unit.name, content: unit.content };
return { unitName: this.makeUnitName(unit.name, rootDir), content: unit.content };
});
}
options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _program) {
result = compileResult;
// The program will be used by typeWriter
program = _program;
}, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
});
const output = Harness.Compiler.compileFiles(
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ undefined);
options = output.options;
result = output.result;
});
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
justName = undefined;
content = undefined;
testCaseContent = undefined;
units = undefined;
tcSettings = undefined;
lastUnit = undefined;
rootDir = undefined;
hasNonDtsFiles = undefined;
result = undefined;
program = undefined;
options = undefined;
toBeCompiled = undefined;
otherFiles = undefined;
harnessCompiler = undefined;
});
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : "";
}
function getErrorBaseline(toBeCompiled: { unitName: string; content: string }[], otherFiles: { unitName: string; content: string }[], result: Harness.Compiler.CompilerResult) {
function getErrorBaseline(toBeCompiled: Harness.Compiler.TestFile[], otherFiles: Harness.Compiler.TestFile[], result: Harness.Compiler.CompilerResult) {
return Harness.Compiler.getErrorBaseline(toBeCompiled.concat(otherFiles), result.errors);
}
@@ -136,6 +139,14 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it (`Correct module resolution tracing for ${fileName}`, () => {
if (options.traceModuleResolution) {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".trace.json"), () => {
return JSON.stringify(result.traceResults || [], undefined, 4);
});
}
});
// Source maps?
it("Correct sourcemap content for " + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
@@ -151,8 +162,8 @@ class CompilerBaselineRunner extends RunnerBase {
});
it("Correct JS output for " + fileName, () => {
if (!ts.fileExtensionIs(lastUnit.name, ".d.ts") && this.emit) {
if (result.files.length === 0 && result.errors.length === 0) {
if (hasNonDtsFiles && this.emit) {
if (!options.noEmit && result.files.length === 0 && result.errors.length === 0) {
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
}
@@ -184,9 +195,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
}
const declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
}, options);
const declFileCompilationResult =
Harness.Compiler.compileDeclarationFiles(
toBeCompiled, otherFiles, result, harnessSettings, options, /*currentDirectory*/ undefined);
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
@@ -251,16 +262,16 @@ class CompilerBaselineRunner extends RunnerBase {
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type outputed as: number | string
// But with a pull type check, we may see it as: string | number
// For example, with a full type check, we may see a type displayed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ true);
const pullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ false);
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
@@ -274,14 +285,14 @@ class CompilerBaselineRunner extends RunnerBase {
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine:*/ false);
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine:*/ true);
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
@@ -367,7 +378,6 @@ class CompilerBaselineRunner extends RunnerBase {
public initializeTests() {
describe(this.testSuiteName + " tests", () => {
describe("Setup compiler for compiler baselines", () => {
const harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
});
+2 -2
View File
@@ -1073,7 +1073,7 @@ declare module "crypto" {
update(data: any): void;
sign(private_key: string, output_format: string): string;
}
export function createVerify(algorith: string): Verify;
export function createVerify(algorithm: string): Verify;
interface Verify {
update(data: any): void;
verify(object: string, signature: string, signature_format?: string): boolean;
@@ -1237,7 +1237,7 @@ declare module "assert" {
export function equal(actual: any, expected: any, message?: string): void;
export function notEqual(actual: any, expected: any, message?: string): void;
export function deepEqual(actual: any, expected: any, message?: string): void;
export function notDeepEqual(acutal: any, expected: any, message?: string): void;
export function notDeepEqual(actual: any, expected: any, message?: string): void;
export function strictEqual(actual: any, expected: any, message?: string): void;
export function notStrictEqual(actual: any, expected: any, message?: string): void;
export var throws: {
+819 -311
View File
File diff suppressed because it is too large Load Diff
-50
View File
@@ -58,56 +58,6 @@ class FourSlashRunner extends RunnerBase {
}
});
});
describe("Generate Tao XML", () => {
const invalidReasons: any = {};
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1;
}
});
const invalidReport: { reason: string; count: number }[] = [];
for (const reason in invalidReasons) {
if (invalidReasons.hasOwnProperty(reason)) {
invalidReport.push({ reason: reason, count: invalidReasons[reason] });
}
}
invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
const lines: string[] = [];
lines.push("<!-- Blocked Test Report");
invalidReport.forEach((reasonAndCount) => {
lines.push(reasonAndCount.count + " tests blocked by " + reasonAndCount.reason);
});
lines.push("-->");
lines.push("<TaoTest xmlns=\"http://microsoft.com/schemas/VSLanguages/TAO\">");
lines.push(" <InitTest>");
lines.push(" <StartTarget />");
lines.push(" </InitTest>");
lines.push(" <ScenarioList>");
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
lines.push("<!-- Skipped " + xml.originalName + ", reason: " + xml.invalidReason + " -->");
}
else {
lines.push(" <Scenario Name=\"" + xml.originalName + "\">");
xml.actions.forEach(action => {
lines.push(" " + action);
});
lines.push(" </Scenario>");
}
});
lines.push(" </ScenarioList>");
lines.push(" <CleanupScenario>");
lines.push(" <CloseAllDocuments />");
lines.push(" <CleanupCreatedFiles />");
lines.push(" </CleanupScenario>");
lines.push(" <CleanupTest>");
lines.push(" <CloseTarget />");
lines.push(" </CleanupTest>");
lines.push("</TaoTest>");
Harness.IO.writeFile("built/local/fourslash.xml", lines.join("\r\n"));
});
});
}
}
+197 -298
View File
@@ -31,7 +31,6 @@
// this will work in the browser via browserify
var _chai: typeof chai = require("chai");
var assert: typeof _chai.assert = _chai.assert;
var expect: typeof _chai.expect = _chai.expect;
declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(null);
/* tslint:enable:no-var-keyword */
@@ -176,7 +175,9 @@ namespace Utils {
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
for (const childName in node) {
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator") {
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" ||
// for now ignore jsdoc comments
childName === "jsDocComment") {
continue;
}
const child = (<any>node)[childName];
@@ -244,7 +245,6 @@ namespace Utils {
}
function getNodeFlagName(f: number) { return getFlagName((<any>ts).NodeFlags, f); }
function getParserContextFlagName(f: number) { return getFlagName((<any>ts).ParserContextFlags, f); }
function serializeNode(n: ts.Node): any {
const o: any = { kind: getKindName(n.kind) };
@@ -273,19 +273,12 @@ namespace Utils {
break;
case "flags":
// Print out flags with their enum names.
if (n.flags) {
o[propertyName] = getNodeFlagName(n.flags);
}
break;
case "parserContextFlags":
// Clear the flag that are produced by aggregating child values.. That is ephemeral
// data we don't care about in the dump. We only care what the parser set directly
// on the ast.
let value = n.parserContextFlags & ts.ParserContextFlags.ParserGeneratedFlags;
if (value) {
o[propertyName] = getParserContextFlagName(value);
// Clear the flags that are produced by aggregating child values. That is ephemeral
// data we don't care about in the dump. We only care what the parser set directly
// on the AST.
const flags = n.flags & ~(ts.NodeFlags.JavaScriptFile | ts.NodeFlags.HasAggregatedChildData);
if (flags) {
o[propertyName] = getNodeFlagName(flags);
}
break;
@@ -352,12 +345,11 @@ namespace Utils {
assert.equal(node1.pos, node2.pos, "node1.pos !== node2.pos");
assert.equal(node1.end, node2.end, "node1.end !== node2.end");
assert.equal(node1.kind, node2.kind, "node1.kind !== node2.kind");
assert.equal(node1.flags, node2.flags, "node1.flags !== node2.flags");
// call this on both nodes to ensure all propagated flags have been set (and thus can be
// compared).
assert.equal(ts.containsParseError(node1), ts.containsParseError(node2));
assert.equal(node1.parserContextFlags, node2.parserContextFlags, "node1.parserContextFlags !== node2.parserContextFlags");
assert.equal(node1.flags, node2.flags, "node1.flags !== node2.flags");
ts.forEachChild(node1,
child1 => {
@@ -511,7 +503,6 @@ namespace Harness {
}
const folder: any = fso.GetFolder(path);
const paths: string[] = [];
return filesInFolder(folder, path);
};
@@ -615,7 +606,6 @@ namespace Harness {
export const getExecutingFilePath = () => "";
export const exit = (exitCode: number) => {};
const supportsCodePage = () => false;
export let log = (s: string) => console.log(s);
namespace Http {
@@ -625,18 +615,6 @@ namespace Harness {
}
/// Ask the server to use node's path.resolve to resolve the given path
function getResolvedPathFromServer(path: string) {
const xhr = new XMLHttpRequest();
try {
xhr.open("GET", path + "?resolve", false);
xhr.send();
}
catch (e) {
return { status: 404, responseText: null };
}
return waitForXHR(xhr);
}
export interface XHRResponse {
status: number;
@@ -647,7 +625,7 @@ namespace Harness {
export function getFileFromServerSync(url: string): XHRResponse {
const xhr = new XMLHttpRequest();
try {
xhr.open("GET", url, false);
xhr.open("GET", url, /*async*/ false);
xhr.send();
}
catch (e) {
@@ -662,7 +640,7 @@ namespace Harness {
const xhr = new XMLHttpRequest();
try {
const actionMsg = "?action=" + action;
xhr.open("POST", url + actionMsg, false);
xhr.open("POST", url + actionMsg, /*async*/ false);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send(contents);
}
@@ -767,26 +745,9 @@ namespace Harness {
}
namespace Harness {
let tcServicesFileName = "typescriptServices.js";
export let libFolder: string;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
libFolder = "built/local/";
tcServicesFileName = "built/local/typescriptServices.js";
break;
case Utils.ExecutionEnvironment.Node:
libFolder = "built/local/";
tcServicesFileName = "built/local/typescriptServices.js";
break;
case Utils.ExecutionEnvironment.Browser:
libFolder = "built/local/";
tcServicesFileName = "built/local/typescriptServices.js";
break;
default:
throw new Error("Unknown context");
}
export let tcServicesFile = IO.readFile(tcServicesFileName);
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 interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
@@ -827,57 +788,14 @@ namespace Harness {
}
}
export interface IEmitterIOHost {
writeFile(path: string, contents: string, writeByteOrderMark: boolean): void;
resolvePath(path: string): string;
}
/** Mimics having multiple files, later concatenated to a single file. */
export class EmitterIOHost implements IEmitterIOHost {
private fileCollection: any = {};
/** create file gets the whole path to create, so this works as expected with the --out parameter */
public writeFile(s: string, contents: string, writeByteOrderMark: boolean): void {
let writer: ITextWriter;
if (this.fileCollection[s]) {
writer = <ITextWriter>this.fileCollection[s];
}
else {
writer = new Harness.Compiler.WriterAggregator();
this.fileCollection[s] = writer;
}
writer.Write(contents);
writer.Close();
}
public resolvePath(s: string) { return s; }
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[] {
const result: { fileName: string; file: WriterAggregator; }[] = [];
for (const p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
const current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
if (current.lines.length > 0) {
if (p.indexOf(".d.ts") !== -1) { current.lines.unshift(["////[", Path.getFileName(p), "]"].join("")); }
result.push({ fileName: p, file: this.fileCollection[p] });
}
}
}
return result;
}
}
export function createSourceFileAndAssertInvariants(
fileName: string,
sourceText: string,
languageVersion: ts.ScriptTarget) {
// We'll only assert inletiants outside of light mode.
// We'll only assert invariants outside of light mode.
const shouldAssertInvariants = !Harness.lightMode;
// Only set the parent nodes if we're asserting inletiants. We don't need them otherwise.
// Only set the parent nodes if we're asserting invariants. We don't need them otherwise.
const result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
if (shouldAssertInvariants) {
@@ -890,12 +808,12 @@ namespace Harness {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export let defaultLibFileName = "lib.d.ts";
export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const defaultLibFileName = "lib.d.ts";
export const defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
// Cache these between executions so we don't have to re-parse them for every test
export let fourslashFileName = "fourslash.ts";
export const fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
@@ -903,41 +821,32 @@ namespace Harness {
}
export function createCompilerHost(
inputFiles: { unitName: string; content: string; }[],
inputFiles: TestFile[],
writeFile: (fn: string, contents: string, writeByteOrderMark: boolean) => void,
scriptTarget: ts.ScriptTarget,
useCaseSensitiveFileNames: boolean,
// the currentDirectory is needed for rwcRunner to passed in specified current directory to compiler host
currentDirectory?: string,
currentDirectory: string,
newLineKind?: ts.NewLineKind): ts.CompilerHost {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
function getCanonicalFileName(fileName: string): string {
return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
const getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
const filemap: { [fileName: string]: ts.SourceFile; } = {};
const getCurrentDirectory = currentDirectory === undefined ? Harness.IO.getCurrentDirectory : () => currentDirectory;
// Register input files
function register(file: { unitName: string; content: string; }) {
const fileMap: ts.FileMap<ts.SourceFile> = ts.createFileMap<ts.SourceFile>();
for (const file of inputFiles) {
if (file.content !== undefined) {
const fileName = ts.normalizePath(file.unitName);
const sourceFile = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget);
filemap[getCanonicalFileName(fileName)] = sourceFile;
filemap[getCanonicalFileName(ts.getNormalizedAbsolutePath(fileName, getCurrentDirectory()))] = sourceFile;
const path = ts.toPath(file.unitName, currentDirectory, getCanonicalFileName);
fileMap.set(path, sourceFile);
}
};
inputFiles.forEach(register);
}
function getSourceFile(fn: string, languageVersion: ts.ScriptTarget) {
fn = ts.normalizePath(fn);
if (Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(fn))) {
return filemap[getCanonicalFileName(fn)];
}
else if (currentDirectory) {
const canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
const path = ts.toPath(fn, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
return fileMap.get(path);
}
else if (fn === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
@@ -959,7 +868,7 @@ namespace Harness {
Harness.IO.newLine();
return {
getCurrentDirectory,
getCurrentDirectory: () => currentDirectory,
getSourceFile,
getDefaultLibFileName: options => defaultLibFileName,
writeFile,
@@ -967,7 +876,7 @@ namespace Harness {
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => newLine,
fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
readFile: (fileName: string): string => { throw new Error("NotYetImplemented"); }
readFile: (fileName: string): string => { return Harness.IO.readFile(fileName); }
};
}
@@ -975,6 +884,7 @@ namespace Harness {
useCaseSensitiveFileNames?: boolean;
includeBuiltFile?: string;
baselineFile?: string;
libFiles?: string;
}
// Additional options not already in ts.optionDeclarations
@@ -984,7 +894,10 @@ namespace Harness {
{ name: "baselineFile", type: "string" },
{ name: "includeBuiltFile", type: "string" },
{ name: "fileName", type: "string" },
{ name: "noErrorTruncation", type: "boolean" }
{ name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" },
{ name: "suppressOutputPathCheck", type: "boolean" },
{ name: "noImplicitReferences", type: "boolean" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
@@ -1034,177 +947,152 @@ namespace Harness {
}
}
export class HarnessCompiler {
private inputFiles: { unitName: string; content: string }[] = [];
private compileOptions: ts.CompilerOptions;
private settings: Harness.TestCaseParser.CompilerSettings = {};
export interface TestFile {
unitName: string;
content: string;
}
private lastErrors: ts.Diagnostic[];
export interface CompilationOutput {
result: CompilerResult;
options: ts.CompilerOptions & HarnessOptions;
}
public reset() {
this.inputFiles = [];
this.settings = {};
this.lastErrors = [];
export function compileFiles(
inputFiles: TestFile[],
otherFiles: TestFile[],
harnessSettings: TestCaseParser.CompilerSettings,
compilerOptions: ts.CompilerOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory: string): CompilationOutput {
const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.clone(compilerOptions) : { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
options.noErrorTruncation = true;
options.skipDefaultLibCheck = true;
currentDirectory = currentDirectory || Harness.IO.getCurrentDirectory();
// Parse settings
if (harnessSettings) {
setCompilerOptionsFromHarnessSetting(harnessSettings, options);
}
if (options.rootDirs) {
options.rootDirs = ts.map(options.rootDirs, d => ts.getNormalizedAbsolutePath(d, currentDirectory));
}
public reportCompilationErrors() {
return this.lastErrors;
const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
const programFiles: TestFile[] = inputFiles.slice();
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
// Treat them as library files, so include them in build, but not in baselines.
if (options.includeBuiltFile) {
const builtFileName = ts.combinePaths(libFolder, options.includeBuiltFile);
const builtFile: TestFile = {
unitName: builtFileName,
content: normalizeLineEndings(IO.readFile(builtFileName), Harness.IO.newLine()),
};
programFiles.push(builtFile);
}
public setCompilerSettings(tcSettings: Harness.TestCaseParser.CompilerSettings) {
this.settings = tcSettings;
}
const fileOutputs: GeneratedFile[] = [];
public addInputFiles(files: { unitName: string; content: string }[]) {
files.forEach(file => this.addInputFile(file));
}
public addInputFile(file: { unitName: string; content: string }) {
this.inputFiles.push(file);
}
public setCompilerOptions(options?: ts.CompilerOptions) {
this.compileOptions = options || { noResolve: false };
}
public emitAll(ioHost?: IEmitterIOHost) {
this.compileFiles(this.inputFiles,
/*otherFiles*/ [],
/*onComplete*/ result => {
result.files.forEach(writeFile);
result.declFilesCode.forEach(writeFile);
result.sourceMaps.forEach(writeFile);
},
/*settingsCallback*/ () => { },
this.compileOptions);
function writeFile(file: GeneratedFile) {
ioHost.writeFile(file.fileName, file.code, false);
// Files from tests\lib that are requested by "@libFiles"
if (options.libFiles) {
for (const fileName of options.libFiles.split(",")) {
const libFileName = "tests/lib/" + fileName;
programFiles.push({ unitName: libFileName, content: normalizeLineEndings(IO.readFile(libFileName), Harness.IO.newLine()) });
}
}
public compileFiles(inputFiles: { unitName: string; content: string }[],
otherFiles: { unitName: string; content: string }[],
onComplete: (result: CompilerResult, program: ts.Program) => void,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions & HarnessOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory?: string) {
options = options || { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.module = options.module || ts.ModuleKind.None;
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
options.noErrorTruncation = true;
options.skipDefaultLibCheck = true;
const programFileNames = programFiles.map(file => file.unitName);
if (settingsCallback) {
settingsCallback(null);
}
const compilerHost = createCompilerHost(
programFiles.concat(otherFiles),
(fileName, code, writeByteOrderMark) => fileOutputs.push({ fileName, code, writeByteOrderMark }),
options.target,
useCaseSensitiveFileNames,
currentDirectory,
options.newLine);
const newLine = "\r\n";
let traceResults: string[];
if (options.traceModuleResolution) {
traceResults = [];
compilerHost.trace = text => traceResults.push(text);
}
const program = ts.createProgram(programFileNames, options, compilerHost);
// Parse settings
setCompilerOptionsFromHarnessSetting(this.settings, options);
const emitResult = program.emit();
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
// Treat them as library files, so include them in build, but not in baselines.
const includeBuiltFiles: { unitName: string; content: string }[] = [];
if (options.includeBuiltFile) {
const builtFileName = libFolder + options.includeBuiltFile;
includeBuiltFiles.push({ unitName: builtFileName, content: normalizeLineEndings(IO.readFile(builtFileName), newLine) });
}
const errors = ts.getPreEmitDiagnostics(program);
const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames();
const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps, traceResults);
return { result, options };
}
const fileOutputs: GeneratedFile[] = [];
const programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
const compilerHost = createCompilerHost(
inputFiles.concat(includeBuiltFiles).concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine);
const program = ts.createProgram(programFiles, options, compilerHost);
const emitResult = program.emit();
const errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
this.lastErrors = errors;
const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps);
onComplete(result, program);
return options;
export function compileDeclarationFiles(inputFiles: TestFile[],
otherFiles: TestFile[],
result: CompilerResult,
harnessSettings: TestCaseParser.CompilerSettings & HarnessOptions,
options: ts.CompilerOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory: string) {
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
throw new Error("There were no errors and declFiles generated did not match number of js files generated");
}
public compileDeclarationFiles(inputFiles: { unitName: string; content: string; }[],
otherFiles: { unitName: string; content: string; }[],
result: CompilerResult,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory?: string) {
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length !== result.files.length) {
throw new Error("There were no errors and declFiles generated did not match number of js files generated");
const declInputFiles: TestFile[] = [];
const declOtherFiles: TestFile[] = [];
// if the .d.ts is non-empty, confirm it compiles correctly as well
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
const output = compileFiles(declInputFiles, declOtherFiles, harnessSettings, options, currentDirectory);
return { declInputFiles, declOtherFiles, declResult: output.result };
}
function addDtsFile(file: TestFile, dtsFiles: TestFile[]) {
if (isDTS(file.unitName)) {
dtsFiles.push(file);
}
const declInputFiles: { unitName: string; content: string }[] = [];
const declOtherFiles: { unitName: string; content: string }[] = [];
let declResult: Harness.Compiler.CompilerResult;
// if the .d.ts is non-empty, confirm it compiles correctly as well
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
this.compileFiles(declInputFiles, declOtherFiles, function (compileResult) { declResult = compileResult; },
settingsCallback, options, currentDirectory);
return { declInputFiles, declOtherFiles, declResult };
}
function addDtsFile(file: { unitName: string; content: string }, dtsFiles: { unitName: string; content: string }[]) {
if (isDTS(file.unitName)) {
dtsFiles.push(file);
}
else if (isTS(file.unitName)) {
const declFile = findResultCodeFile(file.unitName);
if (!findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
}
}
function findResultCodeFile(fileName: string) {
const sourceFile = result.program.getSourceFile(fileName);
assert(sourceFile, "Program has no source file with name '" + fileName + "'");
// Is this file going to be emitted separately
let sourceFileName: string;
const outFile = options.outFile || options.out;
if (ts.isExternalModule(sourceFile) || !outFile) {
if (options.outDir) {
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
else {
sourceFileName = sourceFile.fileName;
}
}
else {
// Goes to single --out file
sourceFileName = outFile;
}
const dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
function findUnit(fileName: string, units: { unitName: string; content: string; }[]) {
return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
else if (isTS(file.unitName)) {
const declFile = findResultCodeFile(file.unitName);
if (declFile && !findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
}
}
}
function findResultCodeFile(fileName: string) {
const sourceFile = result.program.getSourceFile(fileName);
assert(sourceFile, "Program has no source file with name '" + fileName + "'");
// Is this file going to be emitted separately
let sourceFileName: string;
const outFile = options.outFile || options.out;
if (!outFile) {
if (options.outDir) {
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
else {
sourceFileName = sourceFile.fileName;
}
}
else {
// Goes to single --out file
sourceFileName = outFile;
}
const dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
function findUnit(fileName: string, units: TestFile[]) {
return ts.forEach(units, unit => unit.unitName === fileName ? unit : undefined);
}
}
function normalizeLineEndings(text: string, lineEnding: string): string {
@@ -1230,7 +1118,7 @@ namespace Harness {
return errorOutput;
}
export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: ts.Diagnostic[]) {
export function getErrorBaseline(inputFiles: TestFile[], diagnostics: ts.Diagnostic[]) {
diagnostics.sort(ts.compareDiagnostics);
const outputLines: string[] = [];
// Count up all errors that were found in files other than lib.d.ts so we don't miss any
@@ -1371,16 +1259,6 @@ namespace Harness {
}
}
/** The harness' compiler instance used when tests are actually run. Reseting or changing settings of this compiler instance must be done within a test case (i.e., describe/it) */
let harnessCompiler: HarnessCompiler;
/** Returns the singleton harness compiler instance for generating and running tests.
If required a fresh compiler instance will be created, otherwise the existing singleton will be re-used.
*/
export function getCompiler() {
return harnessCompiler = harnessCompiler || new HarnessCompiler();
}
// This does not need to exist strictly speaking, but many tests will need to be updated if it's removed
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
@@ -1429,9 +1307,9 @@ namespace Harness {
/** @param fileResults an array of strings for the fileName and an ITextWriter with its code */
constructor(fileResults: GeneratedFile[], errors: ts.Diagnostic[], public program: ts.Program,
public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[]) {
public currentDirectoryForProgram: string, private sourceMapData: ts.SourceMapData[], public traceResults: string[]) {
fileResults.forEach(emittedFile => {
for (const emittedFile of fileResults) {
if (isDTS(emittedFile.fileName)) {
// .d.ts file, add to declFiles emit
this.declFilesCode.push(emittedFile);
@@ -1446,14 +1324,14 @@ namespace Harness {
else {
throw new Error("Unrecognized file extension for file " + emittedFile.fileName);
}
});
}
this.errors = errors;
}
public getSourceMapRecord() {
if (this.sourceMapData) {
return Harness.SourceMapRecoder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
return Harness.SourceMapRecorder.getSourceMapRecord(this.sourceMapData, this.program, this.files);
}
}
}
@@ -1489,7 +1367,7 @@ namespace Harness {
}
/** Given a test file containing // @FileName directives, return an array of named units of code to be added to an existing compiler instance */
export function makeUnitsFromTest(code: string, fileName: string): { settings: CompilerSettings; testUnitData: TestUnitData[]; } {
export function makeUnitsFromTest(code: string, fileName: string, rootDir?: string): { settings: CompilerSettings; testUnitData: TestUnitData[]; tsConfig: ts.ParsedCommandLine } {
const settings = extractCompilerSettings(code);
// List of all the subfiles we've parsed out
@@ -1555,7 +1433,7 @@ namespace Harness {
}
// normalize the fileName for the single file case
currentFileName = testUnitData.length > 0 ? currentFileName : Path.getFileName(fileName);
currentFileName = testUnitData.length > 0 || currentFileName ? currentFileName : Path.getFileName(fileName);
// EOF, push whatever remains
const newTestFile2 = {
@@ -1567,7 +1445,31 @@ namespace Harness {
};
testUnitData.push(newTestFile2);
return { settings, testUnitData };
// unit tests always list files explicitly
const parseConfigHost: ts.ParseConfigHost = {
readDirectory: (name) => []
};
// check if project has tsconfig.json in the list of files
let tsConfig: ts.ParsedCommandLine;
for (let i = 0; i < testUnitData.length; i++) {
const data = testUnitData[i];
if (ts.getBaseFileName(data.name).toLowerCase() === "tsconfig.json") {
const configJson = ts.parseConfigFileTextToJson(data.name, data.content);
assert.isTrue(configJson.config !== undefined);
let baseDir = ts.normalizePath(ts.getDirectoryPath(data.name));
if (rootDir) {
baseDir = ts.getNormalizedAbsolutePath(baseDir, rootDir);
}
tsConfig = ts.parseJsonConfigFileContent(configJson.config, parseConfigHost, baseDir);
// delete entry from the list
testUnitData.splice(i, 1);
break;
}
}
return { settings, testUnitData, tsConfig };
}
}
@@ -1674,7 +1576,7 @@ namespace Harness {
const encoded_actual = Utils.encodeString(actual);
if (expected != encoded_actual) {
// Overwrite & issue error
const errMsg = "The baseline file " + relativeFileName + " has changed";
const errMsg = "The baseline file " + relativeFileName + " has changed.";
throw new Error(errMsg);
}
}
@@ -1711,12 +1613,9 @@ namespace Harness {
return filePath.indexOf(Harness.libFolder) === 0;
}
export function getDefaultLibraryFile(io: Harness.IO): { unitName: string, content: string } {
export function getDefaultLibraryFile(io: Harness.IO): Harness.Compiler.TestFile {
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + "lib.d.ts";
return {
unitName: libFile,
content: io.readFile(libFile)
};
return { unitName: libFile, content: io.readFile(libFile) };
}
if (Error) (<any>Error).stackTraceLimit = 1;
+24 -20
View File
@@ -7,7 +7,7 @@ namespace Harness.LanguageService {
export class ScriptInfo {
public version: number = 1;
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
public lineMap: number[] = undefined;
private lineMap: number[] = undefined;
constructor(public fileName: string, public content: string) {
this.setContent(content);
@@ -15,7 +15,11 @@ namespace Harness.LanguageService {
private setContent(content: string): void {
this.content = content;
this.lineMap = ts.computeLineStarts(content);
this.lineMap = undefined;
}
public getLineMap(): number[] {
return this.lineMap || (this.lineMap = ts.computeLineStarts(this.content));
}
public updateContent(content: string): void {
@@ -153,7 +157,7 @@ namespace Harness.LanguageService {
throw new Error("No script with name '" + fileName + "'");
}
public openFile(fileName: string): void {
public openFile(fileName: string, content?: string): void {
}
/**
@@ -164,7 +168,7 @@ namespace Harness.LanguageService {
const script: ScriptInfo = this.fileNameToScript[fileName];
assert.isNotNull(script);
return ts.computeLineAndCharacterOfPosition(script.lineMap, position);
return ts.computeLineAndCharacterOfPosition(script.getLineMap(), position);
}
}
@@ -179,6 +183,7 @@ namespace Harness.LanguageService {
const script = this.getScriptInfo(fileName);
return script ? new ScriptSnapshot(script) : undefined;
}
getScriptKind(fileName: string): ts.ScriptKind { return ts.ScriptKind.Unknown; }
getScriptVersion(fileName: string): string {
const script = this.getScriptInfo(fileName);
return script ? script.version.toString() : undefined;
@@ -189,7 +194,7 @@ namespace Harness.LanguageService {
error(s: string): void { }
}
export class NativeLanugageServiceAdapter implements LanguageServiceAdapter {
export class NativeLanguageServiceAdapter implements LanguageServiceAdapter {
private host: NativeLanguageServiceHost;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new NativeLanguageServiceHost(cancellationToken, options);
@@ -197,7 +202,7 @@ namespace Harness.LanguageService {
getHost() { return this.host; }
getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); }
getClassifier(): ts.Classifier { return ts.createClassifier(); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavaScriptFileExtension(fileName)); }
}
/// Shim adapter
@@ -249,6 +254,7 @@ namespace Harness.LanguageService {
const nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
}
getScriptKind(fileName: string): ts.ScriptKind { return this.nativeHost.getScriptKind(fileName); }
getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); }
getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); }
@@ -263,6 +269,10 @@ namespace Harness.LanguageService {
log(s: string): void { this.nativeHost.log(s); }
trace(s: string): void { this.nativeHost.trace(s); }
error(s: string): void { this.nativeHost.error(s); }
directoryExists(directoryName: string): boolean {
// for tests pessimistically assume that directory always exists
return true;
}
}
class ClassifierShimProxy implements ts.Classifier {
@@ -311,13 +321,6 @@ namespace Harness.LanguageService {
class LanguageServiceShimProxy implements ts.LanguageService {
constructor(private shim: ts.LanguageServiceShim) {
}
private unwrappJSONCallResult(result: string): any {
const parsedResult = JSON.parse(result);
if (parsedResult.error) {
throw new Error("Language Service Shim Error: " + JSON.stringify(parsedResult.error));
}
return parsedResult.result;
}
cleanupSemanticCache(): void {
this.shim.cleanupSemanticCache();
}
@@ -420,13 +423,13 @@ namespace Harness.LanguageService {
getProgram(): ts.Program {
throw new Error("Program can not be marshaled across the shim layer.");
}
getSourceFile(fileName: string): ts.SourceFile {
getNonBoundSourceFile(fileName: string): ts.SourceFile {
throw new Error("SourceFile can not be marshaled across the shim layer.");
}
dispose(): void { this.shim.dispose({}); }
}
export class ShimLanugageServiceAdapter implements LanguageServiceAdapter {
export class ShimLanguageServiceAdapter implements LanguageServiceAdapter {
private host: ShimLanguageServiceHost;
private factory: ts.TypeScriptServicesFactory;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
@@ -493,9 +496,9 @@ namespace Harness.LanguageService {
this.client = client;
}
openFile(fileName: string): void {
super.openFile(fileName);
this.client.openFile(fileName);
openFile(fileName: string, content?: string): void {
super.openFile(fileName, content);
this.client.openFile(fileName, content);
}
editScript(fileName: string, start: number, end: number, newText: string) {
@@ -546,7 +549,8 @@ namespace Harness.LanguageService {
}
directoryExists(path: string): boolean {
return false;
// for tests assume that directory exists
return true;
}
getExecutingFilePath(): string {
@@ -607,7 +611,7 @@ namespace Harness.LanguageService {
}
}
export class ServerLanugageServiceAdapter implements LanguageServiceAdapter {
export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
private host: SessionClientHost;
private client: ts.server.SessionClient;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
+14 -22
View File
@@ -136,7 +136,7 @@ namespace Playback {
};
wrapper.startReplayFromData = log => {
replayLog = log;
// Remove non-found files from the log (shouldn't really need them, but we still record them for diganostic purposes)
// Remove non-found files from the log (shouldn't really need them, but we still record them for diagnostic purposes)
replayLog.filesRead = replayLog.filesRead.filter(f => f.result.contents !== undefined);
};
@@ -174,7 +174,7 @@ namespace Playback {
return true;
}
else {
return findResultByFields(replayLog.fileExists, { path }, false);
return findResultByFields(replayLog.fileExists, { path }, /*defaultValue*/ false);
}
})
);
@@ -223,7 +223,18 @@ namespace Playback {
recordLog.directoriesRead.push(logEntry);
return result;
},
(path, extension, exclude) => findResultByPath(wrapper, replayLog.directoriesRead.filter(d => d.extension === extension && ts.arrayIsEqualTo(d.exclude, exclude)), path));
(path, extension, exclude) => findResultByPath(wrapper,
replayLog.directoriesRead.filter(
d => {
if (d.extension === extension) {
if (d.exclude) {
return ts.arrayIsEqualTo(d.exclude, exclude);
}
return true;
}
return false;
}
), path));
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
@@ -305,25 +316,6 @@ namespace Playback {
}
}
const pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
const key = left + "-~~-" + right;
function areSame(a: string, b: string) {
return ts.normalizeSlashes(a).toLowerCase() === ts.normalizeSlashes(b).toLowerCase();
}
function check() {
if (Harness.Path.getFileName(left).toLowerCase() === Harness.Path.getFileName(right).toLowerCase()) {
return areSame(left, right) || areSame(wrapper.resolvePath(left), right) || areSame(left, wrapper.resolvePath(right)) || areSame(wrapper.resolvePath(left), wrapper.resolvePath(right));
}
}
if (pathEquivCache.hasOwnProperty(key)) {
return pathEquivCache[key];
}
else {
return pathEquivCache[key] = check();
}
}
function noOpReplay(name: string) {
// console.log("Swallowed write operation during replay: " + name);
}
+129 -73
View File
@@ -7,19 +7,11 @@ interface ProjectRunnerTestCase {
scenario: string;
projectRoot: string; // project where it lives - this also is the current directory when compiling
inputFiles: string[]; // list of input files to be given to program
out?: string; // --out
outDir?: string; // --outDir
sourceMap?: boolean; // --map
mapRoot?: string; // --mapRoot
resolveMapRoot?: boolean; // should we resolve this map root and give compiler the absolute disk path as map root?
sourceRoot?: string; // --sourceRoot
resolveSourceRoot?: boolean; // should we resolve this source root and give compiler the absolute disk path as map root?
declaration?: boolean; // --d
baselineCheck?: boolean; // Verify the baselines of output files, if this is false, we will write to output to the disk but there is no verification of baselines
runTest?: boolean; // Run the resulting test
bug?: string; // If there is any bug associated with this test case
noResolve?: boolean;
rootDir?: string; // --rootDir
}
interface ProjectRunnerTestCaseResolutionInfo extends ProjectRunnerTestCase {
@@ -34,14 +26,14 @@ interface BatchCompileProjectTestCaseEmittedFile extends Harness.Compiler.Genera
interface CompileProjectFilesResult {
moduleKind: ts.ModuleKind;
program: ts.Program;
program?: ts.Program;
compilerOptions?: ts.CompilerOptions;
errors: ts.Diagnostic[];
sourceMapData: ts.SourceMapData[];
sourceMapData?: ts.SourceMapData[];
}
interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult {
outputFiles: BatchCompileProjectTestCaseEmittedFile[];
nonSubfolderDiskFiles: number;
outputFiles?: BatchCompileProjectTestCaseEmittedFile[];
}
class ProjectRunner extends RunnerBase {
@@ -59,7 +51,7 @@ class ProjectRunner extends RunnerBase {
}
private runProjectTestCase(testCaseFileName: string) {
let testCase: ProjectRunnerTestCase;
let testCase: ProjectRunnerTestCase & ts.CompilerOptions;
let testFileText: string = null;
try {
@@ -70,7 +62,7 @@ class ProjectRunner extends RunnerBase {
}
try {
testCase = <ProjectRunnerTestCase>JSON.parse(testFileText);
testCase = <ProjectRunnerTestCase & ts.CompilerOptions>JSON.parse(testFileText);
}
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
@@ -128,9 +120,10 @@ class ProjectRunner extends RunnerBase {
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: () => string[],
getSourceFileTextImpl: (fileName: string) => string,
writeFile: (fileName: string, data: string, writeByteOrderMark: boolean) => void): CompileProjectFilesResult {
writeFile: (fileName: string, data: string, writeByteOrderMark: boolean) => void,
compilerOptions: ts.CompilerOptions): CompileProjectFilesResult {
const program = ts.createProgram(getInputFiles(), createCompilerOptions(), createCompilerHost());
const program = ts.createProgram(getInputFiles(), compilerOptions, createCompilerHost());
let errors = ts.getPreEmitDiagnostics(program);
const emitResult = program.emit();
@@ -155,21 +148,6 @@ class ProjectRunner extends RunnerBase {
sourceMapData
};
function createCompilerOptions(): ts.CompilerOptions {
return {
declaration: !!testCase.declaration,
sourceMap: !!testCase.sourceMap,
outFile: testCase.out,
outDir: testCase.outDir,
mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? Harness.IO.resolvePath(testCase.mapRoot) : testCase.mapRoot,
sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? Harness.IO.resolvePath(testCase.sourceRoot) : testCase.sourceRoot,
module: moduleKind,
moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
noResolve: testCase.noResolve,
rootDir: testCase.rootDir
};
}
function getSourceFileText(fileName: string): string {
const text = getSourceFileTextImpl(fileName);
return text !== undefined ? text : getSourceFileTextImpl(ts.getNormalizedAbsolutePath(fileName, getCurrentDirectory()));
@@ -209,23 +187,105 @@ class ProjectRunner extends RunnerBase {
let nonSubfolderDiskFiles = 0;
const outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
let inputFiles = testCase.inputFiles;
let compilerOptions = createCompilerOptions();
const projectCompilerResult = compileProjectFiles(moduleKind, () => testCase.inputFiles, getSourceFileText, writeFile);
let configFileName: string;
if (compilerOptions.project) {
// Parse project
configFileName = ts.normalizePath(ts.combinePaths(compilerOptions.project, "tsconfig.json"));
assert(!inputFiles || inputFiles.length === 0, "cannot specify input files and project option together");
}
else if (!inputFiles || inputFiles.length === 0) {
configFileName = ts.findConfigFile("", fileExists);
}
if (configFileName) {
const result = ts.readConfigFile(configFileName, getSourceFileText);
if (result.error) {
return {
moduleKind,
errors: [result.error]
};
}
const configObject = result.config;
const configParseResult = ts.parseJsonConfigFileContent(configObject, { readDirectory }, ts.getDirectoryPath(configFileName), compilerOptions);
if (configParseResult.errors.length > 0) {
return {
moduleKind,
errors: configParseResult.errors
};
}
inputFiles = configParseResult.fileNames;
compilerOptions = configParseResult.options;
}
const projectCompilerResult = compileProjectFiles(moduleKind, () => inputFiles, getSourceFileText, writeFile, compilerOptions);
return {
moduleKind,
program: projectCompilerResult.program,
compilerOptions,
sourceMapData: projectCompilerResult.sourceMapData,
outputFiles,
errors: projectCompilerResult.errors,
nonSubfolderDiskFiles,
};
function createCompilerOptions() {
// Set the special options that depend on other testcase options
const compilerOptions: ts.CompilerOptions = {
mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? Harness.IO.resolvePath(testCase.mapRoot) : testCase.mapRoot,
sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? Harness.IO.resolvePath(testCase.sourceRoot) : testCase.sourceRoot,
module: moduleKind,
moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
};
// Set the values specified using json
const optionNameMap: ts.Map<ts.CommandLineOption> = {};
ts.forEach(ts.optionDeclarations, option => {
optionNameMap[option.name] = option;
});
for (const name in testCase) {
if (name !== "mapRoot" && name !== "sourceRoot" && ts.hasProperty(optionNameMap, name)) {
const option = optionNameMap[name];
const optType = option.type;
let value = <any>testCase[name];
if (typeof optType !== "string") {
const key = value.toLowerCase();
if (ts.hasProperty(optType, key)) {
value = optType[key];
}
}
compilerOptions[option.name] = value;
}
}
return compilerOptions;
}
function getFileNameInTheProjectTest(fileName: string): string {
return ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName);
}
function readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
const harnessReadDirectoryResult = Harness.IO.readDirectory(getFileNameInTheProjectTest(rootDir), extension, exclude);
const result: string[] = [];
for (let i = 0; i < harnessReadDirectoryResult.length; i++) {
result[i] = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, harnessReadDirectoryResult[i],
getCurrentDirectory(), Harness.Compiler.getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
return result;
}
function fileExists(fileName: string): boolean {
return Harness.IO.fileExists(getFileNameInTheProjectTest(fileName));
}
function getSourceFileText(fileName: string): string {
let text: string = undefined;
try {
text = Harness.IO.readFile(ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName));
text = Harness.IO.readFile(getFileNameInTheProjectTest(fileName));
}
catch (e) {
// text doesn't get defined.
@@ -247,9 +307,10 @@ class ProjectRunner extends RunnerBase {
// If the generated output file resides in the parent folder or is rooted path,
// we need to instead create files that can live in the project reference folder
// but make sure extension of these files matches with the fileName the compiler asked to write
diskRelativeName = "diskFile" + nonSubfolderDiskFiles++ +
diskRelativeName = "diskFile" + nonSubfolderDiskFiles +
(Harness.Compiler.isDTS(fileName) ? ".d.ts" :
Harness.Compiler.isJS(fileName) ? ".js" : ".js.map");
nonSubfolderDiskFiles++;
}
if (Harness.Compiler.isJS(fileName)) {
@@ -288,13 +349,16 @@ class ProjectRunner extends RunnerBase {
function compileCompileDTsFiles(compilerResult: BatchCompileProjectTestCaseResult) {
const allInputFiles: { emittedFileName: string; code: string; }[] = [];
if (!compilerResult.program) {
return;
}
const compilerOptions = compilerResult.program.getCompilerOptions();
ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => {
if (Harness.Compiler.isDTS(sourceFile.fileName)) {
if (ts.isDeclarationFile(sourceFile)) {
allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text });
}
else if (ts.shouldEmitToOwnFile(sourceFile, compilerResult.program.getCompilerOptions())) {
else if (!(compilerOptions.outFile || compilerOptions.out)) {
let emitOutputFilePathWithoutExtension: string = undefined;
if (compilerOptions.outDir) {
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, compilerResult.program.getCurrentDirectory());
@@ -306,20 +370,24 @@ class ProjectRunner extends RunnerBase {
}
const outputDtsFileName = emitOutputFilePathWithoutExtension + ".d.ts";
allInputFiles.unshift(findOutpuDtsFile(outputDtsFileName));
const file = findOutputDtsFile(outputDtsFileName);
if (file) {
allInputFiles.unshift(file);
}
}
else {
const outputDtsFileName = ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts";
const outputDtsFile = findOutpuDtsFile(outputDtsFileName);
const outputDtsFile = findOutputDtsFile(outputDtsFileName);
if (!ts.contains(allInputFiles, outputDtsFile)) {
allInputFiles.unshift(outputDtsFile);
}
}
});
return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile);
// Dont allow config files since we are compiling existing source options
return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile, compilerResult.compilerOptions);
function findOutpuDtsFile(fileName: string) {
function findOutputDtsFile(fileName: string) {
return ts.forEach(compilerResult.outputFiles, outputFile => outputFile.emittedFileName === fileName ? outputFile : undefined);
}
function getInputFiles() {
@@ -343,11 +411,16 @@ class ProjectRunner extends RunnerBase {
}
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
const inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
const inputFiles = compilerResult.program ? ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => {
return { unitName: sourceFile.fileName, content: sourceFile.text };
});
return {
unitName: ts.isRootedDiskPath(sourceFile.fileName) ?
RunnerBase.removeFullPaths(sourceFile.fileName) :
sourceFile.fileName,
content: sourceFile.text
};
}) : [];
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
@@ -360,34 +433,17 @@ class ProjectRunner extends RunnerBase {
let compilerResult: BatchCompileProjectTestCaseResult;
function getCompilerResolutionInfo() {
const resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
scenario: testCase.scenario,
projectRoot: testCase.projectRoot,
inputFiles: testCase.inputFiles,
out: testCase.out,
outDir: testCase.outDir,
sourceMap: testCase.sourceMap,
mapRoot: testCase.mapRoot,
resolveMapRoot: testCase.resolveMapRoot,
sourceRoot: testCase.sourceRoot,
resolveSourceRoot: testCase.resolveSourceRoot,
declaration: testCase.declaration,
baselineCheck: testCase.baselineCheck,
runTest: testCase.runTest,
bug: testCase.bug,
rootDir: testCase.rootDir,
resolvedInputFiles: ts.map(compilerResult.program.getSourceFiles(), inputFile => {
return ts.convertToRelativePath(inputFile.fileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
}),
emittedFiles: ts.map(compilerResult.outputFiles, outputFile => {
return ts.convertToRelativePath(outputFile.emittedFileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
})
};
const resolutionInfo: ProjectRunnerTestCaseResolutionInfo & ts.CompilerOptions = JSON.parse(JSON.stringify(testCase));
resolutionInfo.resolvedInputFiles = ts.map(compilerResult.program.getSourceFiles(), inputFile => {
return ts.convertToRelativePath(inputFile.fileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
});
resolutionInfo.emittedFiles = ts.map(compilerResult.outputFiles, outputFile => {
return ts.convertToRelativePath(outputFile.emittedFileName, getCurrentDirectory(), path => Harness.Compiler.getCanonicalFileName(path));
});
return resolutionInfo;
}
it(name + ": " + moduleNameToString(moduleKind) , () => {
it(name + ": " + moduleNameToString(moduleKind), () => {
// Compile using node
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
@@ -428,7 +484,7 @@ class ProjectRunner extends RunnerBase {
it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline("SourceMapRecord for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
return Harness.SourceMapRecorder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
}
@@ -439,7 +495,7 @@ class ProjectRunner extends RunnerBase {
it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
const dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
if (dTsCompileResult && dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline("Errors in generated Dts files for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
return getErrorsBaseline(dTsCompileResult);
});
+17 -17
View File
@@ -27,26 +27,24 @@ namespace RWC {
export function runRWCTest(jsonPath: string) {
describe("Testing a RWC project: " + jsonPath, () => {
let inputFiles: { unitName: string; content: string; }[] = [];
let otherFiles: { unitName: string; content: string; }[] = [];
let inputFiles: Harness.Compiler.TestFile[] = [];
let otherFiles: Harness.Compiler.TestFile[] = [];
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
const baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: "rwc",
Baselinefolder: "internal/baselines"
};
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
const baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
let useCustomLibraryFile: boolean;
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
inputFiles = undefined;
otherFiles = undefined;
inputFiles = [];
otherFiles = [];
compilerResult = undefined;
compilerOptions = undefined;
baselineOpts = undefined;
baseName = undefined;
currentDirectory = undefined;
// useCustomLibraryFile is a flag specified in the json object to indicate whether to use built/local/lib.d.ts
// or to use lib.d.ts inside the json object. If the flag is true, use the lib.d.ts inside json file
@@ -55,7 +53,6 @@ namespace RWC {
});
it("can compile", () => {
const harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
const ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
@@ -71,8 +68,6 @@ namespace RWC {
});
runWithIOLog(ioLog, oldIO => {
harnessCompiler.reset();
let fileNames = opts.fileNames;
const tsconfigFile = ts.forEach(ioLog.filesRead, f => isTsConfigFile(f) ? f : undefined);
@@ -128,17 +123,21 @@ namespace RWC {
opts.options.noLib = true;
// Emit the results
compilerOptions = harnessCompiler.compileFiles(
compilerOptions = null;
const output = Harness.Compiler.compileFiles(
inputFiles,
otherFiles,
newCompilerResults => { compilerResult = newCompilerResults; },
/*settingsCallback*/ undefined, opts.options,
/* harnessOptions */ undefined,
opts.options,
// Since each RWC json file specifies its current directory in its json file, we need
// to pass this information in explicitly instead of acquiring it from the process.
currentDirectory);
compilerOptions = output.options;
compilerResult = output.result;
});
function getHarnessCompilerInputUnit(fileName: string) {
function getHarnessCompilerInputUnit(fileName: string): Harness.Compiler.TestFile {
const unitName = ts.normalizeSlashes(Harness.IO.resolvePath(fileName));
let content: string = null;
try {
@@ -201,8 +200,9 @@ namespace RWC {
it("has the expected errors in generated declaration files", () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline("has the expected errors in generated declaration files", baseName + ".dts.errors.txt", () => {
const declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
/*settingscallback*/ undefined, compilerOptions, currentDirectory);
const declFileCompilationResult = Harness.Compiler.compileDeclarationFiles(
inputFiles, otherFiles, compilerResult, /*harnessSettings*/ undefined, compilerOptions, currentDirectory);
if (declFileCompilationResult.declResult.errors.length === 0) {
return null;
}
+34 -35
View File
@@ -15,7 +15,7 @@
///<reference path="harness.ts"/>
namespace Harness.SourceMapRecoder {
namespace Harness.SourceMapRecorder {
interface SourceMapSpanWithDecodeErrors {
sourceMapSpan: ts.SourceMapSpan;
@@ -172,7 +172,6 @@ namespace Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 5. Check if there is name:
decodeOfEncodedMapping.nameIndex = -1;
if (!isSourceMappingSegmentEnd()) {
prevNameIndex += base64VLQFormatDecode();
decodeOfEncodedMapping.nameIndex = prevNameIndex;
@@ -190,7 +189,7 @@ namespace Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
createErrorIfCondition(true, "No encoded entry found");
createErrorIfCondition(/*condition*/ true, "No encoded entry found");
}
export function hasCompletedDecoding() {
@@ -203,7 +202,7 @@ namespace Harness.SourceMapRecoder {
}
namespace SourceMapSpanWriter {
let sourceMapRecoder: Compiler.WriterAggregator;
let sourceMapRecorder: Compiler.WriterAggregator;
let sourceMapSources: string[];
let sourceMapNames: string[];
@@ -217,8 +216,8 @@ namespace Harness.SourceMapRecoder {
let prevWrittenJsLine: number;
let spanMarkerContinues: boolean;
export function intializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: Compiler.GeneratedFile) {
sourceMapRecoder = sourceMapRecordWriter;
export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: Compiler.GeneratedFile) {
sourceMapRecorder = sourceMapRecordWriter;
sourceMapSources = sourceMapData.sourceMapSources;
sourceMapNames = sourceMapData.sourceMapNames;
@@ -232,15 +231,15 @@ namespace Harness.SourceMapRecoder {
SourceMapDecoder.initializeSourceMapDecoding(sourceMapData);
sourceMapRecoder.WriteLine("===================================================================");
sourceMapRecoder.WriteLine("JsFile: " + sourceMapData.sourceMapFile);
sourceMapRecoder.WriteLine("mapUrl: " + sourceMapData.jsSourceMappingURL);
sourceMapRecoder.WriteLine("sourceRoot: " + sourceMapData.sourceMapSourceRoot);
sourceMapRecoder.WriteLine("sources: " + sourceMapData.sourceMapSources);
sourceMapRecorder.WriteLine("===================================================================");
sourceMapRecorder.WriteLine("JsFile: " + sourceMapData.sourceMapFile);
sourceMapRecorder.WriteLine("mapUrl: " + sourceMapData.jsSourceMappingURL);
sourceMapRecorder.WriteLine("sourceRoot: " + sourceMapData.sourceMapSourceRoot);
sourceMapRecorder.WriteLine("sources: " + sourceMapData.sourceMapSources);
if (sourceMapData.sourceMapSourcesContent) {
sourceMapRecoder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMapSourcesContent));
sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMapSourcesContent));
}
sourceMapRecoder.WriteLine("===================================================================");
sourceMapRecorder.WriteLine("===================================================================");
}
function getSourceMapSpanString(mapEntry: ts.SourceMapSpan, getAbsentNameIndex?: boolean) {
@@ -249,7 +248,7 @@ namespace Harness.SourceMapRecoder {
mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")";
}
else {
if (mapEntry.nameIndex !== -1 || getAbsentNameIndex) {
if ((mapEntry.nameIndex && mapEntry.nameIndex !== -1) || getAbsentNameIndex) {
mapString += " nameIndex (" + mapEntry.nameIndex + ")";
}
}
@@ -292,10 +291,10 @@ namespace Harness.SourceMapRecoder {
recordSourceMapSpan(sourceMapSpan);
assert.isTrue(spansOnSingleLine.length === 1);
sourceMapRecoder.WriteLine("-------------------------------------------------------------------");
sourceMapRecoder.WriteLine("emittedFile:" + jsFile.fileName);
sourceMapRecoder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex]);
sourceMapRecoder.WriteLine("-------------------------------------------------------------------");
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
sourceMapRecorder.WriteLine("emittedFile:" + jsFile.fileName);
sourceMapRecorder.WriteLine("sourceFile:" + sourceMapSources[spansOnSingleLine[0].sourceMapSpan.sourceIndex]);
sourceMapRecorder.WriteLine("-------------------------------------------------------------------");
tsLineMap = ts.computeLineStarts(newSourceFileCode);
tsCode = newSourceFileCode;
@@ -307,8 +306,8 @@ namespace Harness.SourceMapRecoder {
writeRecordedSpans();
if (!SourceMapDecoder.hasCompletedDecoding()) {
sourceMapRecoder.WriteLine("!!!! **** There are more source map entries in the sourceMap's mapping than what was encoded");
sourceMapRecoder.WriteLine("!!!! **** Remaining decoded string: " + SourceMapDecoder.getRemainingDecodeString());
sourceMapRecorder.WriteLine("!!!! **** There are more source map entries in the sourceMap's mapping than what was encoded");
sourceMapRecorder.WriteLine("!!!! **** Remaining decoded string: " + SourceMapDecoder.getRemainingDecodeString());
}
@@ -324,7 +323,7 @@ namespace Harness.SourceMapRecoder {
function writeJsFileLines(endJsLine: number) {
for (; prevWrittenJsLine < endJsLine; prevWrittenJsLine++) {
sourceMapRecoder.Write(">>>" + getTextOfLine(prevWrittenJsLine, jsLineMap, jsFile.code));
sourceMapRecorder.Write(">>>" + getTextOfLine(prevWrittenJsLine, jsLineMap, jsFile.code));
}
}
@@ -357,9 +356,9 @@ namespace Harness.SourceMapRecoder {
}
function writeSourceMapIndent(indentLength: number, indentPrefix: string) {
sourceMapRecoder.Write(indentPrefix);
sourceMapRecorder.Write(indentPrefix);
for (let i = 1; i < indentLength; i++) {
sourceMapRecoder.Write(" ");
sourceMapRecorder.Write(" ");
}
}
@@ -370,12 +369,12 @@ namespace Harness.SourceMapRecoder {
writeSourceMapIndent(prevEmittedCol, markerId);
for (let i = prevEmittedCol; i < endColumn; i++) {
sourceMapRecoder.Write("^");
sourceMapRecorder.Write("^");
}
if (endContinues) {
sourceMapRecoder.Write("->");
sourceMapRecorder.Write("->");
}
sourceMapRecoder.WriteLine("");
sourceMapRecorder.WriteLine("");
spanMarkerContinues = endContinues;
}
@@ -391,16 +390,16 @@ namespace Harness.SourceMapRecoder {
// If there are decode errors, write
for (let i = 0; i < currentSpan.decodeErrors.length; i++) {
writeSourceMapIndent(prevEmittedCol, markerIds[index]);
sourceMapRecoder.WriteLine(currentSpan.decodeErrors[i]);
sourceMapRecorder.WriteLine(currentSpan.decodeErrors[i]);
}
}
const tsCodeLineMap = ts.computeLineStarts(sourceText);
for (let i = 0; i < tsCodeLineMap.length; i++) {
writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >");
sourceMapRecoder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
sourceMapRecorder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
if (i === tsCodeLineMap.length - 1) {
sourceMapRecoder.WriteLine("");
sourceMapRecorder.WriteLine("");
}
}
@@ -408,7 +407,7 @@ namespace Harness.SourceMapRecoder {
}
function writeSpanDetails(currentSpan: SourceMapSpanWithDecodeErrors, index: number) {
sourceMapRecoder.WriteLine(markerIds[index] + getSourceMapSpanString(currentSpan.sourceMapSpan));
sourceMapRecorder.WriteLine(markerIds[index] + getSourceMapSpanString(currentSpan.sourceMapSpan));
}
if (spansOnSingleLine.length) {
@@ -432,19 +431,19 @@ namespace Harness.SourceMapRecoder {
// Emit column number etc
iterateSpans(writeSpanDetails);
sourceMapRecoder.WriteLine("---");
sourceMapRecorder.WriteLine("---");
}
}
}
export function getSourceMapRecord(sourceMapDataList: ts.SourceMapData[], program: ts.Program, jsFiles: Compiler.GeneratedFile[]) {
const sourceMapRecoder = new Compiler.WriterAggregator();
const sourceMapRecorder = new Compiler.WriterAggregator();
for (let i = 0; i < sourceMapDataList.length; i++) {
const sourceMapData = sourceMapDataList[i];
let prevSourceFile: ts.SourceFile;
SourceMapSpanWriter.intializeSourceMapSpanWriter(sourceMapRecoder, sourceMapData, jsFiles[i]);
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData, jsFiles[i]);
for (let j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
const decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
const currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
@@ -458,7 +457,7 @@ namespace Harness.SourceMapRecoder {
}
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
return sourceMapRecoder.lines.join("\r\n");
sourceMapRecorder.Close();
return sourceMapRecorder.lines.join("\r\n");
}
}
+17 -14
View File
@@ -5,9 +5,9 @@
class Test262BaselineRunner extends RunnerBase {
private static basePath = "internal/cases/test262";
private static helpersFilePath = "tests/cases/test262-harness/helpers.d.ts";
private static helperFile = {
private static helperFile: Harness.Compiler.TestFile = {
unitName: Test262BaselineRunner.helpersFilePath,
content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath)
content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath),
};
private static testFileExtensionRegex = /\.js$/;
private static options: ts.CompilerOptions = {
@@ -31,8 +31,7 @@ class Test262BaselineRunner extends RunnerBase {
let testState: {
filename: string;
compilerResult: Harness.Compiler.CompilerResult;
inputFiles: { unitName: string; content: string }[];
program: ts.Program;
inputFiles: Harness.Compiler.TestFile[];
};
before(() => {
@@ -40,8 +39,9 @@ class Test262BaselineRunner extends RunnerBase {
const testFilename = ts.removeFileExtension(filePath).replace(/\//g, "_") + ".test";
const testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
const inputFiles = testCaseContent.testUnitData.map(unit => {
return { unitName: Test262BaselineRunner.getTestFilePath(unit.name), content: unit.content };
const inputFiles: Harness.Compiler.TestFile[] = testCaseContent.testUnitData.map(unit => {
const unitName = Test262BaselineRunner.getTestFilePath(unit.name);
return { unitName, content: unit.content };
});
// Emit the results
@@ -49,13 +49,16 @@ class Test262BaselineRunner extends RunnerBase {
filename: testFilename,
inputFiles: inputFiles,
compilerResult: undefined,
program: undefined,
};
Harness.Compiler.getCompiler().compileFiles([Test262BaselineRunner.helperFile].concat(inputFiles), /*otherFiles*/ [], (compilerResult, program) => {
testState.compilerResult = compilerResult;
testState.program = program;
}, /*settingsCallback*/ undefined, Test262BaselineRunner.options);
const output = Harness.Compiler.compileFiles(
[Test262BaselineRunner.helperFile].concat(inputFiles),
/*otherFiles*/ [],
/* harnessOptions */ undefined,
Test262BaselineRunner.options,
/* currentDirectory */ undefined
);
testState.compilerResult = output.result;
});
after(() => {
@@ -80,14 +83,14 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
it("satisfies inletiants", () => {
const sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
it("satisfies invariants", () => {
const sourceFile = testState.compilerResult.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it("has the expected AST", () => {
Harness.Baseline.runBaseline("has the expected AST", testState.filename + ".AST.txt", () => {
const sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
const sourceFile = testState.compilerResult.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
});
+263 -182
View File
File diff suppressed because it is too large Load Diff
+85 -34
View File
@@ -321,6 +321,7 @@ interface AudioContext extends EventTarget {
destination: AudioDestinationNode;
listener: AudioListener;
sampleRate: number;
state: string;
createAnalyser(): AnalyserNode;
createBiquadFilter(): BiquadFilterNode;
createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;
@@ -377,6 +378,8 @@ interface AudioNode extends EventTarget {
numberOfOutputs: number;
connect(destination: AudioNode, output?: number, input?: number): void;
disconnect(output?: number): void;
disconnect(destination: AudioNode, output?: number, input?: number): void;
disconnect(destination: AudioParam, output?: number): void;
}
declare var AudioNode: {
@@ -1254,7 +1257,7 @@ interface Console {
select(element: Element): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(): void;
trace(message?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
}
@@ -1513,9 +1516,9 @@ interface DataTransferItemList {
length: number;
add(data: File): DataTransferItem;
clear(): void;
item(index: number): File;
item(index: number): DataTransferItem;
remove(index: number): void;
[index: number]: File;
[index: number]: DataTransferItem;
}
declare var DataTransferItemList: {
@@ -2058,6 +2061,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Gets or sets the version attribute specified in the declaration of an XML document.
*/
xmlVersion: string;
currentScript: HTMLScriptElement;
adoptNode(source: Node): Node;
captureEvents(): void;
clear(): void;
@@ -2567,6 +2571,8 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param content The text and HTML tags to write.
*/
writeln(...content: string[]): void;
createElement(tagName: "picture"): HTMLPictureElement;
getElementsByTagName(tagname: "picture"): NodeListOf<HTMLPictureElement>;
addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -2773,6 +2779,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
tagName: string;
id: string;
className: string;
innerHTML: string;
getAttribute(name?: string): string;
getAttributeNS(namespaceURI: string, localName: string): string;
getAttributeNode(name: string): Attr;
@@ -2968,7 +2975,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
removeAttributeNode(oldAttr: Attr): Attr;
requestFullscreen(): void;
requestPointerLock(): void;
setAttribute(name?: string, value?: string): void;
setAttribute(name: string, value: string): void;
setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void;
setAttributeNode(newAttr: Attr): Attr;
setAttributeNodeNS(newAttr: Attr): Attr;
@@ -2977,6 +2984,8 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
webkitRequestFullScreen(): void;
webkitRequestFullscreen(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
matches(selector: string): boolean;
getElementsByTagName(tagname: "picture"): NodeListOf<HTMLPictureElement>;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -3766,6 +3775,7 @@ interface HTMLCanvasElement extends HTMLElement {
* @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image.
*/
toDataURL(type?: string, ...args: any[]): string;
toBlob(): Blob;
}
declare var HTMLCanvasElement: {
@@ -3961,7 +3971,6 @@ interface HTMLElement extends Element {
title: string;
blur(): void;
click(): void;
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
insertAdjacentElement(position: string, insertedElement: Element): Element;
@@ -5511,7 +5520,7 @@ interface HTMLMediaElement extends HTMLElement {
* Gets or sets the current playback position, in seconds.
*/
preload: string;
readyState: any;
readyState: number;
/**
* Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked.
*/
@@ -6135,7 +6144,7 @@ interface HTMLSelectElement extends HTMLElement {
* Sets or retrieves the name of the object.
*/
name: string;
options: HTMLSelectElement;
options: HTMLCollection;
/**
* When present, marks an element that can't be submitted without a value.
*/
@@ -6168,6 +6177,7 @@ interface HTMLSelectElement extends HTMLElement {
* Returns whether an element will successfully validate based on forms validation rules and constraints.
*/
willValidate: boolean;
selectedOptions: HTMLCollection;
/**
* Adds an element to the areas, controlRange, or options collection.
* @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.
@@ -6421,19 +6431,19 @@ interface HTMLTableElement extends HTMLElement {
/**
* Creates an empty caption element in the table.
*/
createCaption(): HTMLElement;
createCaption(): HTMLTableCaptionElement;
/**
* Creates an empty tBody element in the table.
*/
createTBody(): HTMLElement;
createTBody(): HTMLTableSectionElement;
/**
* Creates an empty tFoot element in the table.
*/
createTFoot(): HTMLElement;
createTFoot(): HTMLTableSectionElement;
/**
* Returns the tHead element object if successful, or null otherwise.
*/
createTHead(): HTMLElement;
createTHead(): HTMLTableSectionElement;
/**
* Deletes the caption element and its contents from the table.
*/
@@ -6455,7 +6465,7 @@ interface HTMLTableElement extends HTMLElement {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
insertRow(index?: number): HTMLElement;
insertRow(index?: number): HTMLTableRowElement;
}
declare var HTMLTableElement: {
@@ -6506,7 +6516,7 @@ interface HTMLTableRowElement extends HTMLElement, HTMLTableAlignment {
* Creates a new cell in the table row, and adds the cell to the cells collection.
* @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.
*/
insertCell(index?: number): HTMLElement;
insertCell(index?: number): HTMLTableCellElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6533,7 +6543,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment {
* Creates a new row (tr) in the table, and adds the row to the rows collection.
* @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.
*/
insertRow(index?: number): HTMLElement;
insertRow(index?: number): HTMLTableRowElement;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6886,7 +6896,7 @@ interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
source: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
delete(): IDBRequest;
@@ -6920,11 +6930,11 @@ interface IDBDatabase extends EventTarget {
objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: string;
version: number;
close(): void;
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -6947,10 +6957,11 @@ declare var IDBFactory: {
}
interface IDBIndex {
keyPath: string;
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
@@ -6981,13 +6992,14 @@ declare var IDBKeyRange: {
interface IDBObjectStore {
indexNames: DOMStringList;
keyPath: string;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
@@ -7022,7 +7034,7 @@ interface IDBRequest extends EventTarget {
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
source: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -7071,7 +7083,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
data: number[];
data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -7635,7 +7647,7 @@ declare var MediaQueryList: {
interface MediaSource extends EventTarget {
activeSourceBuffers: SourceBufferList;
duration: number;
readyState: number;
readyState: string;
sourceBuffers: SourceBufferList;
addSourceBuffer(type: string): SourceBuffer;
endOfStream(error?: number): void;
@@ -7869,6 +7881,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
vibrate(pattern: number | number[]): boolean;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -7909,6 +7922,7 @@ interface Node extends EventTarget {
normalize(): void;
removeChild(oldChild: Node): Node;
replaceChild(newChild: Node, oldChild: Node): Node;
contains(node: Node): boolean;
ATTRIBUTE_NODE: number;
CDATA_SECTION_NODE: number;
COMMENT_NODE: number;
@@ -10207,11 +10221,14 @@ declare var SVGViewElement: {
}
interface SVGZoomAndPan {
zoomAndPan: number;
}
declare var SVGZoomAndPan: {
SVG_ZOOMANDPAN_DISABLE: number;
SVG_ZOOMANDPAN_MAGNIFY: number;
SVG_ZOOMANDPAN_UNKNOWN: number;
}
declare var SVGZoomAndPan: SVGZoomAndPan;
interface SVGZoomEvent extends UIEvent {
newScale: number;
@@ -10362,17 +10379,16 @@ declare var Storage: {
}
interface StorageEvent extends Event {
key: string;
newValue: any;
oldValue: any;
storageArea: Storage;
url: string;
initStorageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void;
key?: string;
oldValue?: string;
newValue?: string;
storageArea?: Storage;
}
declare var StorageEvent: {
prototype: StorageEvent;
new(): StorageEvent;
new (type: string, eventInitDict?: StorageEventInit): StorageEvent;
}
interface StyleMedia {
@@ -11970,7 +11986,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
msMatchMedia(mediaQuery: string): MediaQueryList;
msRequestAnimationFrame(callback: FrameRequestCallback): number;
msWriteProfilerMark(profilerMarkName: string): void;
open(url?: string, target?: string, features?: string, replace?: boolean): any;
open(url?: string, target?: string, features?: string, replace?: boolean): Window;
postMessage(message: any, targetOrigin: string, ports?: any): void;
print(): void;
prompt(message?: string, _default?: string): string;
@@ -12572,6 +12588,24 @@ interface XMLHttpRequestEventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface StorageEventInit extends EventInit {
key?: string;
oldValue?: string;
newValue?: string;
url: string;
storageArea?: Storage;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface NodeListOf<TNode extends Node> extends NodeList {
length: number;
item(index: number): TNode;
@@ -12607,6 +12641,23 @@ interface ProgressEventInit extends EventInit {
total?: number;
}
interface HTMLTemplateElement extends HTMLElement {
content: DocumentFragment;
}
declare var HTMLTemplateElement: {
prototype: HTMLTemplateElement;
new(): HTMLTemplateElement;
}
interface HTMLPictureElement extends HTMLElement {
}
declare var HTMLPictureElement: {
prototype: HTMLPictureElement;
new(): HTMLPictureElement;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@@ -12640,7 +12691,7 @@ interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(): void;
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
@@ -12803,7 +12854,7 @@ declare function msCancelRequestAnimationFrame(handle: number): void;
declare function msMatchMedia(mediaQuery: string): MediaQueryList;
declare function msRequestAnimationFrame(callback: FrameRequestCallback): number;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function open(url?: string, target?: string, features?: string, replace?: boolean): any;
declare function open(url?: string, target?: string, features?: string, replace?: boolean): Window;
declare function postMessage(message: any, targetOrigin: string, ports?: any): void;
declare function print(): void;
declare function prompt(message?: string, _default?: string): string;
+68 -50
View File
@@ -7,14 +7,14 @@ interface Symbol {
/** Returns the primitive value of the specified object. */
valueOf(): Object;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "Symbol";
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
prototype: Symbol;
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
@@ -34,7 +34,7 @@ interface SymbolConstructor {
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string;
keyFor(sym: symbol): string | undefined;
// Well-known Symbols
@@ -42,67 +42,67 @@ interface SymbolConstructor {
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
hasInstance: symbol;
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
isConcatSpreadable: symbol;
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
iterator: symbol;
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
match: symbol;
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
replace: symbol;
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
search: symbol;
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
species: symbol;
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
split: symbol;
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
toPrimitive: symbol;
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
toStringTag: symbol;
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
unscopables: symbol;
readonly unscopables: symbol;
}
declare var Symbol: SymbolConstructor;
@@ -200,7 +200,7 @@ interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
name: string;
readonly name: string;
/**
* Determines whether the given value inherits from this function if this function was used
@@ -218,11 +218,11 @@ interface NumberConstructor {
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
EPSILON: number;
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
@@ -253,14 +253,14 @@ interface NumberConstructor {
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
MAX_SAFE_INTEGER: number;
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
MIN_SAFE_INTEGER: number;
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
@@ -320,7 +320,7 @@ interface Array<T> {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T;
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@@ -331,7 +331,7 @@ interface Array<T> {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number;
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
@@ -407,7 +407,7 @@ interface String {
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number;
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
@@ -453,7 +453,7 @@ interface String {
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray; }): RegExpMatchArray;
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
@@ -565,7 +565,7 @@ interface IterableIterator<T> extends Iterator<T> {
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface GeneratorFunctionConstructor {
@@ -575,7 +575,7 @@ interface GeneratorFunctionConstructor {
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
prototype: GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;
@@ -690,7 +690,7 @@ interface Math {
*/
cbrt(x: number): number;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "Math";
}
interface Date {
@@ -723,7 +723,7 @@ interface RegExp {
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray;
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
@@ -776,19 +776,19 @@ interface RegExp {
*
* If no flags are set, the value is the empty string.
*/
flags: string;
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
sticky: boolean;
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
unicode: boolean;
readonly unicode: boolean;
}
interface RegExpConstructor {
@@ -800,38 +800,38 @@ interface Map<K, V> {
delete(key: K): boolean;
entries(): IterableIterator<[K, V]>;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V;
get(key: K): V | undefined;
has(key: K): boolean;
keys(): IterableIterator<K>;
set(key: K, value?: V): Map<K, V>;
size: number;
readonly size: number;
values(): IterableIterator<V>;
[Symbol.iterator]():IterableIterator<[K,V]>;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "Map";
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
prototype: Map<any, any>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "WeakMap";
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
prototype: WeakMap<any, any>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
@@ -843,17 +843,17 @@ interface Set<T> {
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
size: number;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
prototype: Set<any>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
@@ -862,19 +862,19 @@ interface WeakSet<T> {
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
prototype: WeakSet<any>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
interface JSON {
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "JSON";
}
/**
@@ -884,11 +884,11 @@ interface JSON {
* buffer as needed.
*/
interface ArrayBuffer {
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "DataView";
}
/**
@@ -909,6 +909,7 @@ interface Int8Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
interface Int8ArrayConstructor {
@@ -941,6 +942,7 @@ interface Uint8Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
interface Uint8ArrayConstructor {
@@ -976,6 +978,7 @@ interface Uint8ClampedArray {
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
interface Uint8ClampedArrayConstructor {
@@ -1013,6 +1016,7 @@ interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
interface Int16ArrayConstructor {
@@ -1045,6 +1049,7 @@ interface Uint16Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
interface Uint16ArrayConstructor {
@@ -1077,6 +1082,7 @@ interface Int32Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
interface Int32ArrayConstructor {
@@ -1109,6 +1115,7 @@ interface Uint32Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
interface Uint32ArrayConstructor {
@@ -1141,6 +1148,7 @@ interface Float32Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
interface Float32ArrayConstructor {
@@ -1173,6 +1181,7 @@ interface Float64Array {
*/
values(): IterableIterator<number>;
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}
interface Float64ArrayConstructor {
@@ -1224,7 +1233,7 @@ declare namespace Reflect {
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver? :any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
@@ -1249,14 +1258,14 @@ interface Promise<T> {
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
[Symbol.toStringTag]: string;
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
prototype: Promise<any>;
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
@@ -1272,7 +1281,16 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
@@ -1309,7 +1327,7 @@ interface PromiseConstructor {
*/
resolve(): Promise<void>;
[Symbol.species]: Function;
readonly [Symbol.species]: Function;
}
declare var Promise: PromiseConstructor;
+89
View File
@@ -0,0 +1,89 @@
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
+1
View File
@@ -0,0 +1 @@
/// <reference no-default-lib="true"/>
+23 -11
View File
@@ -69,7 +69,7 @@ interface Console {
select(element: any): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(): void;
trace(message?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
}
@@ -275,7 +275,7 @@ interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
source: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
delete(): IDBRequest;
@@ -309,11 +309,11 @@ interface IDBDatabase extends EventTarget {
objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: string;
version: number;
close(): void;
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -336,10 +336,11 @@ declare var IDBFactory: {
}
interface IDBIndex {
keyPath: string;
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
@@ -370,13 +371,14 @@ declare var IDBKeyRange: {
interface IDBObjectStore {
indexNames: DOMStringList;
keyPath: string;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
@@ -411,7 +413,7 @@ interface IDBRequest extends EventTarget {
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
source: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
@@ -460,7 +462,7 @@ declare var IDBVersionChangeEvent: {
}
interface ImageData {
data: number[];
data: Uint8ClampedArray;
height: number;
width: number;
}
@@ -892,6 +894,16 @@ interface WorkerUtils extends Object, WindowBase64 {
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
@@ -948,7 +960,7 @@ interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(): void;
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
+5 -5
View File
@@ -83,7 +83,7 @@ namespace ts.server {
private processResponse<T extends protocol.Response>(request: protocol.Request): T {
var lastMessage = this.messages.shift();
Debug.assert(!!lastMessage, "Did not recieve any responses.");
Debug.assert(!!lastMessage, "Did not receive any responses.");
// Read the content length
var contentLengthPrefix = "Content-Length: ";
@@ -108,7 +108,7 @@ namespace ts.server {
}
// verify the sequence numbers
Debug.assert(response.request_seq === request.seq, "Malformed response: response sequance number did not match request sequence number.");
Debug.assert(response.request_seq === request.seq, "Malformed response: response sequence number did not match request sequence number.");
// unmarshal errors
if (!response.success) {
@@ -120,8 +120,8 @@ namespace ts.server {
return response;
}
openFile(fileName: string): void {
var args: protocol.FileRequestArgs = { file: fileName };
openFile(fileName: string, content?: string): void {
var args: protocol.OpenRequestArgs = { file: fileName, fileContent: content };
this.processRequest(CommandNames.Open, args);
}
@@ -613,7 +613,7 @@ namespace ts.server {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
getSourceFile(fileName: string): SourceFile {
getNonBoundSourceFile(fileName: string): SourceFile {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
+84 -77
View File
@@ -100,7 +100,8 @@ namespace ts.server {
this.filenameToScript = createFileMap<ScriptInfo>();
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
readFile: fileName => this.host.readFile(fileName)
readFile: fileName => this.host.readFile(fileName),
directoryExists: directoryName => this.host.directoryExists(directoryName)
};
}
@@ -119,7 +120,7 @@ namespace ts.server {
if (!resolution) {
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
// ok, it is safe to use existing module resolution results
resolution = existingResolution;
}
else {
@@ -144,8 +145,8 @@ namespace ts.server {
}
if (resolution.resolvedModule) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
}
@@ -191,6 +192,10 @@ namespace ts.server {
return this.roots.map(root => root.fileName);
}
getScriptKind() {
return ScriptKind.Unknown;
}
getScriptVersion(filename: string) {
return this.getScriptInfo(filename).svc.latestVersion().toString();
}
@@ -263,13 +268,11 @@ namespace ts.server {
}
resolvePath(path: string): string {
const start = new Date().getTime();
const result = this.host.resolvePath(path);
return result;
}
fileExists(path: string): boolean {
const start = new Date().getTime();
const result = this.host.fileExists(path);
return result;
}
@@ -325,32 +328,6 @@ namespace ts.server {
}
}
// assumes normalized paths
function getAbsolutePath(filename: string, directory: string) {
const rootLength = ts.getRootLength(filename);
if (rootLength > 0) {
return filename;
}
else {
const splitFilename = filename.split("/");
const splitDir = directory.split("/");
let i = 0;
let dirTail = 0;
const sflen = splitFilename.length;
while ((i < sflen) && (splitFilename[i].charAt(0) == ".")) {
const dots = splitFilename[i];
if (dots == "..") {
dirTail++;
}
else if (dots != ".") {
return undefined;
}
i++;
}
return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join("/");
}
}
export interface ProjectOptions {
// these fields can be present in the project file
files?: string[];
@@ -371,6 +348,10 @@ namespace ts.server {
openRefCount = 0;
constructor(public projectService: ProjectService, public projectOptions?: ProjectOptions) {
if (projectOptions && projectOptions.files) {
// If files are listed explicitly, allow all extensions
projectOptions.compilerOptions.allowNonTsExtensions = true;
}
this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
}
@@ -384,7 +365,7 @@ namespace ts.server {
}
openReferencedFile(filename: string) {
return this.projectService.openFile(filename, false);
return this.projectService.openFile(filename, /*openedByClient*/ false);
}
getRootFiles() {
@@ -461,6 +442,7 @@ namespace ts.server {
setProjectOptions(projectOptions: ProjectOptions) {
this.projectOptions = projectOptions;
if (projectOptions.compilerOptions) {
projectOptions.compilerOptions.allowNonTsExtensions = true;
this.compilerService.setCompilerOptions(projectOptions.compilerOptions);
}
}
@@ -505,11 +487,11 @@ namespace ts.server {
openFileRootsConfigured: ScriptInfo[] = [];
// a path to directory watcher map that detects added tsconfig files
directoryWatchersForTsconfig: ts.Map<FileWatcher> = {};
// count of how many projects are using the directory watcher. If the
// count of how many projects are using the directory watcher. If the
// number becomes 0 for a watcher, then we should close it.
directoryWatchersRefCount: ts.Map<number> = {};
hostConfiguration: HostConfiguration;
timerForDetectingProjectFilelistChanges: Map<NodeJS.Timer> = {};
timerForDetectingProjectFileListChanges: Map<NodeJS.Timer> = {};
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
@@ -559,37 +541,38 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName)) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) {
return;
}
this.log("Detected source file changes: " + fileName);
this.startTimerForDetectingProjectFilelistChanges(project);
this.startTimerForDetectingProjectFileListChanges(project);
}
startTimerForDetectingProjectFilelistChanges(project: Project) {
if (this.timerForDetectingProjectFilelistChanges[project.projectFilename]) {
clearTimeout(this.timerForDetectingProjectFilelistChanges[project.projectFilename]);
startTimerForDetectingProjectFileListChanges(project: Project) {
if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) {
clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
}
this.timerForDetectingProjectFilelistChanges[project.projectFilename] = setTimeout(
() => this.handleProjectFilelistChanges(project),
this.timerForDetectingProjectFileListChanges[project.projectFilename] = setTimeout(
() => this.handleProjectFileListChanges(project),
250
);
}
handleProjectFilelistChanges(project: Project) {
const { succeeded, projectOptions, error } = this.configFileToProjectOptions(project.projectFilename);
handleProjectFileListChanges(project: Project) {
const { projectOptions } = this.configFileToProjectOptions(project.projectFilename);
const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f)));
const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f)));
// We check if the project file list has changed. If so, we update the project.
if (!arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) {
// For configured projects, the change is made outside the tsconfig file, and
// it is not likely to affect the project for other files opened by the client. We can
// it is not likely to affect the project for other files opened by the client. We can
// just update the current project.
this.updateConfiguredProject(project);
// Call updateProjectStructure to clean up inferred projects we may have
// Call updateProjectStructure to clean up inferred projects we may have
// created for the new files
this.updateProjectStructure();
}
@@ -606,7 +589,8 @@ namespace ts.server {
this.log("Detected newly added tsconfig file: " + fileName);
const { succeeded, projectOptions, error } = this.configFileToProjectOptions(fileName);
const { projectOptions } = this.configFileToProjectOptions(fileName);
const rootFilesInTsconfig = projectOptions.files.map(f => this.getCanonicalFileName(f));
const openFileRoots = this.openFileRoots.map(s => this.getCanonicalFileName(s.fileName));
@@ -739,7 +723,8 @@ namespace ts.server {
else {
for (const directory of project.directoriesWatchedForTsconfig) {
// if the ref count for this directory watcher drops to 0, it's time to close it
if (!(--project.projectService.directoryWatchersRefCount[directory])) {
project.projectService.directoryWatchersRefCount[directory]--;
if (!project.projectService.directoryWatchersRefCount[directory]) {
this.log("Close directory watcher for: " + directory);
project.projectService.directoryWatchersForTsconfig[directory].close();
delete project.projectService.directoryWatchersForTsconfig[directory];
@@ -811,8 +796,8 @@ namespace ts.server {
* @param info The file that has been closed or newly configured
*/
closeOpenFile(info: ScriptInfo) {
// Closing file should trigger re-reading the file content from disk. This is
// because the user may chose to discard the buffer content before saving
// Closing file should trigger re-reading the file content from disk. This is
// because the user may chose to discard the buffer content before saving
// to the disk, and the server's version of the file can be out of sync.
info.svc.reloadFromFile(info.fileName);
@@ -910,8 +895,8 @@ namespace ts.server {
}
/**
* This function is to update the project structure for every projects.
* It is called on the premise that all the configured projects are
* This function is to update the project structure for every projects.
* It is called on the premise that all the configured projects are
* up to date.
*/
updateProjectStructure() {
@@ -965,7 +950,7 @@ namespace ts.server {
if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) {
// If the root file has already been added into a configured project,
// meaning the original inferred project is gone already.
// meaning the original inferred project is gone already.
if (!rootedProject.isConfiguredProject()) {
this.removeProject(rootedProject);
}
@@ -1001,14 +986,15 @@ namespace ts.server {
/**
* @param filename is absolute pathname
* @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
openFile(fileName: string, openedByClient: boolean) {
openFile(fileName: string, openedByClient: boolean, fileContent?: string) {
fileName = ts.normalizePath(fileName);
let info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
let content: string;
if (this.host.fileExists(fileName)) {
content = this.host.readFile(fileName);
content = fileContent || this.host.readFile(fileName);
}
if (!content) {
if (openedByClient) {
@@ -1025,6 +1011,9 @@ namespace ts.server {
}
}
if (info) {
if (fileContent) {
info.svc.reload(fileContent);
}
if (openedByClient) {
info.isOpen = true;
}
@@ -1039,10 +1028,16 @@ namespace ts.server {
// the newly opened file.
findConfigFile(searchPath: string): string {
while (true) {
const fileName = ts.combinePaths(searchPath, "tsconfig.json");
if (this.host.fileExists(fileName)) {
return fileName;
const tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json");
if (this.host.fileExists(tsconfigFileName)) {
return tsconfigFileName;
}
const jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json");
if (this.host.fileExists(jsconfigFileName)) {
return jsconfigFileName;
}
const parentPath = ts.getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
@@ -1055,19 +1050,20 @@ namespace ts.server {
/**
* Open file whose contents is managed by the client
* @param filename is absolute pathname
* @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
openClientFile(fileName: string) {
openClientFile(fileName: string, fileContent?: string) {
this.openOrUpdateConfiguredProjectForFile(fileName);
const info = this.openFile(fileName, true);
const info = this.openFile(fileName, /*openedByClient*/ true, fileContent);
this.addOpenFile(info);
this.printProjects();
return info;
}
/**
* This function tries to search for a tsconfig.json for the given file. If we found it,
* This function tries to search for a tsconfig.json for the given file. If we found it,
* we first detect if there is already a configured project created for it: if so, we re-read
* the tsconfig file content and update the project; otherwise we create a new one.
* the tsconfig file content and update the project; otherwise we create a new one.
*/
openOrUpdateConfiguredProjectForFile(fileName: string) {
const searchPath = ts.normalizePath(getDirectoryPath(fileName));
@@ -1099,7 +1095,6 @@ namespace ts.server {
* Close file whose contents is managed by the client
* @param filename is absolute pathname
*/
closeClientFile(filename: string) {
const info = ts.lookUp(this.filenameToScriptInfo, filename);
if (info) {
@@ -1193,7 +1188,7 @@ namespace ts.server {
return { succeeded: false, error: rawConfig.error };
}
else {
const parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath);
const parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, /*existingOptions*/ {}, configFilename);
Debug.assert(!!parsedCommandLine.fileNames);
if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) {
@@ -1267,10 +1262,10 @@ namespace ts.server {
for (const fileName of fileNamesToAdd) {
let info = this.getScriptInfo(fileName);
if (!info) {
info = this.openFile(fileName, false);
info = this.openFile(fileName, /*openedByClient*/ false);
}
else {
// if the root file was opened by client, it would belong to either
// if the root file was opened by client, it would belong to either
// openFileRoots or openFileReferenced.
if (info.isOpen) {
if (this.openFileRoots.indexOf(info) >= 0) {
@@ -1316,7 +1311,10 @@ namespace ts.server {
this.setCompilerOptions(opt);
}
else {
this.setCompilerOptions(ts.getDefaultCompilerOptions());
const defaultOpts = ts.getDefaultCompilerOptions();
defaultOpts.allowNonTsExtensions = true;
defaultOpts.allowJs = true;
this.setCompilerOptions(defaultOpts);
}
this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
this.classifier = ts.createClassifier();
@@ -1328,7 +1326,7 @@ namespace ts.server {
}
isExternalModule(filename: string): boolean {
const sourceFile = this.languageService.getSourceFile(filename);
const sourceFile = this.languageService.getNonBoundSourceFile(filename);
return ts.isExternalModule(sourceFile);
}
@@ -1345,6 +1343,7 @@ namespace ts.server {
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
@@ -1745,7 +1744,8 @@ namespace ts.server {
let count = 1;
let pos = 0;
this.index.every((ll, s, len) => {
starts[count++] = pos;
starts[count] = pos;
count++;
pos += ll.text.length;
return true;
}, 0);
@@ -1753,9 +1753,9 @@ namespace ts.server {
}
getLineMapper() {
return ((line: number) => {
return (line: number) => {
return this.index.lineNumberToInfo(line).offset;
});
};
}
getTextChangeRangeSinceVersion(scriptVersion: number) {
@@ -2011,7 +2011,8 @@ namespace ts.server {
while (adjustedStart >= childCharCount) {
this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart);
adjustedStart -= childCharCount;
child = this.children[++childIndex];
childIndex++;
child = this.children[childIndex];
childCharCount = child.charCount();
}
// Case I: both start and end of range in same subtree
@@ -2026,14 +2027,16 @@ namespace ts.server {
return;
}
let adjustedLength = rangeLength - (childCharCount - adjustedStart);
child = this.children[++childIndex];
childIndex++;
child = this.children[childIndex];
childCharCount = child.charCount();
while (adjustedLength > childCharCount) {
if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) {
return;
}
adjustedLength -= childCharCount;
child = this.children[++childIndex];
childIndex++;
child = this.children[childIndex];
childCharCount = child.charCount();
}
if (adjustedLength > 0) {
@@ -2157,7 +2160,8 @@ namespace ts.server {
if (childIndex < clen) {
splitNode = new LineNode();
while (childIndex < clen) {
splitNode.add(this.children[childIndex++]);
splitNode.add(this.children[childIndex]);
childIndex++;
}
splitNode.updateCounts();
}
@@ -2198,7 +2202,9 @@ namespace ts.server {
let nodeIndex = 0;
childIndex++;
while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) {
this.children[childIndex++] = nodes[nodeIndex++];
this.children[childIndex] = nodes[nodeIndex];
childIndex++;
nodeIndex++;
}
let splitNodes: LineNode[] = [];
let splitNodeCount = 0;
@@ -2211,7 +2217,8 @@ namespace ts.server {
}
let splitNode = <LineNode>splitNodes[0];
while (nodeIndex < nodeCount) {
splitNode.add(nodes[nodeIndex++]);
splitNode.add(nodes[nodeIndex]);
nodeIndex++;
if (splitNode.children.length === lineCollectionCapacity) {
splitNodeIndex++;
splitNode = <LineNode>splitNodes[splitNodeIndex];
+11 -6
View File
@@ -444,7 +444,7 @@ declare namespace ts.server.protocol {
/** Defines space handling after a comma delimiter. Default value is true. */
insertSpaceAfterCommaDelimiter?: boolean;
/** Defines space handling after a semicolon in a for statemen. Default value is true */
/** Defines space handling after a semicolon in a for statement. Default value is true */
insertSpaceAfterSemicolonInForStatements?: boolean;
/** Defines space handling after a binary operator. Default value is true. */
@@ -469,7 +469,7 @@ declare namespace ts.server.protocol {
placeOpenBraceOnNewLineForControlBlocks?: boolean;
/** Index operator */
[key: string] : string | number | boolean;
[key: string]: string | number | boolean;
}
/**
@@ -513,6 +513,11 @@ declare namespace ts.server.protocol {
* Information found in an "open" request.
*/
export interface OpenRequestArgs extends FileRequestArgs {
/**
* Used when a version of the file content is known to be more up to date than the one on disk.
* Then the known content will be used upon opening instead of the disk copy
*/
fileContent?: string;
}
/**
@@ -830,7 +835,7 @@ declare namespace ts.server.protocol {
prefixDisplayParts: SymbolDisplayPart[];
/**
* The suffix disaply parts.
* The suffix display parts.
*/
suffixDisplayParts: SymbolDisplayPart[];
@@ -898,7 +903,7 @@ declare namespace ts.server.protocol {
}
/**
* Repsonse object for a SignatureHelpRequest.
* Response object for a SignatureHelpRequest.
*/
export interface SignatureHelpResponse extends Response {
body?: SignatureHelpItems;
@@ -965,7 +970,7 @@ declare namespace ts.server.protocol {
*/
export interface Diagnostic {
/**
* Starting file location at which text appies.
* Starting file location at which text applies.
*/
start: Location;
@@ -1174,7 +1179,7 @@ declare namespace ts.server.protocol {
}
/**
* NavBar itesm request; value of command field is "navbar".
* NavBar items request; value of command field is "navbar".
* Return response giving the list of navigation bar entries
* extracted from the requested file.
*/
-2
View File
@@ -4,9 +4,7 @@
/* tslint:disable:no-null */
namespace ts.server {
const nodeproto: typeof NodeJS._debugger = require("_debugger");
const readline: NodeJS.ReadLine = require("readline");
const path: NodeJS.Path = require("path");
const fs: typeof NodeJS.fs = require("fs");
const rl = readline.createInterface({
+14 -15
View File
@@ -129,9 +129,6 @@ namespace ts.server {
export class Session {
protected projectService: ProjectService;
private pendingOperation = false;
private fileHash: ts.Map<number> = {};
private nextFileId = 1;
private errorTimer: any; /*NodeJS.Timer | number*/
private immediateId: any;
private changeSeq = 0;
@@ -239,11 +236,6 @@ namespace ts.server {
}
}
private errorCheck(file: string, project: Project) {
this.syntacticCheck(file, project);
this.semanticCheck(file, project);
}
private reloadProjects() {
this.projectService.reloadProjects();
}
@@ -271,7 +263,8 @@ namespace ts.server {
let index = 0;
const checkOne = () => {
if (matchSeq(seq)) {
const checkSpec = checkList[index++];
const checkSpec = checkList[index];
index++;
if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) {
this.syntacticCheck(checkSpec.fileName, checkSpec.project);
this.immediateId = setImmediate(() => {
@@ -532,9 +525,13 @@ namespace ts.server {
};
}
private openClientFile(fileName: string) {
/**
* @param fileName is the name of the file to be opened
* @param fileContent is a version of the file content that is known to be more up to date than the one on disk
*/
private openClientFile(fileName: string, fileContent?: string) {
const file = ts.normalizePath(fileName);
this.projectService.openClientFile(file);
this.projectService.openClientFile(file, fileContent);
}
private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
@@ -606,7 +603,7 @@ namespace ts.server {
// Check whether we should auto-indent. This will be when
// the position is on a line containing only whitespace.
// This should leave the edits returned from
// getFormattingEditsAfterKeytroke either empty or pertaining
// getFormattingEditsAfterKeystroke either empty or pertaining
// only to the previous line. If all this is true, then
// add edits necessary to properly indent the current line.
if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
@@ -795,7 +792,9 @@ namespace ts.server {
}
private closeClientFile(fileName: string) {
if (!fileName) { return; }
if (!fileName) {
return;
}
const file = ts.normalizePath(fileName);
this.projectService.closeClientFile(file);
}
@@ -897,7 +896,7 @@ namespace ts.server {
}
getDiagnosticsForProject(delay: number, fileName: string) {
const { configFileName, fileNames } = this.getProjectInfo(fileName, true);
const { fileNames } = this.getProjectInfo(fileName, /*needFileNameList*/ true);
// No need to analyze lib.d.ts
let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0);
@@ -968,7 +967,7 @@ namespace ts.server {
},
[CommandNames.Open]: (request: protocol.Request) => {
const openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file);
this.openClientFile(openArgs.file, openArgs.fileContent);
return {responseRequired: false};
},
[CommandNames.Quickinfo]: (request: protocol.Request) => {
-1
View File
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
+285 -85
View File
@@ -10,13 +10,13 @@ namespace ts.BreakpointResolver {
*/
export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number) {
// Cannot set breakpoint in dts file
if (sourceFile.flags & NodeFlags.DeclarationFile) {
if (sourceFile.isDeclarationFile) {
return undefined;
}
let tokenAtLocation = getTokenAtPosition(sourceFile, position);
let lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) {
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
// eg: let x =10; |--- cursor is here
// let y = 10;
@@ -39,16 +39,27 @@ namespace ts.BreakpointResolver {
return spanInNode(tokenAtLocation);
function textSpan(startNode: Node, endNode?: Node) {
return createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd());
const start = startNode.decorators ?
skipTrivia(sourceFile.text, startNode.decorators.end) :
startNode.getStart(sourceFile);
return createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode: Node, previousTokenToFindNextEndToken: Node): TextSpan {
return textSpan(startNode, findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
}
function spanInNodeIfStartsOnSameLine(node: Node, otherwiseOnNode?: Node): TextSpan {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
return spanInNode(node);
}
return spanInNode(otherwiseOnNode);
}
function spanInNodeArray<T>(nodeArray: NodeArray<T>) {
return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
}
function spanInPreviousNode(node: Node): TextSpan {
return spanInNode(findPrecedingToken(node.pos, sourceFile));
}
@@ -59,28 +70,6 @@ namespace ts.BreakpointResolver {
function spanInNode(node: Node): TextSpan {
if (node) {
if (isExpression(node)) {
if (node.parent.kind === SyntaxKind.DoStatement) {
// Set span as if on while keyword
return spanInPreviousNode(node);
}
if (node.parent.kind === SyntaxKind.ForStatement) {
// For now lets set the span on this expression, fix it later
return textSpan(node);
}
if (node.parent.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.CommaToken) {
// if this is comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
if (node.parent.kind === SyntaxKind.ArrowFunction && (<FunctionLikeDeclaration>node.parent).body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
}
}
switch (node.kind) {
case SyntaxKind.VariableStatement:
// Span on first variable declaration
@@ -108,7 +97,7 @@ namespace ts.BreakpointResolver {
if (isFunctionBlock(node)) {
return spanInFunctionBlock(<Block>node);
}
// Fall through
// Fall through
case SyntaxKind.ModuleBlock:
return spanInBlock(<Block>node);
@@ -125,7 +114,7 @@ namespace ts.BreakpointResolver {
case SyntaxKind.WhileStatement:
// Span on while(...)
return textSpan(node, findNextToken((<WhileStatement>node).expression, node));
return textSpanEndingAtNextToken(node, (<WhileStatement>node).expression);
case SyntaxKind.DoStatement:
// span in statement of the do statement
@@ -137,7 +126,7 @@ namespace ts.BreakpointResolver {
case SyntaxKind.IfStatement:
// set on if(..) span
return textSpan(node, findNextToken((<IfStatement>node).expression, node));
return textSpanEndingAtNextToken(node, (<IfStatement>node).expression);
case SyntaxKind.LabeledStatement:
// span in statement
@@ -152,13 +141,16 @@ namespace ts.BreakpointResolver {
return spanInForStatement(<ForStatement>node);
case SyntaxKind.ForInStatement:
// span of for (a in ...)
return textSpanEndingAtNextToken(node, (<ForInStatement>node).expression);
case SyntaxKind.ForOfStatement:
// span on for (a in ...)
return textSpan(node, findNextToken((<ForInStatement | ForOfStatement>node).expression, node));
// span in initializer
return spanInInitializerOfForLike(<ForOfStatement | ForInStatement>node);
case SyntaxKind.SwitchStatement:
// span on switch(...)
return textSpan(node, findNextToken((<SwitchStatement>node).expression, node));
return textSpanEndingAtNextToken(node, (<SwitchStatement>node).expression);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
@@ -198,8 +190,7 @@ namespace ts.BreakpointResolver {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.BindingElement:
// span on complete node
return textSpan(node);
@@ -207,6 +198,13 @@ namespace ts.BreakpointResolver {
// span in statement
return spanInNode((<WithStatement>node).statement);
case SyntaxKind.Decorator:
return spanInNodeArray(node.parent.decorators);
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
return spanInBindingPattern(<BindingPattern>node);
// No breakpoint in interface, type alias
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
@@ -219,14 +217,17 @@ namespace ts.BreakpointResolver {
case SyntaxKind.CommaToken:
return spanInPreviousNode(node)
case SyntaxKind.OpenBraceToken:
return spanInOpenBraceToken(node);
case SyntaxKind.CloseBraceToken:
return spanInCloseBraceToken(node);
case SyntaxKind.OpenParenToken:
case SyntaxKind.CloseBracketToken:
return spanInCloseBracketToken(node);
case SyntaxKind.OpenParenToken:
return spanInOpenParenToken(node);
case SyntaxKind.CloseParenToken:
@@ -248,15 +249,93 @@ namespace ts.BreakpointResolver {
case SyntaxKind.FinallyKeyword:
return spanInNextNode(node);
case SyntaxKind.OfKeyword:
return spanInOfKeyword(node);
default:
// If this is name of property assignment, set breakpoint in the initializer
if (node.parent.kind === SyntaxKind.PropertyAssignment && (<PropertyDeclaration>node.parent).name === node) {
return spanInNode((<PropertyDeclaration>node.parent).initializer);
// Destructuring pattern in destructuring assignment
// [a, b, c] of
// [a, b, c] = expression
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
return spanInArrayLiteralOrObjectLiteralDestructuringPattern(<DestructuringPattern>node);
}
// Set breakpoint on identifier element of destructuring pattern
// a or ...c or d: x from
// [a, b, ...c] or { a, b } or { d: x } from destructuring pattern
if ((node.kind === SyntaxKind.Identifier ||
node.kind == SyntaxKind.SpreadElementExpression ||
node.kind === SyntaxKind.PropertyAssignment ||
node.kind === SyntaxKind.ShorthandPropertyAssignment) &&
isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
return textSpan(node);
}
if (node.kind === SyntaxKind.BinaryExpression) {
const binaryExpression = <BinaryExpression>node;
// Set breakpoint in destructuring pattern if its destructuring assignment
// [a, b, c] or {a, b, c} of
// [a, b, c] = expression or
// {a, b, c} = expression
if (isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) {
return spanInArrayLiteralOrObjectLiteralDestructuringPattern(
<ArrayLiteralExpression | ObjectLiteralExpression>binaryExpression.left);
}
if (binaryExpression.operatorToken.kind === SyntaxKind.EqualsToken &&
isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) {
// Set breakpoint on assignment expression element of destructuring pattern
// a = expression of
// [a = expression, b, c] = someExpression or
// { a = expression, b, c } = someExpression
return textSpan(node);
}
if (binaryExpression.operatorToken.kind === SyntaxKind.CommaToken) {
return spanInNode(binaryExpression.left);
}
}
if (isExpression(node)) {
switch (node.parent.kind) {
case SyntaxKind.DoStatement:
// Set span as if on while keyword
return spanInPreviousNode(node);
case SyntaxKind.Decorator:
// Set breakpoint on the decorator emit
return spanInNode(node.parent);
case SyntaxKind.ForStatement:
case SyntaxKind.ForOfStatement:
return textSpan(node);
case SyntaxKind.BinaryExpression:
if ((<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.CommaToken) {
// if this is comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
break;
case SyntaxKind.ArrowFunction:
if ((<FunctionLikeDeclaration>node.parent).body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
}
break;
}
}
// If this is name of property assignment, set breakpoint in the initializer
if (node.parent.kind === SyntaxKind.PropertyAssignment &&
(<PropertyDeclaration>node.parent).name === node &&
!isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
return spanInNode((<PropertyDeclaration>node.parent).initializer);
}
// Breakpoint in type assertion goes to its operand
if (node.parent.kind === SyntaxKind.TypeAssertionExpression && (<TypeAssertion>node.parent).type === node) {
return spanInNode((<TypeAssertion>node.parent).expression);
return spanInNextNode((<TypeAssertion>node.parent).type);
}
// return type of function go to previous token
@@ -264,48 +343,70 @@ namespace ts.BreakpointResolver {
return spanInPreviousNode(node);
}
// initializer of variable/parameter declaration go to previous node
if ((node.parent.kind === SyntaxKind.VariableDeclaration ||
node.parent.kind === SyntaxKind.Parameter)) {
const paramOrVarDecl = <VariableDeclaration | ParameterDeclaration>node.parent;
if (paramOrVarDecl.initializer === node ||
paramOrVarDecl.type === node ||
isAssignmentOperator(node.kind)) {
return spanInPreviousNode(node);
}
}
if (node.parent.kind === SyntaxKind.BinaryExpression) {
const binaryExpression = <BinaryExpression>node.parent;
if (isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
(binaryExpression.right === node ||
binaryExpression.operatorToken === node)) {
// If initializer of destructuring assignment move to previous token
return spanInPreviousNode(node);
}
}
// Default go to parent to set the breakpoint
return spanInNode(node.parent);
}
}
function textSpanFromVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan {
let declarations = variableDeclaration.parent.declarations;
if (declarations && declarations[0] === variableDeclaration) {
// First declaration - include let keyword
return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
else {
// Span only on this declaration
return textSpan(variableDeclaration);
}
}
function spanInVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan {
// If declaration of for in statement, just set the span in parent
if (variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement ||
variableDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement) {
if (variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement) {
return spanInNode(variableDeclaration.parent.parent);
}
let isParentVariableStatement = variableDeclaration.parent.parent.kind === SyntaxKind.VariableStatement;
let isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === SyntaxKind.ForStatement && contains((<VariableDeclarationList>(<ForStatement>variableDeclaration.parent.parent).initializer).declarations, variableDeclaration);
let declarations = isParentVariableStatement
? (<VariableStatement>variableDeclaration.parent.parent).declarationList.declarations
: isDeclarationOfForStatement
? (<VariableDeclarationList>(<ForStatement>variableDeclaration.parent.parent).initializer).declarations
: undefined;
// If this is a destructuring pattern set breakpoint in binding pattern
if (isBindingPattern(variableDeclaration.name)) {
return spanInBindingPattern(<BindingPattern>variableDeclaration.name);
}
// Breakpoint is possible in variableDeclaration only if there is initialization
if (variableDeclaration.initializer || (variableDeclaration.flags & NodeFlags.Export)) {
if (declarations && declarations[0] === variableDeclaration) {
if (isParentVariableStatement) {
// First declaration - include let keyword
return textSpan(variableDeclaration.parent, variableDeclaration);
}
else {
Debug.assert(isDeclarationOfForStatement);
// Include let keyword from for statement declarations in the span
return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
}
}
else {
// Span only on this declaration
return textSpan(variableDeclaration);
}
// or its declaration from 'for of'
if (variableDeclaration.initializer ||
(variableDeclaration.flags & NodeFlags.Export) ||
variableDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement) {
return textSpanFromVariableDeclaration(variableDeclaration);
}
else if (declarations && declarations[0] !== variableDeclaration) {
let declarations = variableDeclaration.parent.declarations;
if (declarations && declarations[0] !== variableDeclaration) {
// If we cant set breakpoint on this declaration, set it on previous one
let indexOfCurrentDeclaration = indexOf(declarations, variableDeclaration);
return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]);
// Because the variable declaration may be binding pattern and
// we would like to set breakpoint in last binding element if thats the case,
// use preceding token instead
return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
}
}
@@ -316,7 +417,11 @@ namespace ts.BreakpointResolver {
}
function spanInParameterDeclaration(parameter: ParameterDeclaration): TextSpan {
if (canHaveSpanInParameterDeclaration(parameter)) {
if (isBindingPattern(parameter.name)) {
// set breakpoint in binding pattern
return spanInBindingPattern(<BindingPattern>parameter.name);
}
else if (canHaveSpanInParameterDeclaration(parameter)) {
return textSpan(parameter);
}
else {
@@ -373,11 +478,11 @@ namespace ts.BreakpointResolver {
case SyntaxKind.WhileStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);
// Set span on previous token if it starts on same line otherwise on the first statement of the block
case SyntaxKind.ForStatement:
case SyntaxKind.ForOfStatement:
return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
}
@@ -385,17 +490,23 @@ namespace ts.BreakpointResolver {
return spanInNode(block.statements[0]);
}
function spanInInitializerOfForLike(forLikeStatement: ForStatement | ForOfStatement | ForInStatement): TextSpan {
if (forLikeStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
// declaration list, set breakpoint in first declaration
let variableDeclarationList = <VariableDeclarationList>forLikeStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
}
}
else {
// Expression - set breakpoint in it
return spanInNode(forLikeStatement.initializer);
}
}
function spanInForStatement(forStatement: ForStatement): TextSpan {
if (forStatement.initializer) {
if (forStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
let variableDeclarationList = <VariableDeclarationList>forStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
}
}
else {
return spanInNode(forStatement.initializer);
}
return spanInInitializerOfForLike(forStatement);
}
if (forStatement.condition) {
@@ -406,6 +517,45 @@ namespace ts.BreakpointResolver {
}
}
function spanInBindingPattern(bindingPattern: BindingPattern): TextSpan {
// Set breakpoint in first binding element
let firstBindingElement = forEach(bindingPattern.elements,
element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);
if (firstBindingElement) {
return spanInNode(firstBindingElement);
}
// Empty binding pattern of binding element, set breakpoint on binding element
if (bindingPattern.parent.kind === SyntaxKind.BindingElement) {
return textSpan(bindingPattern.parent);
}
// Variable declaration is used as the span
return textSpanFromVariableDeclaration(<VariableDeclaration>bindingPattern.parent);
}
function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node: DestructuringPattern): TextSpan {
Debug.assert(node.kind !== SyntaxKind.ArrayBindingPattern && node.kind !== SyntaxKind.ObjectBindingPattern);
const elements: NodeArray<Expression | ObjectLiteralElement> =
node.kind === SyntaxKind.ArrayLiteralExpression ?
(<ArrayLiteralExpression>node).elements :
(<ObjectLiteralExpression>node).properties;
const firstBindingElement = forEach(elements,
element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);
if (firstBindingElement) {
return spanInNode(firstBindingElement);
}
// Could be ArrayLiteral from destructuring assignment or
// just nested element in another destructuring assignment
// set breakpoint on assignment when parent is destructuring assignment
// Otherwise set breakpoint for this element
return textSpan(node.parent.kind === SyntaxKind.BinaryExpression ? node.parent : node);
}
// Tokens:
function spanInOpenBraceToken(node: Node): TextSpan {
switch (node.parent.kind) {
@@ -457,18 +607,52 @@ namespace ts.BreakpointResolver {
}
return undefined;
case SyntaxKind.ObjectBindingPattern:
// Breakpoint in last binding element or binding pattern if it contains no elements
let bindingPattern = <BindingPattern>node.parent;
return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern);
// Default to parent node
default:
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Breakpoint in last binding element or binding pattern if it contains no elements
let objectLiteral = <ObjectLiteralExpression>node.parent;
return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral);
}
return spanInNode(node.parent);
}
}
function spanInCloseBracketToken(node: Node): TextSpan {
switch (node.parent.kind) {
case SyntaxKind.ArrayBindingPattern:
// Breakpoint in last binding element or binding pattern if it contains no elements
let bindingPattern = <BindingPattern>node.parent;
return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern);
default:
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Breakpoint in last binding element or binding pattern if it contains no elements
let arrayLiteral = <ArrayLiteralExpression>node.parent;
return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
}
// Default to parent node
return spanInNode(node.parent);
}
}
function spanInOpenParenToken(node: Node): TextSpan {
if (node.parent.kind === SyntaxKind.DoStatement) {
// Go to while keyword and do action instead
if (node.parent.kind === SyntaxKind.DoStatement || // Go to while keyword and do action instead
node.parent.kind === SyntaxKind.CallExpression ||
node.parent.kind === SyntaxKind.NewExpression) {
return spanInPreviousNode(node);
}
if (node.parent.kind === SyntaxKind.ParenthesizedExpression) {
return spanInNextNode(node);
}
// Default to parent node
return spanInNode(node.parent);
}
@@ -487,6 +671,10 @@ namespace ts.BreakpointResolver {
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ParenthesizedExpression:
return spanInPreviousNode(node);
// Default to parent node
@@ -497,7 +685,9 @@ namespace ts.BreakpointResolver {
function spanInColonToken(node: Node): TextSpan {
// Is this : specifying return annotation of the function declaration
if (isFunctionLike(node.parent) || node.parent.kind === SyntaxKind.PropertyAssignment) {
if (isFunctionLike(node.parent) ||
node.parent.kind === SyntaxKind.PropertyAssignment ||
node.parent.kind === SyntaxKind.Parameter) {
return spanInPreviousNode(node);
}
@@ -506,7 +696,7 @@ namespace ts.BreakpointResolver {
function spanInGreaterThanOrLessThanToken(node: Node): TextSpan {
if (node.parent.kind === SyntaxKind.TypeAssertionExpression) {
return spanInNode((<TypeAssertion>node.parent).expression);
return spanInNextNode(node);
}
return spanInNode(node.parent);
@@ -515,7 +705,17 @@ namespace ts.BreakpointResolver {
function spanInWhileKeyword(node: Node): TextSpan {
if (node.parent.kind === SyntaxKind.DoStatement) {
// Set span on while expression
return textSpan(node, findNextToken((<DoStatement>node.parent).expression, node.parent));
return textSpanEndingAtNextToken(node, (<DoStatement>node.parent).expression);
}
// Default to parent node
return spanInNode(node.parent);
}
function spanInOfKeyword(node: Node): TextSpan {
if (node.parent.kind === SyntaxKind.ForOfStatement) {
// set using next token
return spanInNextNode(node);
}
// Default to parent node
+92 -65
View File
@@ -31,8 +31,8 @@ namespace ts.formatting {
* the first token in line so it should be indented
*/
interface DynamicIndentation {
getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind): number;
getIndentationForComment(owningToken: SyntaxKind, tokenIndentation: number): number;
getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind, container: Node): number;
getIndentationForComment(owningToken: SyntaxKind, tokenIndentation: number, container: Node): number;
/**
* Indentation for open and close tokens of the node if it is block or another node that needs special indentation
* ... {
@@ -54,7 +54,7 @@ namespace ts.formatting {
* so bar inherits indentation from foo and bar.delta will be 4
*
*/
getDelta(): number;
getDelta(child: TextRangeWithKind): number;
/**
* Formatter calls this function when rule adds or deletes new lines from the text
* so indentation scope can adjust values of indentation and delta.
@@ -72,12 +72,20 @@ namespace ts.formatting {
if (line === 0) {
return [];
}
// get the span for the previous\current line
// After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
// If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
// trailing whitespaces. So the end of the formatting span should be the later one between:
// 1. the end of the previous line
// 2. the last non-whitespace character in the current line
let endOfFormatSpan = getEndLinePosition(line, sourceFile);
while (isWhiteSpace(sourceFile.text.charCodeAt(endOfFormatSpan)) && !isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
let span = {
// get start position for the previous line
pos: getStartPositionOfLine(line - 1, sourceFile),
// get end position for the current line (end value is exclusive so add 1 to the result)
end: getEndLinePosition(line, sourceFile) + 1
// end value is exclusive so add 1 to the result
end: endOfFormatSpan + 1
}
return formatSpan(span, sourceFile, options, rulesProvider, FormattingRequestKind.FormatOnEnter);
}
@@ -121,7 +129,7 @@ namespace ts.formatting {
function findOutermostParent(position: number, expectedTokenKind: SyntaxKind, sourceFile: SourceFile): Node {
let precedingToken = findPrecedingToken(position, sourceFile);
// when it is claimed that trigger character was typed at given position
// we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed).
// If this condition is not hold - then trigger character was typed in some other context,
@@ -151,7 +159,7 @@ namespace ts.formatting {
return current;
}
// Returns true if node is a element in some list in parent
// i.e. parent is class declaration with the list of members and node is one of members.
function isListElement(parent: Node, node: Node): boolean {
@@ -198,7 +206,7 @@ namespace ts.formatting {
if (!errors.length) {
return rangeHasNoErrors;
}
// pick only errors that fall in range
let sorted = errors
.filter(d => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length))
@@ -256,7 +264,7 @@ namespace ts.formatting {
return enclosingNode.pos;
}
// preceding token ends after the start of original range (i.e when originaRange.pos falls in the middle of literal)
// preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal)
// start from the beginning of enclosingNode to handle the entire 'originalRange'
if (precedingToken.end >= originalRange.pos) {
return enclosingNode.pos;
@@ -282,19 +290,19 @@ namespace ts.formatting {
*/
function getOwnOrInheritedDelta(n: Node, options: FormatCodeOptions, sourceFile: SourceFile): number {
let previousLine = Constants.Unknown;
let childKind = SyntaxKind.Unknown;
let child: Node;
while (n) {
let line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
if (previousLine !== Constants.Unknown && line !== previousLine) {
break;
}
if (SmartIndenter.shouldIndentChildNode(n.kind, childKind)) {
if (SmartIndenter.shouldIndentChildNode(n, child)) {
return options.IndentSize;
}
previousLine = line;
childKind = n.kind;
child = n;
n = n.parent;
}
return 0;
@@ -341,6 +349,14 @@ namespace ts.formatting {
processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
}
if (!formattingScanner.isOnToken()) {
let leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
if (leadingTrivia) {
processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined);
trimTrailingWhitespacesForRemainingRange();
}
}
formattingScanner.close();
return edits;
@@ -360,7 +376,9 @@ namespace ts.formatting {
range: TextRange,
inheritedIndentation: number): number {
if (rangeOverlapsWithStartEnd(range, startPos, endPos)) {
if (rangeOverlapsWithStartEnd(range, startPos, endPos) ||
rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
if (inheritedIndentation !== Constants.Unknown) {
return inheritedIndentation;
}
@@ -386,34 +404,7 @@ namespace ts.formatting {
effectiveParentStartLine: number): Indentation {
let indentation = inheritedIndentation;
if (indentation === Constants.Unknown) {
if (isSomeBlock(node.kind)) {
// blocks should be indented in
// - other blocks
// - source file
// - switch\default clauses
if (isSomeBlock(parent.kind) ||
parent.kind === SyntaxKind.SourceFile ||
parent.kind === SyntaxKind.CaseClause ||
parent.kind === SyntaxKind.DefaultClause) {
indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta();
}
else {
indentation = parentDynamicIndentation.getIndentation();
}
}
else {
if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
indentation = parentDynamicIndentation.getIndentation();
}
else {
indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta();
}
}
}
var delta = SmartIndenter.shouldIndentChildNode(node.kind, SyntaxKind.Unknown) ? options.IndentSize : 0;
var delta = SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
// if node is located on the same line with the parent
@@ -422,8 +413,17 @@ namespace ts.formatting {
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta);
delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta);
}
else if (indentation === Constants.Unknown) {
if (SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) {
indentation = parentDynamicIndentation.getIndentation();
}
else {
indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node);
}
}
return {
indentation,
delta
@@ -455,7 +455,7 @@ namespace ts.formatting {
function getDynamicIndentation(node: Node, nodeStartLine: number, indentation: number, delta: number): DynamicIndentation {
return {
getIndentationForComment: (kind, tokenIndentation) => {
getIndentationForComment: (kind, tokenIndentation, container) => {
switch (kind) {
// preceding comment to the token that closes the indentation scope inherits the indentation from the scope
// .. {
@@ -464,11 +464,11 @@ namespace ts.formatting {
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.CloseParenToken:
return indentation + delta;
return indentation + getEffectiveDelta(delta, container);
}
return tokenIndentation !== Constants.Unknown ? tokenIndentation : indentation;
},
getIndentationForToken: (line, kind) => {
getIndentationForToken: (line, kind, container) => {
if (nodeStartLine !== line && node.decorators) {
if (kind === getFirstNonDecoratorTokenOfNode(node)) {
// if this token is the first token following the list of decorators, we do not need to indent
@@ -489,13 +489,13 @@ namespace ts.formatting {
return indentation;
default:
// if token line equals to the line of containing node (this is a first token in the node) - use node indentation
return nodeStartLine !== line ? indentation + delta : indentation;
return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation;
}
},
getIndentation: () => indentation,
getDelta: () => delta,
getDelta: child => getEffectiveDelta(delta, child),
recomputeIndentation: lineAdded => {
if (node.parent && SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) {
if (node.parent && SmartIndenter.shouldIndentChildNode(node.parent, node)) {
if (lineAdded) {
indentation += options.IndentSize;
}
@@ -503,14 +503,19 @@ namespace ts.formatting {
indentation -= options.IndentSize;
}
if (SmartIndenter.shouldIndentChildNode(node.kind, SyntaxKind.Unknown)) {
if (SmartIndenter.shouldIndentChildNode(node)) {
delta = options.IndentSize;
}
else {
delta = 0;
}
}
},
}
}
function getEffectiveDelta(delta: number, child: TextRangeWithKind) {
// Delta value should be zero when the node explicitly prevents indentation of the child node
return SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0;
}
}
@@ -610,7 +615,7 @@ namespace ts.formatting {
// if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
let tokenInfo = formattingScanner.readTokenInfo(child);
Debug.assert(tokenInfo.token.end === child.end);
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation);
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
return inheritedIndentation;
}
@@ -679,7 +684,7 @@ namespace ts.formatting {
}
}
function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation): void {
function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container?: Node): void {
Debug.assert(rangeContainsRange(parent, currentTokenInfo.token));
let lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
@@ -720,11 +725,11 @@ namespace ts.formatting {
if (indentToken) {
let tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) :
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) :
Constants.Unknown;
if (currentTokenInfo.leadingTrivia) {
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation);
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
let indentNextTokenOrTrivia = true;
for (let triviaItem of currentTokenInfo.leadingTrivia) {
@@ -839,9 +844,7 @@ namespace ts.formatting {
}
// We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line
trimTrailingWhitespaces =
(rule.Operation.Action & (RuleAction.NewLine | RuleAction.Space)) &&
rule.Flag !== RuleFlags.CanDeleteNewLines;
trimTrailingWhitespaces = !(rule.Operation.Action & RuleAction.Delete) && rule.Flag !== RuleFlags.CanDeleteNewLines;
}
else {
trimTrailingWhitespaces = true;
@@ -940,17 +943,41 @@ namespace ts.formatting {
continue;
}
let pos = lineEndPosition;
while (pos >= lineStartPosition && isWhiteSpace(sourceFile.text.charCodeAt(pos))) {
pos--;
}
if (pos !== lineEndPosition) {
Debug.assert(pos === lineStartPosition || !isWhiteSpace(sourceFile.text.charCodeAt(pos)));
recordDelete(pos + 1, lineEndPosition - pos);
let whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
if (whitespaceStart !== -1) {
Debug.assert(whitespaceStart === lineStartPosition || !isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1)));
recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
}
}
}
/**
* @param start The position of the first character in range
* @param end The position of the last character in range
*/
function getTrailingWhitespaceStartPosition(start: number, end: number) {
let pos = end;
while (pos >= start && isWhiteSpace(sourceFile.text.charCodeAt(pos))) {
pos--;
}
if (pos !== end) {
return pos + 1;
}
return -1;
}
/**
* Trimming will be done for lines after the previous range
*/
function trimTrailingWhitespacesForRemainingRange() {
let startPosition = previousRange ? previousRange.end : originalRange.pos;
let startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
let endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange);
}
function newTextChange(start: number, len: number, newText: string): TextChange {
return { span: createTextSpan(start, len), newText }
}
+22 -20
View File
@@ -5,21 +5,22 @@
namespace ts.formatting {
const standardScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, LanguageVariant.Standard);
const jsxScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, LanguageVariant.JSX);
/**
* Scanner that is currently used for formatting
*/
let scanner: Scanner;
export interface FormattingScanner {
advance(): void;
isOnToken(): boolean;
readTokenInfo(n: Node): TokenInfo;
getCurrentLeadingTrivia(): TextRangeWithKind[];
lastTrailingTriviaWasNewLine(): boolean;
close(): void;
}
const enum ScanAction{
const enum ScanAction {
Scan,
RescanGreaterThanToken,
RescanSlashToken,
@@ -37,19 +38,20 @@ namespace ts.formatting {
let wasNewLine: boolean = true;
let leadingTrivia: TextRangeWithKind[];
let trailingTrivia: TextRangeWithKind[];
let savedPos: number;
let lastScanAction: ScanAction;
let lastTokenInfo: TokenInfo;
return {
advance: advance,
readTokenInfo: readTokenInfo,
isOnToken: isOnToken,
advance,
readTokenInfo,
isOnToken,
getCurrentLeadingTrivia: () => leadingTrivia,
lastTrailingTriviaWasNewLine: () => wasNewLine,
close: () => {
Debug.assert(scanner !== undefined);
lastTokenInfo = undefined;
scanner.setText(undefined);
scanner = undefined;
@@ -58,7 +60,7 @@ namespace ts.formatting {
function advance(): void {
Debug.assert(scanner !== undefined);
lastTokenInfo = undefined;
let isStarted = scanner.getStartPos() !== startPos;
@@ -81,7 +83,7 @@ namespace ts.formatting {
let t: SyntaxKind;
let pos = scanner.getStartPos();
// Read leading trivia and token
while (pos < endPos) {
let t = scanner.getToken();
@@ -122,10 +124,10 @@ namespace ts.formatting {
return false;
}
function shouldRescanJsxIdentifier(node: Node): boolean {
if (node.parent) {
switch(node.parent.kind) {
switch (node.parent.kind) {
case SyntaxKind.JsxAttribute:
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxClosingElement:
@@ -133,7 +135,7 @@ namespace ts.formatting {
return node.kind === SyntaxKind.Identifier;
}
}
return false;
}
@@ -142,7 +144,7 @@ namespace ts.formatting {
}
function shouldRescanTemplateToken(container: Node): boolean {
return container.kind === SyntaxKind.TemplateMiddle ||
return container.kind === SyntaxKind.TemplateMiddle ||
container.kind === SyntaxKind.TemplateTail;
}
@@ -152,11 +154,11 @@ namespace ts.formatting {
function readTokenInfo(n: Node): TokenInfo {
Debug.assert(scanner !== undefined);
if (!isOnToken()) {
// scanner is not on the token (either advance was not called yet or scanner is already past the end position)
return {
leadingTrivia: leadingTrivia,
leadingTrivia,
trailingTrivia: undefined,
token: undefined
};
@@ -164,7 +166,7 @@ namespace ts.formatting {
// normally scanner returns the smallest available token
// check the kind of context node to determine if scanner should have more greedy behavior and consume more text.
let expectedScanAction =
let expectedScanAction =
shouldRescanGreaterThanToken(n)
? ScanAction.RescanGreaterThanToken
: shouldRescanSlashToken(n)
@@ -179,7 +181,7 @@ namespace ts.formatting {
// readTokenInfo was called before with the same expected scan action.
// No need to re-scan text, return existing 'lastTokenInfo'
// it is ok to call fixTokenKind here since it does not affect
// what portion of text is consumed. In opposize rescanning can change it,
// what portion of text is consumed. In contrast rescanning can change it,
// i.e. for '>=' when originally scanner eats just one character
// and rescanning forces it to consume more.
return fixTokenKind(lastTokenInfo, n);
@@ -226,7 +228,7 @@ namespace ts.formatting {
if (trailingTrivia) {
trailingTrivia = undefined;
}
while(scanner.getStartPos() < endPos) {
while (scanner.getStartPos() < endPos) {
currentToken = scanner.scan();
if (!isTrivia(currentToken)) {
break;
@@ -261,7 +263,7 @@ namespace ts.formatting {
function isOnToken(): boolean {
Debug.assert(scanner !== undefined);
let current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken();
let startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos();
return startPos < endPos && current !== SyntaxKind.EndOfFileToken && !isTrivia(current);
+101 -91
View File
@@ -123,6 +123,7 @@ namespace ts.formatting {
public SpaceAfterModuleName: Rule;
// Lambda expressions
public SpaceBeforeArrow: Rule;
public SpaceAfterArrow: Rule;
// Optional parameters and let args
@@ -218,9 +219,11 @@ namespace ts.formatting {
public SpaceBetweenAsyncAndFunctionKeyword: Rule;
// Template strings
public SpaceBetweenTagAndTemplateString: Rule;
public NoSpaceBetweenTagAndTemplateString: Rule;
public NoSpaceAfterTemplateHeadAndMiddle: Rule;
public SpaceAfterTemplateHeadAndMiddle: Rule;
public NoSpaceBeforeTemplateMiddleAndTail: Rule;
public SpaceBeforeTemplateMiddleAndTail: Rule;
constructor() {
///
@@ -232,29 +235,29 @@ namespace ts.formatting {
this.IgnoreAfterLineComment = new Rule(RuleDescriptor.create3(SyntaxKind.SingleLineCommentTrivia, Shared.TokenRange.Any), RuleOperation.create1(RuleAction.Ignore));
// Space after keyword but not before ; or : or ?
this.NoSpaceBeforeSemicolon = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.SemicolonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeColon = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.ColonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.NoSpaceBeforeQuestionMark = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.QuestionToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.SpaceAfterColon = new Rule(RuleDescriptor.create3(SyntaxKind.ColonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Space));
this.SpaceAfterQuestionMarkInConditionalOperator = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsConditionalOperatorContext), RuleAction.Space));
this.NoSpaceAfterQuestionMark = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterSemicolon = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBeforeSemicolon = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.SemicolonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeColon = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.ColonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.NoSpaceBeforeQuestionMark = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.QuestionToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.SpaceAfterColon = new Rule(RuleDescriptor.create3(SyntaxKind.ColonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Space));
this.SpaceAfterQuestionMarkInConditionalOperator = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsConditionalOperatorContext), RuleAction.Space));
this.NoSpaceAfterQuestionMark = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterSemicolon = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
// Space after }.
this.SpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), RuleAction.Space));
this.SpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsAfterCodeBlockContext), RuleAction.Space));
// Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied
this.SpaceBetweenCloseBraceAndElse = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.ElseKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBetweenCloseBraceAndWhile = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.WhileKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken, SyntaxKind.SemicolonToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceBetweenCloseBraceAndElse = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.ElseKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceBetweenCloseBraceAndWhile = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.WhileKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken, SyntaxKind.SemicolonToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// No space for dot
this.NoSpaceBeforeDot = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.DotToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterDot = new Rule(RuleDescriptor.create3(SyntaxKind.DotToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeDot = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.DotToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterDot = new Rule(RuleDescriptor.create3(SyntaxKind.DotToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// No space before and after indexer
this.NoSpaceBeforeOpenBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext ), RuleAction.Delete));
this.NoSpaceBeforeOpenBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), RuleAction.Delete));
// Place a space before open brace in a function declaration
this.FunctionOpenBraceLeftTokenRange = Shared.TokenRange.AnyIncludingMultilineComments;
@@ -271,7 +274,7 @@ namespace ts.formatting {
// Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
this.SpaceAfterOpenBrace = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSingleLineBlockContext), RuleAction.Space));
this.SpaceBeforeCloseBrace = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSingleLineBlockContext), RuleAction.Space));
this.NoSpaceBetweenEmptyBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), RuleAction.Delete));
this.NoSpaceBetweenEmptyBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectContext), RuleAction.Delete));
// Insert new line after { and before } in multi-line contexts.
this.NewLineAfterOpenBraceInBlockContext = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBraceToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsMultilineBlockContext), RuleAction.NewLine));
@@ -282,105 +285,103 @@ namespace ts.formatting {
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
this.NoSpaceAfterUnaryPrefixOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.UnaryPrefixOperators, Shared.TokenRange.UnaryPrefixExpressions), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.NoSpaceAfterUnaryPreincrementOperator = new Rule(RuleDescriptor.create3(SyntaxKind.PlusPlusToken, Shared.TokenRange.UnaryPreincrementExpressions), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterUnaryPredecrementOperator = new Rule(RuleDescriptor.create3(SyntaxKind.MinusMinusToken, Shared.TokenRange.UnaryPredecrementExpressions), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeUnaryPostincrementOperator = new Rule(RuleDescriptor.create2(Shared.TokenRange.UnaryPostincrementExpressions, SyntaxKind.PlusPlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeUnaryPostdecrementOperator = new Rule(RuleDescriptor.create2(Shared.TokenRange.UnaryPostdecrementExpressions, SyntaxKind.MinusMinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterUnaryPrefixOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.UnaryPrefixOperators, Shared.TokenRange.UnaryPrefixExpressions), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.NoSpaceAfterUnaryPreincrementOperator = new Rule(RuleDescriptor.create3(SyntaxKind.PlusPlusToken, Shared.TokenRange.UnaryPreincrementExpressions), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterUnaryPredecrementOperator = new Rule(RuleDescriptor.create3(SyntaxKind.MinusMinusToken, Shared.TokenRange.UnaryPredecrementExpressions), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeUnaryPostincrementOperator = new Rule(RuleDescriptor.create2(Shared.TokenRange.UnaryPostincrementExpressions, SyntaxKind.PlusPlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeUnaryPostdecrementOperator = new Rule(RuleDescriptor.create2(Shared.TokenRange.UnaryPostdecrementExpressions, SyntaxKind.MinusMinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// More unary operator special-casing.
// DevDiv 181814: Be careful when removing leading whitespace
// around unary operators. Examples:
// 1 - -2 --X--> 1--2
// a + ++b --X--> a+++b
this.SpaceAfterPostincrementWhenFollowedByAdd = new Rule(RuleDescriptor.create1(SyntaxKind.PlusPlusToken, SyntaxKind.PlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterAddWhenFollowedByUnaryPlus = new Rule(RuleDescriptor.create1(SyntaxKind.PlusToken, SyntaxKind.PlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterAddWhenFollowedByPreincrement = new Rule(RuleDescriptor.create1(SyntaxKind.PlusToken, SyntaxKind.PlusPlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterPostdecrementWhenFollowedBySubtract = new Rule(RuleDescriptor.create1(SyntaxKind.MinusMinusToken, SyntaxKind.MinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new Rule(RuleDescriptor.create1(SyntaxKind.MinusToken, SyntaxKind.MinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterSubtractWhenFollowedByPredecrement = new Rule(RuleDescriptor.create1(SyntaxKind.MinusToken, SyntaxKind.MinusMinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterPostincrementWhenFollowedByAdd = new Rule(RuleDescriptor.create1(SyntaxKind.PlusPlusToken, SyntaxKind.PlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterAddWhenFollowedByUnaryPlus = new Rule(RuleDescriptor.create1(SyntaxKind.PlusToken, SyntaxKind.PlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterAddWhenFollowedByPreincrement = new Rule(RuleDescriptor.create1(SyntaxKind.PlusToken, SyntaxKind.PlusPlusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterPostdecrementWhenFollowedBySubtract = new Rule(RuleDescriptor.create1(SyntaxKind.MinusMinusToken, SyntaxKind.MinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new Rule(RuleDescriptor.create1(SyntaxKind.MinusToken, SyntaxKind.MinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterSubtractWhenFollowedByPredecrement = new Rule(RuleDescriptor.create1(SyntaxKind.MinusToken, SyntaxKind.MinusMinusToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.NoSpaceBeforeComma = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CommaToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeComma = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CommaToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterCertainKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.VarKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.NewKeyword, SyntaxKind.DeleteKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.AwaitKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterLetConstInVariableDeclaration = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.LetKeyword, SyntaxKind.ConstKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), RuleAction.Space));
this.NoSpaceBeforeOpenParenInFuncCall = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), RuleAction.Delete));
this.SpaceAfterCertainKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.VarKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.NewKeyword, SyntaxKind.DeleteKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.AwaitKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceAfterLetConstInVariableDeclaration = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.LetKeyword, SyntaxKind.ConstKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), RuleAction.Space));
this.NoSpaceBeforeOpenParenInFuncCall = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), RuleAction.Delete));
this.SpaceAfterFunctionInFuncDecl = new Rule(RuleDescriptor.create3(SyntaxKind.FunctionKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space));
this.NoSpaceBeforeOpenParenInFuncDecl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), RuleAction.Delete));
this.SpaceAfterVoidOperator = new Rule(RuleDescriptor.create3(SyntaxKind.VoidKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), RuleAction.Space));
this.NoSpaceBeforeOpenParenInFuncDecl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsFunctionDeclContext), RuleAction.Delete));
this.SpaceAfterVoidOperator = new Rule(RuleDescriptor.create3(SyntaxKind.VoidKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsVoidOpContext), RuleAction.Space));
this.NoSpaceBetweenReturnAndSemicolon = new Rule(RuleDescriptor.create1(SyntaxKind.ReturnKeyword, SyntaxKind.SemicolonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBetweenReturnAndSemicolon = new Rule(RuleDescriptor.create1(SyntaxKind.ReturnKeyword, SyntaxKind.SemicolonToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// Add a space between statements. All keywords except (do,else,case) has open/close parens after them.
// So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any]
this.SpaceBetweenStatements = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.DoKeyword, SyntaxKind.ElseKeyword, SyntaxKind.CaseKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), RuleAction.Space));
this.SpaceBetweenStatements = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.DoKeyword, SyntaxKind.ElseKeyword, SyntaxKind.CaseKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotForContext), RuleAction.Space));
// This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter.
this.SpaceAfterTryFinally = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.TryKeyword, SyntaxKind.FinallyKeyword]), SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterTryFinally = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.TryKeyword, SyntaxKind.FinallyKeyword]), SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
// get x() {}
// set x(val) {}
this.SpaceAfterGetSetInMember = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.GetKeyword, SyntaxKind.SetKeyword]), SyntaxKind.Identifier), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space));
// Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options.
this.SpaceBeforeBinaryKeywordOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.BinaryKeywordOperators), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterBinaryKeywordOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.BinaryKeywordOperators, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceBeforeBinaryKeywordOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.BinaryKeywordOperators), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterBinaryKeywordOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.BinaryKeywordOperators, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
// TypeScript-specific higher priority rules
// Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses
this.NoSpaceAfterConstructor = new Rule(RuleDescriptor.create1(SyntaxKind.ConstructorKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterConstructor = new Rule(RuleDescriptor.create1(SyntaxKind.ConstructorKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// Use of module as a function call. e.g.: import m2 = module("m2");
this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// Add a space around certain TypeScript keywords
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword, SyntaxKind.TypeKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword, SyntaxKind.TypeKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
// Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
this.SpaceAfterModuleName = new Rule(RuleDescriptor.create1(SyntaxKind.StringLiteral, SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsModuleDeclContext), RuleAction.Space));
// Lambda expressions
this.SpaceAfterArrow = new Rule(RuleDescriptor.create3(SyntaxKind.EqualsGreaterThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeArrow = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.EqualsGreaterThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceAfterArrow = new Rule(RuleDescriptor.create3(SyntaxKind.EqualsGreaterThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
// Optional parameters and let args
this.NoSpaceAfterEllipsis = new Rule(RuleDescriptor.create1(SyntaxKind.DotDotDotToken, SyntaxKind.Identifier), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOptionalParameters = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
this.NoSpaceAfterEllipsis = new Rule(RuleDescriptor.create1(SyntaxKind.DotDotDotToken, SyntaxKind.Identifier), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOptionalParameters = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
// generics and type assertions
this.NoSpaceBeforeOpenAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.TypeNames, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceBetweenCloseParenAndAngularBracket = new Rule(RuleDescriptor.create1(SyntaxKind.CloseParenToken, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterOpenAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.LessThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceBeforeCloseAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.GreaterThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterCloseAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.FromTokens([SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.GreaterThanToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterTypeAssertion = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), RuleAction.Delete));
this.NoSpaceBeforeOpenAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.TypeNames, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceBetweenCloseParenAndAngularBracket = new Rule(RuleDescriptor.create1(SyntaxKind.CloseParenToken, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterOpenAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.LessThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceBeforeCloseAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.GreaterThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterCloseAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.FromTokens([SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.GreaterThanToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterTypeAssertion = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsTypeAssertionContext), RuleAction.Delete));
// Remove spaces in empty interface literals. e.g.: x: {}
this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), RuleAction.Delete));
this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsObjectTypeContext), RuleAction.Delete));
// decorators
this.SpaceBeforeAt = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.AtToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterAt = new Rule(RuleDescriptor.create3(SyntaxKind.AtToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceBeforeAt = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.AtToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterAt = new Rule(RuleDescriptor.create3(SyntaxKind.AtToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterDecorator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.Identifier, SyntaxKind.ExportKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.ClassKeyword, SyntaxKind.StaticKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.GetKeyword, SyntaxKind.SetKeyword, SyntaxKind.OpenBracketToken, SyntaxKind.AsteriskToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), RuleAction.Space));
this.NoSpaceBetweenFunctionKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.FunctionKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), RuleAction.Delete));
this.SpaceAfterStarInGeneratorDeclaration = new Rule(RuleDescriptor.create3(SyntaxKind.AsteriskToken, Shared.TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), RuleAction.Space));
this.NoSpaceBetweenYieldKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Delete));
this.SpaceBetweenYieldOrYieldStarAndOperand = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Space));
this.NoSpaceBetweenYieldKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Delete));
this.SpaceBetweenYieldOrYieldStarAndOperand = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Space));
// Async-await
this.SpaceBetweenAsyncAndOpenParen = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBetweenAsyncAndFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.FunctionKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBetweenAsyncAndOpenParen = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceBetweenAsyncAndFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.FunctionKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
// template string
this.SpaceBetweenTagAndTemplateString = new Rule(RuleDescriptor.create3(SyntaxKind.Identifier, Shared.TokenRange.FromTokens([SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TemplateHead])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterTemplateHeadAndMiddle = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.TemplateHead, SyntaxKind.TemplateMiddle]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeTemplateMiddleAndTail = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.TemplateMiddle, SyntaxKind.TemplateTail])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBetweenTagAndTemplateString = new Rule(RuleDescriptor.create3(SyntaxKind.Identifier, Shared.TokenRange.FromTokens([SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TemplateHead])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// These rules are higher in priority than user-configurable rules.
this.HighPriorityCommonRules =
[
this.HighPriorityCommonRules = [
this.IgnoreBeforeComment, this.IgnoreAfterLineComment,
this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator,
this.NoSpaceAfterQuestionMark,
@@ -405,13 +406,13 @@ namespace ts.formatting {
this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator,
this.SpaceAfterVoidOperator,
this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword,
this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail,
this.NoSpaceBetweenTagAndTemplateString,
// TypeScript-specific rules
this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport,
this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords,
this.SpaceAfterModuleName,
this.SpaceAfterArrow,
this.SpaceBeforeArrow, this.SpaceAfterArrow,
this.NoSpaceAfterEllipsis,
this.NoSpaceAfterOptionalParameters,
this.NoSpaceBetweenEmptyInterfaceBraceBrackets,
@@ -427,8 +428,7 @@ namespace ts.formatting {
];
// These rules are lower in priority than user-configurable rules.
this.LowPriorityCommonRules =
[
this.LowPriorityCommonRules = [
this.NoSpaceBeforeSemicolon,
this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock,
this.NoSpaceBeforeComma,
@@ -444,14 +444,14 @@ namespace ts.formatting {
///
// Insert space after comma delimiter
this.SpaceAfterComma = new Rule(RuleDescriptor.create3(SyntaxKind.CommaToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterComma = new Rule(RuleDescriptor.create3(SyntaxKind.CommaToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterComma = new Rule(RuleDescriptor.create3(SyntaxKind.CommaToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNextTokenNotCloseBracket), RuleAction.Space));
this.NoSpaceAfterComma = new Rule(RuleDescriptor.create3(SyntaxKind.CommaToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// Insert space before and after binary operators
this.SpaceBeforeBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.BinaryOperators), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.BinaryOperators, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.NoSpaceBeforeBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.BinaryOperators), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Delete));
this.NoSpaceAfterBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.BinaryOperators, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Delete));
this.SpaceBeforeBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.BinaryOperators), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.SpaceAfterBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.BinaryOperators, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Space));
this.NoSpaceBeforeBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.BinaryOperators), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Delete));
this.NoSpaceAfterBinaryOperator = new Rule(RuleDescriptor.create4(Shared.TokenRange.BinaryOperators, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsBinaryOpContext), RuleAction.Delete));
// Insert space after keywords in control flow statements
this.SpaceAfterKeywordInControl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Keywords, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsControlDeclContext), RuleAction.Space));
@@ -468,22 +468,28 @@ namespace ts.formatting {
this.NewLineBeforeOpenBraceInControl = new Rule(RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), RuleAction.NewLine), RuleFlags.CanDeleteNewLines);
// Insert space after semicolon in for statement
this.SpaceAfterSemicolonInFor = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), RuleAction.Space));
this.NoSpaceAfterSemicolonInFor = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), RuleAction.Delete));
this.SpaceAfterSemicolonInFor = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), RuleAction.Space));
this.NoSpaceAfterSemicolonInFor = new Rule(RuleDescriptor.create3(SyntaxKind.SemicolonToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsForContext), RuleAction.Delete));
// Insert space after opening and before closing nonempty parenthesis
this.SpaceAfterOpenParen = new Rule(RuleDescriptor.create3(SyntaxKind.OpenParenToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCloseParen = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenParens = new Rule(RuleDescriptor.create1(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOpenParen = new Rule(RuleDescriptor.create3(SyntaxKind.OpenParenToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseParen = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterOpenParen = new Rule(RuleDescriptor.create3(SyntaxKind.OpenParenToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCloseParen = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenParens = new Rule(RuleDescriptor.create1(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOpenParen = new Rule(RuleDescriptor.create3(SyntaxKind.OpenParenToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseParen = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// Insert space after opening and before closing nonempty brackets
this.SpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
// Insert space after opening and before closing template string braces
this.NoSpaceAfterTemplateHeadAndMiddle = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.TemplateHead, SyntaxKind.TemplateMiddle]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterTemplateHeadAndMiddle = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.TemplateHead, SyntaxKind.TemplateMiddle]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
this.NoSpaceBeforeTemplateMiddleAndTail = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.TemplateMiddle, SyntaxKind.TemplateTail])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Delete));
this.SpaceBeforeTemplateMiddleAndTail = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.TemplateMiddle, SyntaxKind.TemplateTail])), RuleOperation.create2(new RuleOperationContext(Rules.IsNonJsxSameLineTokenContext), RuleAction.Space));
// Insert space after function keyword for anonymous functions
this.SpaceAfterAnonymousFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.FunctionKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space));
@@ -555,13 +561,13 @@ namespace ts.formatting {
//// Ex:
//// if (1)
//// { ... }
//// * ) and { are on differnet lines. We only need to format if the block is multiline context. So in this case we don't format.
//// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we don't format.
////
//// Ex:
//// if (1)
//// { ...
//// }
//// * ) and { are on differnet lines. We only need to format if the block is multiline context. So in this case we format.
//// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we format.
return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context);
}
@@ -705,12 +711,16 @@ namespace ts.formatting {
return context.currentTokenSpan.kind !== SyntaxKind.CommaToken;
}
static IsNextTokenNotCloseBracket(context: FormattingContext): boolean {
return context.nextTokenSpan.kind !== SyntaxKind.CloseBracketToken;
}
static IsArrowFunctionContext(context: FormattingContext): boolean {
return context.contextNode.kind === SyntaxKind.ArrowFunction;
}
static IsSameLineTokenContext(context: FormattingContext): boolean {
return context.TokensAreOnSameLine();
static IsNonJsxSameLineTokenContext(context: FormattingContext): boolean {
return context.TokensAreOnSameLine() && context.contextNode.kind !== SyntaxKind.JsxText;
}
static IsNotBeforeBlockInFunctionDeclarationContext(context: FormattingContext): boolean {
@@ -732,7 +742,7 @@ namespace ts.formatting {
}
static IsStartOfVariableDeclarationList(context: FormattingContext): boolean {
return context.currentTokenParent.kind === SyntaxKind.VariableDeclarationList &&
return context.currentTokenParent.kind === SyntaxKind.VariableDeclarationList &&
context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos;
}
+16 -7
View File
@@ -71,15 +71,24 @@ namespace ts.formatting {
rules.push(this.globalRules.NoSpaceBetweenParens);
}
if ( options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets ) {
rules.push( this.globalRules.SpaceAfterOpenBracket );
rules.push( this.globalRules.SpaceBeforeCloseBracket );
rules.push( this.globalRules.NoSpaceBetweenBrackets );
if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) {
rules.push(this.globalRules.SpaceAfterOpenBracket);
rules.push(this.globalRules.SpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
}
else {
rules.push( this.globalRules.NoSpaceAfterOpenBracket );
rules.push( this.globalRules.NoSpaceBeforeCloseBracket );
rules.push( this.globalRules.NoSpaceBetweenBrackets );
rules.push(this.globalRules.NoSpaceAfterOpenBracket);
rules.push(this.globalRules.NoSpaceBeforeCloseBracket);
rules.push(this.globalRules.NoSpaceBetweenBrackets);
}
if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) {
rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail);
}
else {
rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle);
rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail);
}
if (options.InsertSpaceAfterSemicolonInForStatements) {
+22 -12
View File
@@ -68,7 +68,7 @@ namespace ts.formatting {
let indentationDelta: number;
while (current) {
if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : SyntaxKind.Unknown)) {
if (positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) {
currentStart = getStartLineAndCharacterForNode(current, sourceFile);
if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) {
@@ -153,7 +153,7 @@ namespace ts.formatting {
}
// increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) {
if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) {
indentationDelta += options.IndentSize;
}
@@ -450,8 +450,9 @@ namespace ts.formatting {
case SyntaxKind.ConditionalExpression:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.JsxElement:
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxExpression:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
@@ -461,16 +462,16 @@ namespace ts.formatting {
case SyntaxKind.ParenthesizedType:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AwaitExpression:
case SyntaxKind.NamedImports:
return true;
}
return false;
}
export function shouldIndentChildNode(parent: SyntaxKind, child: SyntaxKind): boolean {
if (nodeContentIsAlwaysIndented(parent)) {
return true;
}
switch (parent) {
/* @internal */
export function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean) {
let childKind = child ? child.kind : SyntaxKind.Unknown;
switch (parent.kind) {
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForInStatement:
@@ -484,10 +485,19 @@ namespace ts.formatting {
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return child !== SyntaxKind.Block;
default:
return false;
return childKind !== SyntaxKind.Block;
case SyntaxKind.JsxElement:
return childKind !== SyntaxKind.JsxClosingElement;
}
// No explicit rule for given nodes so the result will follow the default value argument
return indentByDefault;
}
/*
Function returns true when the parent node should indent the given child by an explicit rule
*/
export function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean {
return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, false);
}
}
}
+2 -2
View File
@@ -14,7 +14,7 @@ namespace ts.formatting {
constructor(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[]) {
this.tokens = [];
for (let token = from; token <= to; token++) {
if (except.indexOf(token) < 0) {
if (ts.indexOf(except, token) < 0) {
this.tokens.push(token);
}
}
@@ -123,4 +123,4 @@ namespace ts.formatting {
static TypeNames = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]);
}
}
}
}
+227
View File
@@ -0,0 +1,227 @@
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
/// <reference path='services.ts' />
/* @internal */
namespace ts.JsTyping {
export interface TypingResolutionHost {
directoryExists: (path: string) => boolean;
fileExists: (fileName: string) => boolean;
readFile: (path: string, encoding?: string) => string;
readDirectory: (path: string, extension?: string, exclude?: string[], depth?: number) => string[];
};
interface PackageJson {
_requiredBy?: string[];
dependencies?: Map<string>;
devDependencies?: Map<string>;
name?: string;
optionalDependencies?: Map<string>;
peerDependencies?: Map<string>;
typings?: string;
};
// A map of loose file names to library names
// that we are confident require typings
let safeList: Map<string>;
/**
* @param host is the object providing I/O related operations.
* @param fileNames are the file names that belong to the same project
* @param projectRootPath is the path to the project root directory
* @param safeListPath is the path used to retrieve the safe list
* @param packageNameToTypingLocation is the map of package names to their cached typing locations
* @param typingOptions are used to customize the typing inference process
* @param compilerOptions are used as a source for typing inference
*/
export function discoverTypings(
host: TypingResolutionHost,
fileNames: string[],
projectRootPath: Path,
safeListPath: Path,
packageNameToTypingLocation: Map<string>,
typingOptions: TypingOptions,
compilerOptions: CompilerOptions):
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
// A typing name to typing file path mapping
const inferredTypings: Map<string> = {};
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
}
// Only infer typings for .js and .jsx files
fileNames = filter(map(fileNames, normalizePath), f => scriptKindIs(f, /*LanguageServiceHost*/ undefined, ScriptKind.JS, ScriptKind.JSX));
if (!safeList) {
const result = readConfigFile(safeListPath, (path: string) => host.readFile(path));
if (result.config) {
safeList = result.config;
}
else {
safeList = {};
};
}
const filesToWatch: string[] = [];
// Directories to search for package.json, bower.json and other typing information
let searchDirs: string[] = [];
let exclude: string[] = [];
mergeTypings(typingOptions.include);
exclude = typingOptions.exclude || [];
const possibleSearchDirs = map(fileNames, getDirectoryPath);
if (projectRootPath !== undefined) {
possibleSearchDirs.push(projectRootPath);
}
searchDirs = deduplicate(possibleSearchDirs);
for (const searchDir of searchDirs) {
const packageJsonPath = combinePaths(searchDir, "package.json");
getTypingNamesFromJson(packageJsonPath, filesToWatch);
const bowerJsonPath = combinePaths(searchDir, "bower.json");
getTypingNamesFromJson(bowerJsonPath, filesToWatch);
const nodeModulesPath = combinePaths(searchDir, "node_modules");
getTypingNamesFromNodeModuleFolder(nodeModulesPath);
}
getTypingNamesFromSourceFileNames(fileNames);
// Add the cached typing locations for inferred typings that are already installed
for (const name in packageNameToTypingLocation) {
if (hasProperty(inferredTypings, name) && !inferredTypings[name]) {
inferredTypings[name] = packageNameToTypingLocation[name];
}
}
// Remove typings that the user has added to the exclude list
for (const excludeTypingName of exclude) {
delete inferredTypings[excludeTypingName];
}
const newTypingNames: string[] = [];
const cachedTypingPaths: string[] = [];
for (const typing in inferredTypings) {
if (inferredTypings[typing] !== undefined) {
cachedTypingPaths.push(inferredTypings[typing]);
}
else {
newTypingNames.push(typing);
}
}
return { cachedTypingPaths, newTypingNames, filesToWatch };
/**
* Merge a given list of typingNames to the inferredTypings map
*/
function mergeTypings(typingNames: string[]) {
if (!typingNames) {
return;
}
for (const typing of typingNames) {
if (!hasProperty(inferredTypings, typing)) {
inferredTypings[typing] = undefined;
}
}
}
/**
* Get the typing info from common package manager json files like package.json or bower.json
*/
function getTypingNamesFromJson(jsonPath: string, filesToWatch: string[]) {
const result = readConfigFile(jsonPath, (path: string) => host.readFile(path));
if (result.config) {
const jsonConfig: PackageJson = result.config;
filesToWatch.push(jsonPath);
if (jsonConfig.dependencies) {
mergeTypings(getKeys(jsonConfig.dependencies));
}
if (jsonConfig.devDependencies) {
mergeTypings(getKeys(jsonConfig.devDependencies));
}
if (jsonConfig.optionalDependencies) {
mergeTypings(getKeys(jsonConfig.optionalDependencies));
}
if (jsonConfig.peerDependencies) {
mergeTypings(getKeys(jsonConfig.peerDependencies));
}
}
}
/**
* Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
* should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
* to the 'angular-route' typing name.
* @param fileNames are the names for source files in the project
*/
function getTypingNamesFromSourceFileNames(fileNames: string[]) {
const jsFileNames = filter(fileNames, hasJavaScriptFileExtension);
const inferredTypingNames = map(jsFileNames, f => removeFileExtension(getBaseFileName(f.toLowerCase())));
const cleanedTypingNames = map(inferredTypingNames, f => f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""));
if (safeList === undefined) {
mergeTypings(cleanedTypingNames);
}
else {
mergeTypings(filter(cleanedTypingNames, f => hasProperty(safeList, f)));
}
const hasJsxFile = forEach(fileNames, f => scriptKindIs(f, /*LanguageServiceHost*/ undefined, ScriptKind.JSX));
if (hasJsxFile) {
mergeTypings(["react"]);
}
}
/**
* Infer typing names from node_module folder
* @param nodeModulesPath is the path to the "node_modules" folder
*/
function getTypingNamesFromNodeModuleFolder(nodeModulesPath: string) {
// Todo: add support for ModuleResolutionHost too
if (!host.directoryExists(nodeModulesPath)) {
return;
}
const typingNames: string[] = [];
const fileNames = host.readDirectory(nodeModulesPath, "*.json", /*exclude*/ undefined, /*depth*/ 2);
for (const fileName of fileNames) {
const normalizedFileName = normalizePath(fileName);
if (getBaseFileName(normalizedFileName) !== "package.json") {
continue;
}
const result = readConfigFile(normalizedFileName, (path: string) => host.readFile(path));
if (!result.config) {
continue;
}
const packageJson: PackageJson = result.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
if (packageJson._requiredBy &&
filter(packageJson._requiredBy, (r: string) => r[0] === "#" || r === "/").length === 0) {
continue;
}
// If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
// to download d.ts files from DefinitelyTyped
if (!packageJson.name) {
continue;
}
if (packageJson.typings) {
const absolutePath = getNormalizedAbsolutePath(packageJson.typings, getDirectoryPath(normalizedFileName));
inferredTypings[packageJson.name] = absolutePath;
}
else {
typingNames.push(packageJson.name);
}
}
mergeTypings(typingNames);
}
}
}
+24 -24
View File
@@ -3,19 +3,19 @@ namespace ts.NavigateTo {
type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration };
export function getNavigateToItems(program: Program, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[] {
let patternMatcher = createPatternMatcher(searchValue);
const patternMatcher = createPatternMatcher(searchValue);
let rawItems: RawNavigateToItem[] = [];
// This means "compare in a case insensitive manner."
let baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" };
const baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" };
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
forEach(program.getSourceFiles(), sourceFile => {
cancellationToken.throwIfCancellationRequested();
let nameToDeclarations = sourceFile.getNamedDeclarations();
for (let name in nameToDeclarations) {
let declarations = getProperty(nameToDeclarations, name);
const nameToDeclarations = sourceFile.getNamedDeclarations();
for (const name in nameToDeclarations) {
const declarations = getProperty(nameToDeclarations, name);
if (declarations) {
// First do a quick check to see if the name of the declaration matches the
// last portion of the (possibly) dotted name they're searching for.
@@ -25,11 +25,11 @@ namespace ts.NavigateTo {
continue;
}
for (let declaration of declarations) {
for (const declaration of declarations) {
// It was a match! If the pattern has dots in it, then also see if the
// declaration container matches as well.
if (patternMatcher.patternContainsDots) {
let containers = getContainers(declaration);
const containers = getContainers(declaration);
if (!containers) {
return undefined;
}
@@ -41,8 +41,8 @@ namespace ts.NavigateTo {
}
}
let fileName = sourceFile.fileName;
let matchKind = bestMatchKind(matches);
const fileName = sourceFile.fileName;
const matchKind = bestMatchKind(matches);
rawItems.push({ name, fileName, matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration });
}
}
@@ -54,7 +54,7 @@ namespace ts.NavigateTo {
rawItems = rawItems.slice(0, maxResultCount);
}
let items = map(rawItems, createNavigateToItem);
const items = map(rawItems, createNavigateToItem);
return items;
@@ -62,7 +62,7 @@ namespace ts.NavigateTo {
Debug.assert(matches.length > 0);
// This is a case sensitive match, only if all the submatches were case sensitive.
for (let match of matches) {
for (const match of matches) {
if (!match.isCaseSensitive) {
return false;
}
@@ -86,16 +86,16 @@ namespace ts.NavigateTo {
function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) {
if (declaration && declaration.name) {
let text = getTextOfIdentifierOrLiteral(declaration.name);
const text = getTextOfIdentifierOrLiteral(declaration.name);
if (text !== undefined) {
containers.unshift(text);
}
else if (declaration.name.kind === SyntaxKind.ComputedPropertyName) {
return tryAddComputedPropertyName((<ComputedPropertyName>declaration.name).expression, containers, /*includeLastPortion:*/ true);
return tryAddComputedPropertyName((<ComputedPropertyName>declaration.name).expression, containers, /*includeLastPortion*/ true);
}
else {
// Don't know how to add this.
return false
return false;
}
}
@@ -106,7 +106,7 @@ namespace ts.NavigateTo {
//
// [X.Y.Z]() { }
function tryAddComputedPropertyName(expression: Expression, containers: string[], includeLastPortion: boolean): boolean {
let text = getTextOfIdentifierOrLiteral(expression);
const text = getTextOfIdentifierOrLiteral(expression);
if (text !== undefined) {
if (includeLastPortion) {
containers.unshift(text);
@@ -115,24 +115,24 @@ namespace ts.NavigateTo {
}
if (expression.kind === SyntaxKind.PropertyAccessExpression) {
let propertyAccess = <PropertyAccessExpression>expression;
const propertyAccess = <PropertyAccessExpression>expression;
if (includeLastPortion) {
containers.unshift(propertyAccess.name.text);
}
return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true);
return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true);
}
return false;
}
function getContainers(declaration: Declaration) {
let containers: string[] = [];
const containers: string[] = [];
// First, if we started with a computed property name, then add all but the last
// portion into the container array.
if (declaration.name.kind === SyntaxKind.ComputedPropertyName) {
if (!tryAddComputedPropertyName((<ComputedPropertyName>declaration.name).expression, containers, /*includeLastPortion:*/ false)) {
if (!tryAddComputedPropertyName((<ComputedPropertyName>declaration.name).expression, containers, /*includeLastPortion*/ false)) {
return undefined;
}
}
@@ -155,8 +155,8 @@ namespace ts.NavigateTo {
Debug.assert(matches.length > 0);
let bestMatchKind = PatternMatchKind.camelCase;
for (let match of matches) {
let kind = match.kind;
for (const match of matches) {
const kind = match.kind;
if (kind < bestMatchKind) {
bestMatchKind = kind;
}
@@ -171,13 +171,13 @@ namespace ts.NavigateTo {
// We first sort case insensitively. So "Aaa" will come before "bar".
// Then we sort case sensitively, so "aaa" will come before "Aaa".
return i1.matchKind - i2.matchKind ||
i1.name.localeCompare(i2.name, undefined, baseSensitivity) ||
i1.name.localeCompare(i2.name, undefined, baseSensitivity) ||
i1.name.localeCompare(i2.name);
}
function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem {
let declaration = rawItem.declaration;
let container = <Declaration>getContainerNode(declaration);
const declaration = rawItem.declaration;
const container = <Declaration>getContainerNode(declaration);
return {
name: rawItem.name,
kind: getNodeKind(declaration),
+289 -21
View File
@@ -2,7 +2,13 @@
/* @internal */
namespace ts.NavigationBar {
export function getNavigationBarItems(sourceFile: SourceFile): ts.NavigationBarItem[] {
export function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[] {
// TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify
// the 'navbar' and 'navto' logic for TypeScript and JavaScript.
if (isSourceFileJavaScript(sourceFile)) {
return getJsNavigationBarItems(sourceFile, compilerOptions);
}
// If the source file has any child items, then it included in the tree
// and takes lexical ownership of all other top-level items.
let hasGlobalNode = false;
@@ -130,7 +136,7 @@ namespace ts.NavigationBar {
return topLevelNodes;
}
function sortNodes(nodes: Node[]): Node[] {
return nodes.slice(0).sort((n1: Declaration, n2: Declaration) => {
if (n1.name && n2.name) {
@@ -147,13 +153,27 @@ namespace ts.NavigationBar {
}
});
}
function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void {
nodes = sortNodes(nodes);
for (let node of nodes) {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
topLevelNodes.push(node);
for (const member of (<ClassDeclaration>node).members) {
if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.Constructor) {
type FunctionLikeMember = MethodDeclaration | ConstructorDeclaration;
if ((<FunctionLikeMember>member).body) {
// We do not include methods that does not have child functions in it, because of duplications.
if (hasNamedFunctionDeclarations((<Block>(<FunctionLikeMember>member).body).statements)) {
topLevelNodes.push(member);
}
addTopLevelNodes((<Block>(<MethodDeclaration>member).body).statements, topLevelNodes);
}
}
}
break;
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
topLevelNodes.push(node);
@@ -176,29 +196,46 @@ namespace ts.NavigationBar {
}
}
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration) {
function hasNamedFunctionDeclarations(nodes: NodeArray<Statement>): boolean {
for (let s of nodes) {
if (s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text)) {
return true;
}
}
return false;
}
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration): boolean {
if (functionDeclaration.kind === SyntaxKind.FunctionDeclaration) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
// A function declaration is 'top level' if it contains any function declarations
// within it.
if (functionDeclaration.body && functionDeclaration.body.kind === SyntaxKind.Block) {
// Proper function declarations can only have identifier names
if (forEach((<Block>functionDeclaration.body).statements,
s => s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text))) {
if (hasNamedFunctionDeclarations((<Block>functionDeclaration.body).statements)) {
return true;
}
// Or if it is not parented by another function. i.e all functions
// at module scope are 'top level'.
// Or if it is not parented by another function. I.e all functions at module scope are 'top level'.
if (!isFunctionBlock(functionDeclaration.parent)) {
return true;
}
// Or if it is nested inside class methods and constructors.
else {
// We have made sure that a grand parent node exists with 'isFunctionBlock()' above.
const grandParentKind = functionDeclaration.parent.parent.kind;
if (grandParentKind === SyntaxKind.MethodDeclaration ||
grandParentKind === SyntaxKind.Constructor) {
return true;
}
}
}
}
return false;
}
function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] {
let items: ts.NavigationBarItem[] = [];
@@ -370,11 +407,15 @@ namespace ts.NavigationBar {
case SyntaxKind.ClassDeclaration:
return createClassItem(<ClassDeclaration>node);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.Constructor:
return createMemberFunctionLikeItem(<MethodDeclaration | ConstructorDeclaration>node);
case SyntaxKind.EnumDeclaration:
return createEnumItem(<EnumDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
return createIterfaceItem(<InterfaceDeclaration>node);
return createInterfaceItem(<InterfaceDeclaration>node);
case SyntaxKind.ModuleDeclaration:
return createModuleItem(<ModuleDeclaration>node);
@@ -387,7 +428,7 @@ namespace ts.NavigationBar {
function getModuleName(moduleDeclaration: ModuleDeclaration): string {
// We want to maintain quotation marks.
if (moduleDeclaration.name.kind === SyntaxKind.StringLiteral) {
if (isAmbientModule(moduleDeclaration)) {
return getTextOfNode(moduleDeclaration.name);
}
@@ -395,19 +436,19 @@ namespace ts.NavigationBar {
let result: string[] = [];
result.push(moduleDeclaration.name.text);
while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) {
moduleDeclaration = <ModuleDeclaration>moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
}
return result.join(".");
}
function createModuleItem(node: ModuleDeclaration): NavigationBarItem {
let moduleName = getModuleName(node);
let childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
return getNavigationBarItem(moduleName,
@@ -418,11 +459,11 @@ namespace ts.NavigationBar {
getIndent(node));
}
function createFunctionItem(node: FunctionDeclaration) {
function createFunctionItem(node: FunctionDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
return getNavigationBarItem(!node.name ? "default": node.name.text ,
return getNavigationBarItem(!node.name ? "default": node.name.text,
ts.ScriptElementKind.functionElement,
getNodeModifiers(node),
[getNodeSpan(node)],
@@ -433,6 +474,31 @@ namespace ts.NavigationBar {
return undefined;
}
function createMemberFunctionLikeItem(node: MethodDeclaration | ConstructorDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
let scriptElementKind: string;
let memberFunctionName: string;
if (node.kind === SyntaxKind.MethodDeclaration) {
memberFunctionName = getPropertyNameForPropertyNameNode(node.name);
scriptElementKind = ts.ScriptElementKind.memberFunctionElement;
}
else {
memberFunctionName = "constructor";
scriptElementKind = ts.ScriptElementKind.constructorImplementationElement;
}
return getNavigationBarItem(memberFunctionName,
scriptElementKind,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
return undefined;
}
function createSourceFileItem(node: SourceFile): ts.NavigationBarItem {
let childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
@@ -493,7 +559,7 @@ namespace ts.NavigationBar {
getIndent(node));
}
function createIterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem {
function createInterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem {
let childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
return getNavigationBarItem(
node.name.text,
@@ -534,4 +600,206 @@ namespace ts.NavigationBar {
return getTextOfNodeFromSourceText(sourceFile.text, node);
}
}
}
export function getJsNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): NavigationBarItem[] {
const anonFnText = "<function>";
const anonClassText = "<class>";
let indent = 0;
let rootName = isExternalModule(sourceFile) ?
"\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName)))) + "\""
: "<global>";
let sourceFileItem = getNavBarItem(rootName, ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]);
let topItem = sourceFileItem;
// Walk the whole file, because we want to also find function expressions - which may be in variable initializer,
// call arguments, expressions, etc...
forEachChild(sourceFile, visitNode);
function visitNode(node: Node) {
const newItem = createNavBarItem(node);
if (newItem) {
topItem.childItems.push(newItem);
}
// Add a level if traversing into a container
if (newItem && (isFunctionLike(node) || isClassLike(node))) {
const lastTop = topItem;
indent++;
topItem = newItem;
forEachChild(node, visitNode);
topItem = lastTop;
indent--;
// If the last item added was an anonymous function expression, and it had no children, discard it.
if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) {
topItem.childItems.pop();
}
}
else {
forEachChild(node, visitNode);
}
}
function createNavBarItem(node: Node) : NavigationBarItem {
switch (node.kind) {
case SyntaxKind.VariableDeclaration:
// Only add to the navbar if at the top-level of the file
// Note: "const" and "let" are also SyntaxKind.VariableDeclarations
if(node.parent/*VariableDeclarationList*/.parent/*VariableStatement*/
.parent/*SourceFile*/.kind !== SyntaxKind.SourceFile) {
return undefined;
}
// If it is initialized with a function expression, handle it when we reach the function expression node
const varDecl = node as VariableDeclaration;
if (varDecl.initializer && (varDecl.initializer.kind === SyntaxKind.FunctionExpression ||
varDecl.initializer.kind === SyntaxKind.ArrowFunction ||
varDecl.initializer.kind === SyntaxKind.ClassExpression)) {
return undefined;
}
// Fall through
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
// "export default function().." looks just like a regular function/class declaration, except with the 'default' flag
const name = node.flags && (node.flags & NodeFlags.Default) && !(node as (Declaration)).name ? "default" :
node.kind === SyntaxKind.Constructor ? "constructor" :
declarationNameToString((node as (Declaration)).name);
return getNavBarItem(name, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]);
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.ClassExpression:
return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node);
case SyntaxKind.MethodDeclaration:
const methodDecl = node as MethodDeclaration;
return getNavBarItem(declarationNameToString(methodDecl.name),
ScriptElementKind.memberFunctionElement,
[getNodeSpan(node)]);
case SyntaxKind.ExportAssignment:
// e.g. "export default <expr>"
return getNavBarItem("default", ScriptElementKind.variableElement, [getNodeSpan(node)]);
case SyntaxKind.ImportClause: // e.g. 'def' in: import def from 'mod' (in ImportDeclaration)
if (!(node as ImportClause).name) {
// No default import (this node is still a parent of named & namespace imports, which are handled below)
return undefined;
}
// fall through
case SyntaxKind.ImportSpecifier: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause)
case SyntaxKind.NamespaceImport: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause)
case SyntaxKind.ExportSpecifier: // e.g. 'a' or 'b' in: export {a, foo as b} from 'mod'
// Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals
if (node.kind === SyntaxKind.ExportSpecifier) {
if (!(node.parent.parent as ExportDeclaration).moduleSpecifier && !(node as ExportSpecifier).propertyName) {
return undefined;
}
}
const decl = node as (ImportSpecifier | ImportClause | NamespaceImport | ExportSpecifier);
if (!decl.name) {
return undefined;
}
const declName = declarationNameToString(decl.name);
return getNavBarItem(declName, ScriptElementKind.constElement, [getNodeSpan(node)]);
default:
return undefined;
}
}
function getNavBarItem(text: string, kind: string, spans: TextSpan[], kindModifiers = ScriptElementKindModifier.none): NavigationBarItem {
return {
text, kind, kindModifiers, spans, childItems: [], indent, bolded: false, grayed: false
}
}
function getDefineModuleItem(node: Node): NavigationBarItem {
if (node.kind !== SyntaxKind.FunctionExpression && node.kind !== SyntaxKind.ArrowFunction) {
return undefined;
}
// No match if this is not a call expression to an identifier named 'define'
if (node.parent.kind !== SyntaxKind.CallExpression) {
return undefined;
}
const callExpr = node.parent as CallExpression;
if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== 'define') {
return undefined;
}
// Return a module of either the given text in the first argument, or of the source file path
let defaultName = node.getSourceFile().fileName;
if (callExpr.arguments[0].kind === SyntaxKind.StringLiteral) {
defaultName = ((callExpr.arguments[0]) as StringLiteral).text;
}
return getNavBarItem(defaultName, ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]);
}
function getFunctionOrClassExpressionItem(node: Node): NavigationBarItem {
if (node.kind !== SyntaxKind.FunctionExpression &&
node.kind !== SyntaxKind.ArrowFunction &&
node.kind !== SyntaxKind.ClassExpression) {
return undefined;
}
const fnExpr = node as FunctionExpression | ArrowFunction | ClassExpression;
let fnName: string;
if (fnExpr.name && getFullWidth(fnExpr.name) > 0) {
// The expression has an identifier, so use that as the name
fnName = declarationNameToString(fnExpr.name);
}
else {
// See if it is a var initializer. If so, use the var name.
if (fnExpr.parent.kind === SyntaxKind.VariableDeclaration) {
fnName = declarationNameToString((fnExpr.parent as VariableDeclaration).name);
}
// See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
else if (fnExpr.parent.kind === SyntaxKind.BinaryExpression &&
(fnExpr.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
fnName = (fnExpr.parent as BinaryExpression).left.getText();
if (fnName.length > 20) {
fnName = fnName.substring(0, 17) + "...";
}
}
// See if it is a property assignment, and if so use the property name
else if (fnExpr.parent.kind === SyntaxKind.PropertyAssignment &&
(fnExpr.parent as PropertyAssignment).name) {
fnName = (fnExpr.parent as PropertyAssignment).name.getText();
}
else {
fnName = node.kind === SyntaxKind.ClassExpression ? anonClassText : anonFnText;
}
}
const scriptKind = node.kind === SyntaxKind.ClassExpression ? ScriptElementKind.classElement : ScriptElementKind.functionElement;
return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]);
}
function getNodeSpan(node: Node) {
return node.kind === SyntaxKind.SourceFile
? createTextSpanFromBounds(node.getFullStart(), node.getEnd())
: createTextSpanFromBounds(node.getStart(), node.getEnd());
}
function getScriptKindForElementKind(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.VariableDeclaration:
return ScriptElementKind.variableElement;
case SyntaxKind.FunctionDeclaration:
return ScriptElementKind.functionElement;
case SyntaxKind.ClassDeclaration:
return ScriptElementKind.classElement;
case SyntaxKind.Constructor:
return ScriptElementKind.constructorImplementationElement;
case SyntaxKind.GetAccessor:
return ScriptElementKind.memberGetAccessorElement;
case SyntaxKind.SetAccessor:
return ScriptElementKind.memberSetAccessorElement;
default:
return "unknown";
}
}
return sourceFileItem.childItems;
}
}
+150 -151
View File
@@ -1,180 +1,179 @@
/* @internal */
namespace ts {
export module OutliningElementsCollector {
export function collectElements(sourceFile: SourceFile): OutliningSpan[] {
let elements: OutliningSpan[] = [];
let collapseText = "...";
namespace ts.OutliningElementsCollector {
export function collectElements(sourceFile: SourceFile): OutliningSpan[] {
const elements: OutliningSpan[] = [];
const collapseText = "...";
function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) {
if (hintSpanNode && startElement && endElement) {
let span: OutliningSpan = {
textSpan: createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) {
if (hintSpanNode && startElement && endElement) {
const span: OutliningSpan = {
textSpan: createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function addOutliningSpanComments(commentSpan: CommentRange, autoCollapse: boolean) {
if (commentSpan) {
let span: OutliningSpan = {
textSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
function addOutliningSpanComments(commentSpan: CommentRange, autoCollapse: boolean) {
if (commentSpan) {
const span: OutliningSpan = {
textSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
hintSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
elements.push(span);
}
}
function addOutliningForLeadingCommentsForNode(n: Node) {
let comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
function addOutliningForLeadingCommentsForNode(n: Node) {
const comments = ts.getLeadingCommentRangesOfNode(n, sourceFile);
if (comments) {
let firstSingleLineCommentStart = -1;
let lastSingleLineCommentEnd = -1;
let isFirstSingleLineComment = true;
let singleLineCommentCount = 0;
if (comments) {
let firstSingleLineCommentStart = -1;
let lastSingleLineCommentEnd = -1;
let isFirstSingleLineComment = true;
let singleLineCommentCount = 0;
for (let currentComment of comments) {
for (const currentComment of comments) {
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === SyntaxKind.SingleLineCommentTrivia) {
if (isFirstSingleLineComment) {
firstSingleLineCommentStart = currentComment.pos;
}
isFirstSingleLineComment = false;
lastSingleLineCommentEnd = currentComment.end;
singleLineCommentCount++;
// For single line comments, combine consecutive ones (2 or more) into
// a single span from the start of the first till the end of the last
if (currentComment.kind === SyntaxKind.SingleLineCommentTrivia) {
if (isFirstSingleLineComment) {
firstSingleLineCommentStart = currentComment.pos;
}
else if (currentComment.kind === SyntaxKind.MultiLineCommentTrivia) {
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
addOutliningSpanComments(currentComment, /*autoCollapse*/ false);
isFirstSingleLineComment = false;
lastSingleLineCommentEnd = currentComment.end;
singleLineCommentCount++;
}
else if (currentComment.kind === SyntaxKind.MultiLineCommentTrivia) {
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
addOutliningSpanComments(currentComment, /*autoCollapse*/ false);
singleLineCommentCount = 0;
lastSingleLineCommentEnd = -1;
isFirstSingleLineComment = true;
singleLineCommentCount = 0;
lastSingleLineCommentEnd = -1;
isFirstSingleLineComment = true;
}
}
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
}
}
function combineAndAddMultipleSingleLineComments(count: number, start: number, end: number) {
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
const multipleSingleLineComments = {
pos: start,
end: end,
kind: SyntaxKind.SingleLineCommentTrivia
};
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
function autoCollapse(node: Node) {
return isFunctionBlock(node) && node.parent.kind !== SyntaxKind.ArrowFunction;
}
let depth = 0;
const maxDepth = 20;
function walk(n: Node): void {
if (depth > maxDepth) {
return;
}
if (isDeclaration(n)) {
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
case SyntaxKind.Block:
if (!isFunctionBlock(n)) {
const parent = n.parent;
const openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
const closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collapse the block, but consider its hint span
// to be the entire span of the parent.
if (parent.kind === SyntaxKind.DoStatement ||
parent.kind === SyntaxKind.ForInStatement ||
parent.kind === SyntaxKind.ForOfStatement ||
parent.kind === SyntaxKind.ForStatement ||
parent.kind === SyntaxKind.IfStatement ||
parent.kind === SyntaxKind.WhileStatement ||
parent.kind === SyntaxKind.WithStatement ||
parent.kind === SyntaxKind.CatchClause) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
}
combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd);
}
}
function combineAndAddMultipleSingleLineComments(count: number, start: number, end: number) {
// Only outline spans of two or more consecutive single line comments
if (count > 1) {
let multipleSingleLineComments = {
pos: start,
end: end,
kind: SyntaxKind.SingleLineCommentTrivia
}
addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false);
}
}
function autoCollapse(node: Node) {
return isFunctionBlock(node) && node.parent.kind !== SyntaxKind.ArrowFunction;
}
let depth = 0;
let maxDepth = 20;
function walk(n: Node): void {
if (depth > maxDepth) {
return;
}
if (isDeclaration(n)) {
addOutliningForLeadingCommentsForNode(n);
}
switch (n.kind) {
case SyntaxKind.Block:
if (!isFunctionBlock(n)) {
let parent = n.parent;
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
// Check if the block is standalone, or 'attached' to some parent statement.
// If the latter, we want to collaps the block, but consider its hint span
// to be the entire span of the parent.
if (parent.kind === SyntaxKind.DoStatement ||
parent.kind === SyntaxKind.ForInStatement ||
parent.kind === SyntaxKind.ForOfStatement ||
parent.kind === SyntaxKind.ForStatement ||
parent.kind === SyntaxKind.IfStatement ||
parent.kind === SyntaxKind.WhileStatement ||
parent.kind === SyntaxKind.WithStatement ||
parent.kind === SyntaxKind.CatchClause) {
if (parent.kind === SyntaxKind.TryStatement) {
// Could be the try-block, or the finally-block.
const tryStatement = <TryStatement>parent;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
if (parent.kind === SyntaxKind.TryStatement) {
// Could be the try-block, or the finally-block.
let tryStatement = <TryStatement>parent;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
else if (tryStatement.finallyBlock === n) {
const finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
let finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
}
// fall through.
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
let span = createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
// fall through.
}
// Fallthrough.
case SyntaxKind.ModuleBlock: {
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
const span = createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.CaseBlock: {
let openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
let closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
case SyntaxKind.ArrayLiteralExpression:
let openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile);
let closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
// Fallthrough.
case SyntaxKind.ModuleBlock: {
const openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
const closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));
break;
}
depth++;
forEachChild(n, walk);
depth--;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.CaseBlock: {
const openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
const closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n));
break;
}
case SyntaxKind.ArrayLiteralExpression:
const openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile);
const closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile);
addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n));
break;
}
walk(sourceFile);
return elements;
depth++;
forEachChild(n, walk);
depth--;
}
walk(sourceFile);
return elements;
}
}
+82 -136
View File
@@ -8,10 +8,10 @@ namespace ts {
camelCase
}
// Information about a match made by the pattern matcher between a candidate and the
// Information about a match made by the pattern matcher between a candidate and the
// search pattern.
export interface PatternMatch {
// What kind of match this was. Exact matches are better than prefix matches which are
// What kind of match this was. Exact matches are better than prefix matches which are
// better than substring matches which are better than CamelCase matches.
kind: PatternMatchKind;
@@ -19,7 +19,7 @@ namespace ts {
// it was a better match.
camelCaseWeight?: number;
// If this was a match where all constituent parts of the candidate and search pattern
// If this was a match where all constituent parts of the candidate and search pattern
// matched case sensitively or case insensitively. Case sensitive matches of the kind
// are better matches than insensitive matches.
isCaseSensitive: boolean;
@@ -35,7 +35,7 @@ namespace ts {
// once you no longer need it.
export interface PatternMatcher {
// Used to match a candidate against the last segment of a possibly dotted pattern. This
// is useful as a quick check to prevent having to compute a container before calling
// is useful as a quick check to prevent having to compute a container before calling
// "getMatches".
//
// For example, if the search pattern is "ts.c.SK" and the candidate is "SyntaxKind", then
@@ -55,8 +55,8 @@ namespace ts {
}
// First we break up the pattern given by dots. Each portion of the pattern between the
// dots is a 'Segment'. The 'Segment' contains information about the entire section of
// text between the dots, as well as information about any individual 'Words' that we
// dots is a 'Segment'. The 'Segment' contains information about the entire section of
// text between the dots, as well as information about any individual 'Words' that we
// can break the segment into. A 'Word' is simply a contiguous sequence of characters
// that can appear in a typescript identifier. So "GetKeyword" would be one word, while
// "Get Keyword" would be two words. Once we have the individual 'words', we break those
@@ -64,20 +64,20 @@ namespace ts {
// word, it make character spans corresponding to "U", "I" and "Element". These spans
// are then used when doing camel cased matches against candidate patterns.
interface Segment {
// Information about the entire piece of text between the dots. For example, if the
// text between the dots is 'GetKeyword', then TotalTextChunk.Text will be 'GetKeyword' and
// Information about the entire piece of text between the dots. For example, if the
// text between the dots is 'GetKeyword', then TotalTextChunk.Text will be 'GetKeyword' and
// TotalTextChunk.CharacterSpans will correspond to 'Get', 'Keyword'.
totalTextChunk: TextChunk;
// Information about the subwords compromising the total word. For example, if the
// text between the dots is 'GetFoo KeywordBar', then the subwords will be 'GetFoo'
// and 'KeywordBar'. Those individual words will have CharacterSpans of ('Get' and
// 'Foo') and('Keyword' and 'Bar') respectively.
// Information about the subwords compromising the total word. For example, if the
// text between the dots is 'GetFoo KeywordBar', then the subwords will be 'GetFoo'
// and 'KeywordBar'. Those individual words will have CharacterSpans of ('Get' and
// 'Foo') and('Keyword' and 'Bar') respectively.
subWordTextChunks: TextChunk[];
}
// Information about a chunk of text from the pattern. The chunk is a piece of text, with
// cached information about the character spans within in. Character spans are used for
// Information about a chunk of text from the pattern. The chunk is a piece of text, with
// cached information about the character spans within in. Character spans are used for
// camel case matching.
interface TextChunk {
// The text of the chunk. This should be a contiguous sequence of character that could
@@ -92,9 +92,9 @@ namespace ts {
// for something entirely lowercase or not.
isLowerCase: boolean;
// The spans in this text chunk that we think are of interest and should be matched
// The spans in this text chunk that we think are of interest and should be matched
// independently. For example, if the chunk is for "UIElement" the the spans of interest
// correspond to "U", "I" and "Element". If "UIElement" isn't found as an exaxt, prefix.
// correspond to "U", "I" and "Element". If "UIElement" isn't found as an exact, prefix.
// or substring match, then the character spans will be used to attempt a camel case match.
characterSpans: TextSpan[];
}
@@ -110,20 +110,19 @@ namespace ts {
export function createPatternMatcher(pattern: string): PatternMatcher {
// We'll often see the same candidate string many times when searching (For example, when
// we see the name of a module that is used everywhere, or the name of an overload). As
// such, we cache the information we compute about the candidate for the life of this
// we see the name of a module that is used everywhere, or the name of an overload). As
// such, we cache the information we compute about the candidate for the life of this
// pattern matcher so we don't have to compute it multiple times.
let stringToWordSpans: Map<TextSpan[]> = {};
const stringToWordSpans: Map<TextSpan[]> = {};
pattern = pattern.trim();
let fullPatternSegment = createSegment(pattern);
let dotSeparatedSegments = pattern.split(".").map(p => createSegment(p.trim()));
let invalidPattern = dotSeparatedSegments.length === 0 || forEach(dotSeparatedSegments, segmentIsInvalid);
const dotSeparatedSegments = pattern.split(".").map(p => createSegment(p.trim()));
const invalidPattern = dotSeparatedSegments.length === 0 || forEach(dotSeparatedSegments, segmentIsInvalid);
return {
getMatches,
getMatchesForLastSegmentOfPattern,
getMatchesForLastSegmentOfPattern,
patternContainsDots: dotSeparatedSegments.length > 1
};
@@ -131,7 +130,7 @@ namespace ts {
function skipMatch(candidate: string) {
return invalidPattern || !candidate;
}
function getMatchesForLastSegmentOfPattern(candidate: string): PatternMatch[] {
if (skipMatch(candidate)) {
return undefined;
@@ -148,7 +147,7 @@ namespace ts {
// First, check that the last part of the dot separated pattern matches the name of the
// candidate. If not, then there's no point in proceeding and doing the more
// expensive work.
let candidateMatch = matchSegment(candidate, lastOrUndefined(dotSeparatedSegments));
const candidateMatch = matchSegment(candidate, lastOrUndefined(dotSeparatedSegments));
if (!candidateMatch) {
return undefined;
}
@@ -165,16 +164,16 @@ namespace ts {
// So far so good. Now break up the container for the candidate and check if all
// the dotted parts match up correctly.
let totalMatch = candidateMatch;
const totalMatch = candidateMatch;
for (let i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1;
i >= 0;
i--, j--) {
i -= 1, j -= 1) {
let segment = dotSeparatedSegments[i];
let containerName = candidateContainers[j];
const segment = dotSeparatedSegments[i];
const containerName = candidateContainers[j];
let containerMatch = matchSegment(containerName, segment);
const containerMatch = matchSegment(containerName, segment);
if (!containerMatch) {
// This container didn't match the pattern piece. So there's no match at all.
return undefined;
@@ -197,7 +196,7 @@ namespace ts {
}
function matchTextChunk(candidate: string, chunk: TextChunk, punctuationStripped: boolean): PatternMatch {
let index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
const index = indexOfIgnoringCase(candidate, chunk.textLowerCase);
if (index === 0) {
if (chunk.text.length === candidate.length) {
// a) Check if the part matches the candidate entirely, in an case insensitive or
@@ -211,18 +210,18 @@ namespace ts {
}
}
let isLowercase = chunk.isLowerCase;
const isLowercase = chunk.isLowerCase;
if (isLowercase) {
if (index > 0) {
// c) If the part is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of some
// word part. That way we don't match something like 'Class' when the user types 'a'.
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
let wordSpans = getWordSpans(candidate);
for (let span of wordSpans) {
const wordSpans = getWordSpans(candidate);
for (const span of wordSpans) {
if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) {
return createPatternMatch(PatternMatchKind.substring, punctuationStripped,
/*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false));
@@ -242,7 +241,7 @@ namespace ts {
if (!isLowercase) {
// e) If the part was not entirely lowercase, then attempt a camel cased match as well.
if (chunk.characterSpans.length > 0) {
let candidateParts = getWordSpans(candidate);
const candidateParts = getWordSpans(candidate);
let camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false);
if (camelCaseWeight !== undefined) {
return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight);
@@ -259,8 +258,8 @@ namespace ts {
// f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
// We could check every character boundary start of the candidate for the pattern. However, that's
// an m * n operation in the wost case. Instead, find the first instance of the pattern
// substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
// an m * n operation in the wost case. Instead, find the first instance of the pattern
// substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
// filter the list based on a substring that starts on a capital letter and also with a lowercase one.
// (Pattern: fogbar, Candidate: quuxfogbarFogBar).
if (chunk.text.length < candidate.length) {
@@ -275,7 +274,7 @@ namespace ts {
function containsSpaceOrAsterisk(text: string): boolean {
for (let i = 0; i < text.length; i++) {
let ch = text.charCodeAt(i);
const ch = text.charCodeAt(i);
if (ch === CharacterCodes.space || ch === CharacterCodes.asterisk) {
return true;
}
@@ -293,7 +292,7 @@ namespace ts {
// Note: if the segment contains a space or an asterisk then we must assume that it's a
// multi-word segment.
if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) {
let match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false);
const match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false);
if (match) {
return [match];
}
@@ -317,7 +316,7 @@ namespace ts {
//
// c) If the word is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of
// some word part. That way we don't match something like 'Class' when the user
@@ -331,17 +330,17 @@ namespace ts {
// e) If the word was not entirely lowercase, then attempt a camel cased match as
// well.
//
// f) The word is all lower case. Is it a case insensitive substring of the candidate starting
// f) The word is all lower case. Is it a case insensitive substring of the candidate starting
// on a part boundary of the candidate?
//
// Only if all words have some sort of match is the pattern considered matched.
let subWordTextChunks = segment.subWordTextChunks;
const subWordTextChunks = segment.subWordTextChunks;
let matches: PatternMatch[] = undefined;
for (let subWordTextChunk of subWordTextChunks) {
for (const subWordTextChunk of subWordTextChunks) {
// Try to match the candidate with this word
let result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true);
const result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true);
if (!result) {
return undefined;
}
@@ -354,18 +353,18 @@ namespace ts {
}
function partStartsWith(candidate: string, candidateSpan: TextSpan, pattern: string, ignoreCase: boolean, patternSpan?: TextSpan): boolean {
let patternPartStart = patternSpan ? patternSpan.start : 0;
let patternPartLength = patternSpan ? patternSpan.length : pattern.length;
const patternPartStart = patternSpan ? patternSpan.start : 0;
const patternPartLength = patternSpan ? patternSpan.length : pattern.length;
if (patternPartLength > candidateSpan.length) {
// Pattern part is longer than the candidate part. There can never be a match.
return false;
}
if (ignoreCase) {
for (let i = 0; i < patternPartLength; i++) {
let ch1 = pattern.charCodeAt(patternPartStart + i);
let ch2 = candidate.charCodeAt(candidateSpan.start + i);
const ch1 = pattern.charCodeAt(patternPartStart + i);
const ch2 = candidate.charCodeAt(candidateSpan.start + i);
if (toLowerCase(ch1) !== toLowerCase(ch2)) {
return false;
}
@@ -373,8 +372,8 @@ namespace ts {
}
else {
for (let i = 0; i < patternPartLength; i++) {
let ch1 = pattern.charCodeAt(patternPartStart + i);
let ch2 = candidate.charCodeAt(candidateSpan.start + i);
const ch1 = pattern.charCodeAt(patternPartStart + i);
const ch2 = candidate.charCodeAt(candidateSpan.start + i);
if (ch1 !== ch2) {
return false;
}
@@ -385,12 +384,12 @@ namespace ts {
}
function tryCamelCaseMatch(candidate: string, candidateParts: TextSpan[], chunk: TextChunk, ignoreCase: boolean): number {
let chunkCharacterSpans = chunk.characterSpans;
const chunkCharacterSpans = chunk.characterSpans;
// Note: we may have more pattern parts than candidate parts. This is because multiple
// pattern parts may match a candidate part. For example "SiUI" against "SimpleUI".
// We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U
// and I will both match in UI.
// and I will both match in UI.
let currentCandidate = 0;
let currentChunkSpan = 0;
@@ -426,14 +425,14 @@ namespace ts {
// Consider the case of matching SiUI against SimpleUIElement. The candidate parts
// will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si'
// against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to
// still keep matching pattern parts against that candidate part.
// still keep matching pattern parts against that candidate part.
for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) {
let chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
const chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
if (gotOneMatchThisCandidate) {
// We've already gotten one pattern part match in this candidate. We will
// only continue trying to consumer pattern parts if the last part and this
// part are both upper case.
// part are both upper case.
if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) ||
!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) {
break;
@@ -470,55 +469,11 @@ namespace ts {
}
}
// Helper function to compare two matches to determine which is better. Matches are first
// ordered by kind (so all prefix matches always beat all substring matches). Then, if the
// match is a camel case match, the relative weights of the match are used to determine
// which is better (with a greater weight being better). Then if the match is of the same
// type, then a case sensitive match is considered better than an insensitive one.
function patternMatchCompareTo(match1: PatternMatch, match2: PatternMatch): number {
return compareType(match1, match2) ||
compareCamelCase(match1, match2) ||
compareCase(match1, match2) ||
comparePunctuation(match1, match2);
}
function comparePunctuation(result1: PatternMatch, result2: PatternMatch) {
// Consider a match to be better if it was successful without stripping punctuation
// versus a match that had to strip punctuation to succeed.
if (result1.punctuationStripped !== result2.punctuationStripped) {
return result1.punctuationStripped ? 1 : -1;
}
return 0;
}
function compareCase(result1: PatternMatch, result2: PatternMatch) {
if (result1.isCaseSensitive !== result2.isCaseSensitive) {
return result1.isCaseSensitive ? -1 : 1;
}
return 0;
}
function compareType(result1: PatternMatch, result2: PatternMatch) {
return result1.kind - result2.kind;
}
function compareCamelCase(result1: PatternMatch, result2: PatternMatch) {
if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) {
// Swap the values here. If result1 has a higher weight, then we want it to come
// first.
return result2.camelCaseWeight - result1.camelCaseWeight;
}
return 0;
}
function createSegment(text: string): Segment {
return {
totalTextChunk: createTextChunk(text),
subWordTextChunks: breakPatternIntoTextChunks(text)
}
};
}
// A segment is considered invalid if we couldn't find any words in it.
@@ -536,9 +491,9 @@ namespace ts {
return false;
}
// TODO: find a way to determine this for any unicode characters in a
// TODO: find a way to determine this for any unicode characters in a
// non-allocating manner.
let str = String.fromCharCode(ch);
const str = String.fromCharCode(ch);
return str === str.toUpperCase();
}
@@ -553,22 +508,12 @@ namespace ts {
}
// TODO: find a way to determine this for any unicode characters in a
// TODO: find a way to determine this for any unicode characters in a
// non-allocating manner.
let str = String.fromCharCode(ch);
const str = String.fromCharCode(ch);
return str === str.toLowerCase();
}
function containsUpperCaseLetter(string: string): boolean {
for (let i = 0, n = string.length; i < n; i++) {
if (isUpperCaseLetter(string.charCodeAt(i))) {
return true;
}
}
return false;
}
function startsWith(string: string, search: string) {
for (let i = 0, n = search.length; i < n; i++) {
if (string.charCodeAt(i) !== search.charCodeAt(i)) {
@@ -593,8 +538,8 @@ namespace ts {
// Assumes 'value' is already lowercase.
function startsWithIgnoringCase(string: string, value: string, start: number): boolean {
for (let i = 0, n = value.length; i < n; i++) {
let ch1 = toLowerCase(string.charCodeAt(i + start));
let ch2 = value.charCodeAt(i);
const ch1 = toLowerCase(string.charCodeAt(i + start));
const ch2 = value.charCodeAt(i);
if (ch1 !== ch2) {
return false;
@@ -614,7 +559,7 @@ namespace ts {
return ch;
}
// TODO: find a way to compute this for any unicode characters in a
// TODO: find a way to compute this for any unicode characters in a
// non-allocating manner.
return String.fromCharCode(ch).toLowerCase().charCodeAt(0);
}
@@ -629,16 +574,17 @@ namespace ts {
}
function breakPatternIntoTextChunks(pattern: string): TextChunk[] {
let result: TextChunk[] = [];
const result: TextChunk[] = [];
let wordStart = 0;
let wordLength = 0;
for (let i = 0; i < pattern.length; i++) {
let ch = pattern.charCodeAt(i);
const ch = pattern.charCodeAt(i);
if (isWordChar(ch)) {
if (wordLength++ === 0) {
if (wordLength === 0) {
wordStart = i;
}
wordLength++;
}
else {
if (wordLength > 0) {
@@ -656,13 +602,13 @@ namespace ts {
}
function createTextChunk(text: string): TextChunk {
let textLowerCase = text.toLowerCase();
const textLowerCase = text.toLowerCase();
return {
text,
textLowerCase,
isLowerCase: text === textLowerCase,
characterSpans: breakIntoCharacterSpans(text)
}
};
}
/* @internal */ export function breakIntoCharacterSpans(identifier: string): TextSpan[] {
@@ -674,15 +620,15 @@ namespace ts {
}
function breakIntoSpans(identifier: string, word: boolean): TextSpan[] {
let result: TextSpan[] = [];
const result: TextSpan[] = [];
let wordStart = 0;
for (let i = 1, n = identifier.length; i < n; i++) {
let lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
let currentIsDigit = isDigit(identifier.charCodeAt(i));
const lastIsDigit = isDigit(identifier.charCodeAt(i - 1));
const currentIsDigit = isDigit(identifier.charCodeAt(i));
let hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
let hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart);
const hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i);
const hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart);
if (charIsPunctuation(identifier.charCodeAt(i - 1)) ||
charIsPunctuation(identifier.charCodeAt(i)) ||
@@ -738,7 +684,7 @@ namespace ts {
function isAllPunctuation(identifier: string, start: number, end: number): boolean {
for (let i = start; i < end; i++) {
let ch = identifier.charCodeAt(i);
const ch = identifier.charCodeAt(i);
// We don't consider _ or $ as punctuation as there may be things with that name.
if (!charIsPunctuation(ch) || ch === CharacterCodes._ || ch === CharacterCodes.$) {
@@ -759,8 +705,8 @@ namespace ts {
// etc.
if (index !== wordStart &&
index + 1 < identifier.length) {
let currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
let nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1));
const currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
const nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1));
if (currentIsUpper && nextIsLower) {
// We have a transition from an upper to a lower letter here. But we only
@@ -786,12 +732,12 @@ namespace ts {
}
function transitionFromLowerToUpper(identifier: string, word: boolean, index: number): boolean {
let lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
let currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
const lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1));
const currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
// See if the casing indicates we're starting a new word. Note: if we're breaking on
// words, then just seeing an upper case character isn't enough. Instead, it has to
// be uppercase and the previous character can't be uppercase.
// be uppercase and the previous character can't be uppercase.
//
// For example, breaking "AddMetadata" on words would make: Add Metadata
//
@@ -802,7 +748,7 @@ namespace ts {
// on characters would be: A M
//
// We break the search string on characters. But we break the symbol name on words.
let transition = word
const transition = word
? (currentIsUpper && !lastIsUpper)
: currentIsUpper;
return transition;
+1217 -1048
View File
File diff suppressed because it is too large Load Diff
+219 -225
View File
@@ -16,7 +16,11 @@
/// <reference path='services.ts' />
/* @internal */
var debugObjectHost = (<any>this);
let debugObjectHost = (<any>this);
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null */
/* tslint:disable:no-in-operator */
/* @internal */
namespace ts {
@@ -51,6 +55,7 @@ namespace ts {
/** Returns a JSON-encoded value of the type: string[] */
getScriptFileNames(): string;
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): ScriptSnapshotShim;
getLocalizedDiagnosticMessages(): string;
@@ -60,8 +65,9 @@ namespace ts {
getNewLine?(): string;
getProjectVersion?(): string;
useCaseSensitiveFileNames?(): boolean;
getModuleResolutionsForFile?(fileName: string): string;
directoryExists(directoryName: string): boolean;
}
/** Public interface of the the of a config service shim instance.*/
@@ -72,7 +78,9 @@ namespace ts {
* @param exclude A JSON encoded string[] containing the paths to exclude
* when enumerating the directory.
*/
readDirectory(rootDir: string, extension: string, exclude?: string): string;
readDirectory(rootDir: string, extension: string, exclude?: string, depth?: number): string;
trace(s: string): void;
}
///
@@ -224,6 +232,7 @@ namespace ts {
getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getDefaultCompilationSettings(): string;
discoverTypings(discoverTypingsJson: string): string;
}
function logInternalError(logger: Logger, err: Error) {
@@ -233,8 +242,6 @@ namespace ts {
}
class ScriptSnapshotShimAdapter implements IScriptSnapshot {
private lineStartPositions: number[] = null;
constructor(private scriptSnapshotShim: ScriptSnapshotShim) {
}
@@ -247,14 +254,14 @@ namespace ts {
}
public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange {
var oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
const oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
// TODO: should this be '==='?
if (encoded == null) {
return null;
}
var decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded);
const decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded);
return createTextChangeRange(
createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
}
@@ -272,21 +279,25 @@ namespace ts {
private files: string[];
private loggingEnabled = false;
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[];
public directoryExists: (directoryName: string) => boolean;
constructor(private shimHost: LanguageServiceShimHost) {
// if shimHost is a COM object then property check will become method call with no arguments.
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = (moduleNames: string[], containingFile: string) => {
let resolutionsInFile = <Map<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile));
const resolutionsInFile = <Map<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile));
return map(moduleNames, name => {
const result = lookUp(resolutionsInFile, name);
return result ? { resolvedFileName: result } : undefined;
});
};
}
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
}
public log(s: string): void {
@@ -319,7 +330,7 @@ namespace ts {
}
public getCompilationSettings(): CompilerOptions {
var settingsJson = this.shimHost.getCompilationSettings();
const settingsJson = this.shimHost.getCompilationSettings();
// TODO: should this be '==='?
if (settingsJson == null || settingsJson == "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
@@ -328,26 +339,30 @@ namespace ts {
}
public getScriptFileNames(): string[] {
var encoded = this.shimHost.getScriptFileNames();
const encoded = this.shimHost.getScriptFileNames();
return this.files = JSON.parse(encoded);
}
public getScriptSnapshot(fileName: string): IScriptSnapshot {
// Shim the API changes for 1.5 release. This should be removed once
// TypeScript 1.5 has shipped.
if (this.files && this.files.indexOf(fileName) < 0) {
return undefined;
}
var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName);
return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot);
}
public getScriptKind(fileName: string): ScriptKind {
if ("getScriptKind" in this.shimHost) {
return this.shimHost.getScriptKind(fileName);
}
else {
return ScriptKind.Unknown;
}
}
public getScriptVersion(fileName: string): string {
return this.shimHost.getScriptVersion(fileName);
}
public getLocalizedDiagnosticMessages(): any {
var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages();
if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") {
return null;
}
@@ -362,7 +377,7 @@ namespace ts {
}
public getCancellationToken(): HostCancellationToken {
var hostCancellationToken = this.shimHost.getCancellationToken();
const hostCancellationToken = this.shimHost.getCancellationToken();
return new ThrottledCancellationToken(hostCancellationToken);
}
@@ -371,14 +386,7 @@ namespace ts {
}
public getDefaultLibFileName(options: CompilerOptions): string {
// Wrap the API changes for 1.5 release. This try/catch
// should be removed once TypeScript 1.5 has shipped.
try {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
}
catch (e) {
return "";
}
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
}
}
@@ -393,8 +401,8 @@ namespace ts {
}
public isCancellationRequested(): boolean {
var time = Date.now();
var duration = Math.abs(time - this.lastCancellationCheckTime);
const time = Date.now();
const duration = Math.abs(time - this.lastCancellationCheckTime);
if (duration > 10) {
// Check no more than once every 10 ms.
this.lastCancellationCheckTime = time;
@@ -405,52 +413,56 @@ namespace ts {
}
}
export class CoreServicesShimHostAdapter implements ParseConfigHost {
export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost {
public directoryExists: (directoryName: string) => boolean;
constructor(private shimHost: CoreServicesShimHost) {
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
}
public readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
// Wrap the API changes for 1.5 release. This try/catch
// should be removed once TypeScript 1.5 has shipped.
// Also consider removing the optional designation for
// the exclude param at this time.
var encoded: string;
public readDirectory(rootDir: string, extension: string, exclude: string[], depth?: number): string[] {
// Wrap the API changes for 2.0 release. This try/catch
// should be removed once TypeScript 2.0 has shipped.
let encoded: string;
try {
encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude));
encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth);
}
catch (e) {
encoded = this.shimHost.readDirectory(rootDir, extension);
encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude));
}
return JSON.parse(encoded);
}
public fileExists(fileName: string): boolean {
return this.shimHost.fileExists(fileName);
}
public readFile(fileName: string): string {
return this.shimHost.readFile(fileName);
}
}
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): any {
let start: number;
if (logPerformance) {
logger.log(actionDescription);
var start = Date.now();
start = Date.now();
}
var result = action();
const result = action();
if (logPerformance) {
var end = Date.now();
logger.log(actionDescription + " completed in " + (end - start) + " msec");
if (typeof (result) === "string") {
var str = <string>result;
const end = Date.now();
logger.log(`${actionDescription} completed in ${end - start} msec`);
if (typeof result === "string") {
let str = result;
if (str.length > 128) {
str = str.substring(0, 128) + "...";
}
logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`);
}
}
@@ -459,8 +471,8 @@ namespace ts {
function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): string {
try {
var result = simpleForwardCall(logger, actionDescription, action, logPerformance);
return JSON.stringify({ result: result });
const result = simpleForwardCall(logger, actionDescription, action, logPerformance);
return JSON.stringify({ result });
}
catch (err) {
if (err instanceof OperationCanceledException) {
@@ -481,7 +493,7 @@ namespace ts {
}
}
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; code: number; } []{
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; code: number; }[] {
return diagnostics.map(d => realizeDiagnostic(d, newLine));
}
@@ -540,10 +552,9 @@ namespace ts {
*/
public refresh(throwOnError: boolean): void {
this.forwardJSONCall(
"refresh(" + throwOnError + ")",
() => {
return <any>null;
});
`refresh(${throwOnError})`,
() => <any>null
);
}
public cleanupSemanticCache(): void {
@@ -555,63 +566,57 @@ namespace ts {
});
}
private realizeDiagnostics(diagnostics: Diagnostic[]): { message: string; start: number; length: number; category: string; }[]{
var newLine = getNewLineOrDefaultFromHost(this.host);
private realizeDiagnostics(diagnostics: Diagnostic[]): { message: string; start: number; length: number; category: string; }[] {
const newLine = getNewLineOrDefaultFromHost(this.host);
return ts.realizeDiagnostics(diagnostics, newLine);
}
public getSyntacticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
"getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
var classifications = this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length));
return classifications;
});
`getSyntacticClassifications('${fileName}', ${start}, ${length})`,
() => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length))
);
}
public getSemanticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
"getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
var classifications = this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length));
return classifications;
});
`getSemanticClassifications('${fileName}', ${start}, ${length})`,
() => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length))
);
}
public getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
"getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
return convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length)));
});
`getEncodedSyntacticClassifications('${fileName}', ${start}, ${length})`,
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
() => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length)))
);
}
public getEncodedSemanticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
"getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
return convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length)));
});
`getEncodedSemanticClassifications('${fileName}', ${start}, ${length})`,
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
() => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length)))
);
}
public getSyntacticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
"getSyntacticDiagnostics('" + fileName + "')",
`getSyntacticDiagnostics('${fileName}')`,
() => {
var diagnostics = this.languageService.getSyntacticDiagnostics(fileName);
const diagnostics = this.languageService.getSyntacticDiagnostics(fileName);
return this.realizeDiagnostics(diagnostics);
});
}
public getSemanticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
"getSemanticDiagnostics('" + fileName + "')",
`getSemanticDiagnostics('${fileName}')`,
() => {
var diagnostics = this.languageService.getSemanticDiagnostics(fileName);
const diagnostics = this.languageService.getSemanticDiagnostics(fileName);
return this.realizeDiagnostics(diagnostics);
});
}
@@ -620,7 +625,7 @@ namespace ts {
return this.forwardJSONCall(
"getCompilerOptionsDiagnostics()",
() => {
var diagnostics = this.languageService.getCompilerOptionsDiagnostics();
const diagnostics = this.languageService.getCompilerOptionsDiagnostics();
return this.realizeDiagnostics(diagnostics);
});
}
@@ -633,11 +638,9 @@ namespace ts {
*/
public getQuickInfoAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getQuickInfoAtPosition('" + fileName + "', " + position + ")",
() => {
var quickInfo = this.languageService.getQuickInfoAtPosition(fileName, position);
return quickInfo;
});
`getQuickInfoAtPosition('${fileName}', ${position})`,
() => this.languageService.getQuickInfoAtPosition(fileName, position)
);
}
@@ -649,11 +652,9 @@ namespace ts {
*/
public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string {
return this.forwardJSONCall(
"getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")",
() => {
var spanInfo = this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos);
return spanInfo;
});
`getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`,
() => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos)
);
}
/**
@@ -662,22 +663,18 @@ namespace ts {
*/
public getBreakpointStatementAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getBreakpointStatementAtPosition('" + fileName + "', " + position + ")",
() => {
var spanInfo = this.languageService.getBreakpointStatementAtPosition(fileName, position);
return spanInfo;
});
`getBreakpointStatementAtPosition('${fileName}', ${position})`,
() => this.languageService.getBreakpointStatementAtPosition(fileName, position)
);
}
/// SIGNATUREHELP
public getSignatureHelpItems(fileName: string, position: number): string {
return this.forwardJSONCall(
"getSignatureHelpItems('" + fileName + "', " + position + ")",
() => {
var signatureInfo = this.languageService.getSignatureHelpItems(fileName, position);
return signatureInfo;
});
`getSignatureHelpItems('${fileName}', ${position})`,
() => this.languageService.getSignatureHelpItems(fileName, position)
);
}
/// GOTO DEFINITION
@@ -688,10 +685,9 @@ namespace ts {
*/
public getDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getDefinitionAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getDefinitionAtPosition(fileName, position);
});
`getDefinitionAtPosition('${fileName}', ${position})`,
() => this.languageService.getDefinitionAtPosition(fileName, position)
);
}
/// GOTO Type
@@ -702,44 +698,39 @@ namespace ts {
*/
public getTypeDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getTypeDefinitionAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getTypeDefinitionAtPosition(fileName, position);
});
`getTypeDefinitionAtPosition('${fileName}', ${position})`,
() => this.languageService.getTypeDefinitionAtPosition(fileName, position)
);
}
public getRenameInfo(fileName: string, position: number): string {
return this.forwardJSONCall(
"getRenameInfo('" + fileName + "', " + position + ")",
() => {
return this.languageService.getRenameInfo(fileName, position);
});
`getRenameInfo('${fileName}', ${position})`,
() => this.languageService.getRenameInfo(fileName, position)
);
}
public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string {
return this.forwardJSONCall(
"findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")",
() => {
return this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments);
});
`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`,
() => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments)
);
}
/// GET BRACE MATCHING
public getBraceMatchingAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getBraceMatchingAtPosition('" + fileName + "', " + position + ")",
() => {
var textRanges = this.languageService.getBraceMatchingAtPosition(fileName, position);
return textRanges;
});
`getBraceMatchingAtPosition('${fileName}', ${position})`,
() => this.languageService.getBraceMatchingAtPosition(fileName, position)
);
}
/// GET SMART INDENT
public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string {
return this.forwardJSONCall(
"getIndentationAtPosition('" + fileName + "', " + position + ")",
`getIndentationAtPosition('${fileName}', ${position})`,
() => {
var localOptions: EditorOptions = JSON.parse(options);
const localOptions: EditorOptions = JSON.parse(options);
return this.languageService.getIndentationAtPosition(fileName, position, localOptions);
});
}
@@ -748,35 +739,32 @@ namespace ts {
public getReferencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getReferencesAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getReferencesAtPosition(fileName, position);
});
`getReferencesAtPosition('${fileName}', ${position})`,
() => this.languageService.getReferencesAtPosition(fileName, position)
);
}
public findReferences(fileName: string, position: number): string {
return this.forwardJSONCall(
"findReferences('" + fileName + "', " + position + ")",
() => {
return this.languageService.findReferences(fileName, position);
});
`findReferences('${fileName}', ${position})`,
() => this.languageService.findReferences(fileName, position)
);
}
public getOccurrencesAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getOccurrencesAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getOccurrencesAtPosition(fileName, position);
});
`getOccurrencesAtPosition('${fileName}', ${position})`,
() => this.languageService.getOccurrencesAtPosition(fileName, position)
);
}
public getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string {
return this.forwardJSONCall(
"getDocumentHighlights('" + fileName + "', " + position + ")",
`getDocumentHighlights('${fileName}', ${position})`,
() => {
var results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
// workaround for VS document higlighting issue - keep only items from the initial file
let normalizedName = normalizeSlashes(fileName).toLowerCase();
const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
// workaround for VS document highlighting issue - keep only items from the initial file
const normalizedName = normalizeSlashes(fileName).toLowerCase();
return filter(results, r => normalizeSlashes(r.fileName).toLowerCase() === normalizedName);
});
}
@@ -790,56 +778,49 @@ namespace ts {
*/
public getCompletionsAtPosition(fileName: string, position: number) {
return this.forwardJSONCall(
"getCompletionsAtPosition('" + fileName + "', " + position + ")",
() => {
var completion = this.languageService.getCompletionsAtPosition(fileName, position);
return completion;
});
`getCompletionsAtPosition('${fileName}', ${position})`,
() => this.languageService.getCompletionsAtPosition(fileName, position)
);
}
/** Get a string based representation of a completion list entry details */
public getCompletionEntryDetails(fileName: string, position: number, entryName: string) {
return this.forwardJSONCall(
"getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")",
() => {
var details = this.languageService.getCompletionEntryDetails(fileName, position, entryName);
return details;
});
`getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`,
() => this.languageService.getCompletionEntryDetails(fileName, position, entryName)
);
}
public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")",
`getFormattingEditsForRange('${fileName}', ${start}, ${end})`,
() => {
var localOptions: ts.FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
return edits;
const localOptions: ts.FormatCodeOptions = JSON.parse(options);
return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions);
});
}
public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsForDocument('" + fileName + "')",
`getFormattingEditsForDocument('${fileName}')`,
() => {
var localOptions: ts.FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsForDocument(fileName, localOptions);
return edits;
const localOptions: ts.FormatCodeOptions = JSON.parse(options);
return this.languageService.getFormattingEditsForDocument(fileName, localOptions);
});
}
public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string {
return this.forwardJSONCall(
"getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')",
`getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`,
() => {
var localOptions: ts.FormatCodeOptions = JSON.parse(options);
var edits = this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
return edits;
const localOptions: ts.FormatCodeOptions = JSON.parse(options);
return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions);
});
}
public getDocCommentTemplateAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")",
`getDocCommentTemplateAtPosition('${fileName}', ${position})`,
() => this.languageService.getDocCommentTemplateAtPosition(fileName, position)
);
}
@@ -849,51 +830,38 @@ namespace ts {
/** Return a list of symbols that are interesting to navigate to */
public getNavigateToItems(searchValue: string, maxResultCount?: number): string {
return this.forwardJSONCall(
"getNavigateToItems('" + searchValue + "', " + maxResultCount+ ")",
() => {
var items = this.languageService.getNavigateToItems(searchValue, maxResultCount);
return items;
});
`getNavigateToItems('${searchValue}', ${maxResultCount})`,
() => this.languageService.getNavigateToItems(searchValue, maxResultCount)
);
}
public getNavigationBarItems(fileName: string): string {
return this.forwardJSONCall(
"getNavigationBarItems('" + fileName + "')",
() => {
var items = this.languageService.getNavigationBarItems(fileName);
return items;
});
`getNavigationBarItems('${fileName}')`,
() => this.languageService.getNavigationBarItems(fileName)
);
}
public getOutliningSpans(fileName: string): string {
return this.forwardJSONCall(
"getOutliningSpans('" + fileName + "')",
() => {
var items = this.languageService.getOutliningSpans(fileName);
return items;
});
`getOutliningSpans('${fileName}')`,
() => this.languageService.getOutliningSpans(fileName)
);
}
public getTodoComments(fileName: string, descriptors: string): string {
return this.forwardJSONCall(
"getTodoComments('" + fileName + "')",
() => {
var items = this.languageService.getTodoComments(fileName, JSON.parse(descriptors));
return items;
});
`getTodoComments('${fileName}')`,
() => this.languageService.getTodoComments(fileName, JSON.parse(descriptors))
);
}
/// Emit
public getEmitOutput(fileName: string): string {
return this.forwardJSONCall(
"getEmitOutput('" + fileName + "')",
() => {
var output = this.languageService.getEmitOutput(fileName);
// Shim the API changes for 1.5 release. This should be removed once
// TypeScript 1.5 has shipped.
(<any>output).emitOutputStatus = output.emitSkipped ? 1 : 0;
return output;
});
`getEmitOutput('${fileName}')`,
() => this.languageService.getEmitOutput(fileName)
);
}
}
@@ -918,12 +886,11 @@ namespace ts {
/// COLORIZATION
public getClassificationsForLine(text: string, lexState: EndOfLineState, classifyKeywordsInGenerics?: boolean): string {
var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
var items = classification.entries;
var result = "";
for (var i = 0; i < items.length; i++) {
result += items[i].length + "\n";
result += items[i].classification + "\n";
const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
let result = "";
for (const item of classification.entries) {
result += item.length + "\n";
result += item.classification + "\n";
}
result += classification.finalLexState;
return result;
@@ -940,24 +907,25 @@ namespace ts {
private forwardJSONCall(actionDescription: string, action: () => any): any {
return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
}
public resolveModuleName(fileName: string, moduleName: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => {
let compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
return {
resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName: undefined,
resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined,
failedLookupLocations: result.failedLookupLocations
};
});
});
}
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
"getPreProcessedFileInfo('" + fileName + "')",
() => {
var result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()));
var convertResult = {
// for now treat files as JavaScript
const result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
const convertResult = {
referencedFiles: <IFileReference[]>[],
importedFiles: <IFileReference[]>[],
ambientExternalModules: result.ambientExternalModules,
@@ -985,26 +953,29 @@ namespace ts {
public getTSConfigFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
"getTSConfigFileInfo('" + fileName + "')",
`getTSConfigFileInfo('${fileName}')`,
() => {
let text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength());
const text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength());
let result = parseConfigFileTextToJson(fileName, text);
const result = parseConfigFileTextToJson(fileName, text);
if (result.error) {
return {
options: {},
typingOptions: {},
files: [],
errors: [realizeDiagnostic(result.error, '\r\n')]
errors: [realizeDiagnostic(result.error, "\r\n")]
};
}
var configFile = parseJsonConfigFileContent(result.config, this.host, getDirectoryPath(normalizeSlashes(fileName)));
const normalizedFileName = normalizeSlashes(fileName);
const configFile = parseJsonConfigFileContent(result.config, this.host, getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName);
return {
options: configFile.options,
typingOptions: configFile.typingOptions,
files: configFile.fileNames,
errors: realizeDiagnostics(configFile.errors, '\r\n')
errors: realizeDiagnostics(configFile.errors, "\r\n")
};
});
}
@@ -1012,9 +983,23 @@ namespace ts {
public getDefaultCompilationSettings(): string {
return this.forwardJSONCall(
"getDefaultCompilationSettings()",
() => {
return getDefaultCompilerOptions();
});
() => getDefaultCompilerOptions()
);
}
public discoverTypings(discoverTypingsJson: string): string {
const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
return this.forwardJSONCall("discoverTypings()", () => {
const info = <DiscoverTypingsInfo>JSON.parse(discoverTypingsJson);
return ts.JsTyping.discoverTypings(
this.host,
info.fileNames,
toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName),
toPath(info.safeListPath, info.safeListPath, getCanonicalFileName),
info.packageNameToTypingLocation,
info.typingOptions,
info.compilerOptions);
});
}
}
@@ -1032,10 +1017,10 @@ namespace ts {
public createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim {
try {
if (this.documentRegistry === undefined) {
this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory());
}
var hostAdapter = new LanguageServiceShimHostAdapter(host);
var languageService = createLanguageService(hostAdapter, this.documentRegistry);
const hostAdapter = new LanguageServiceShimHostAdapter(host);
const languageService = createLanguageService(hostAdapter, this.documentRegistry);
return new LanguageServiceShimObject(this, host, languageService);
}
catch (err) {
@@ -1056,7 +1041,7 @@ namespace ts {
public createCoreServicesShim(host: CoreServicesShimHost): CoreServicesShim {
try {
var adapter = new CoreServicesShimHostAdapter(host);
const adapter = new CoreServicesShimHostAdapter(host);
return new CoreServicesShimObject(this, <Logger>host, adapter);
}
catch (err) {
@@ -1068,7 +1053,7 @@ namespace ts {
public close(): void {
// Forget all the registered shims
this._shims = [];
this.documentRegistry = createDocumentRegistry();
this.documentRegistry = undefined;
}
public registerShim(shim: Shim): void {
@@ -1076,7 +1061,7 @@ namespace ts {
}
public unregisterShim(shim: Shim): void {
for (var i = 0, n = this._shims.length; i < n; i++) {
for (let i = 0, n = this._shims.length; i < n; i++) {
if (this._shims[i] === shim) {
delete this._shims[i];
return;
@@ -1095,12 +1080,21 @@ namespace ts {
}
}
/* tslint:enable:no-in-operator */
/* tslint:enable:no-null */
/// TODO: this is used by VS, clean this up on both sides of the interface
/* @internal */
module TypeScript.Services {
export var TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
namespace TypeScript.Services {
export const TypeScriptServicesFactory = ts.TypeScriptServicesFactory;
}
/* tslint:disable:no-unused-variable */
// 'toolsVersion' gets consumed by the managed side, so it's not unused.
// TODO: it should be moved into a namespace though.
/* @internal */
const toolsVersion = "1.6";
const toolsVersion = "1.9";
/* tslint:enable:no-unused-variable */
+4 -4
View File
@@ -50,7 +50,7 @@ namespace ts.SignatureHelp {
// case TypeScript.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
// stack++;
// // Intentaion fall through
// // Intentional fall through
// case TypeScript.SyntaxKind.GreaterThanToken:
// stack++;
// break;
@@ -76,7 +76,7 @@ namespace ts.SignatureHelp {
// break;
// case TypeScript.SyntaxKind.EqualsGreaterThanToken:
// // This can be a function type or a constructor type. In either case, we want to skip the function defintion
// // This can be a function type or a constructor type. In either case, we want to skip the function definition
// token = previousToken(token, /*includeSkippedTokens*/ true);
// if (token && token.kind() === TypeScript.SyntaxKind.CloseParenToken) {
@@ -99,7 +99,7 @@ namespace ts.SignatureHelp {
// }
// }
// else {
// // This is not a funtion type. exit the main loop
// // This is not a function type. exit the main loop
// break whileLoop;
// }
@@ -204,7 +204,7 @@ namespace ts.SignatureHelp {
if (!candidates.length) {
// We didn't have any sig help items produced by the TS compiler. If this is a JS
// file, then see if we can figure out anything better.
if (isJavaScript(sourceFile.fileName)) {
if (isSourceFileJavaScript(sourceFile)) {
return createJavaScriptSignatureHelpItems(argumentInfo);
}

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