Merge branch 'transforms-merge' into transforms-visitEachChildPerf

This commit is contained in:
Ron Buckton committed 2016-05-25 14:15:20 -07:00
commit 48bd560dd1
968 files changed
+116781 -32942

No files matched your search

+5 -2
View File
@@ -6,6 +6,8 @@ tests/cases/perf/*
!tests/cases/webharness/compilerToString.js
test-args.txt
~*.docx
\#*\#
.\#*
tests/baselines/local/*
tests/baselines/local.old/*
tests/services/baselines/local/*
@@ -46,5 +48,6 @@ coverage/
internal/
**/.DS_Store
.settings
.vscode/*
!.vscode/tasks.json
**/.vs
**/.vscode
!**/.vscode/tasks.json
+3 -1
View File
@@ -1,10 +1,12 @@
built
doc
internal
issue_template.md
lib/README.md
pull_request_template.md
scripts
src
tests
internal
tslint.json
Jakefile.js
.editorconfig
+73 -46
View File
@@ -202,7 +202,7 @@ var librarySourceMap = [
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"] },
{ target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
];
];
var es2015LibrarySources = [
"es2015.core.d.ts",
"es2015.collection.d.ts",
@@ -212,7 +212,7 @@ var es2015LibrarySources = [
"es2015.proxy.d.ts",
"es2015.reflect.d.ts",
"es2015.symbol.d.ts",
"es2015.symbol.wellknown.d.ts",
"es2015.symbol.wellknown.d.ts"
];
var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
@@ -221,28 +221,35 @@ var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
var es2016LibrarySource = [ "es2016.array.include.d.ts" ];
var es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
})
});
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]
var es2017LibrarySource = ["es2017.object.d.ts"];
var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"];
var librarySourceMap = [
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"], },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"], },
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"] },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"] },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"] },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"] },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
{ target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] },
{ target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] },
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources), },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources), },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap);
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap);
var libraryTargets = librarySourceMap.map(function (f) {
return path.join(builtLocalDirectory, f.target);
@@ -282,7 +289,7 @@ function concatenateFiles(destinationFile, sourceFiles) {
}
var useDebugMode = true;
var host = (process.env.TYPESCRIPT_HOST || process.env.host || "node");
var host = process.env.TYPESCRIPT_HOST || process.env.host || "node";
var compilerFilename = "tsc.js";
var LKGCompiler = path.join(LKGDirectory, compilerFilename);
var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
@@ -560,9 +567,10 @@ compileFile(servicesFileInBrowserTest, servicesSources,[builtLocalDirectory, cop
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
var lsslFile = path.join(builtLocalDirectory, "tslssl.js");
var tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js");
var tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
compileFile(
lsslFile,
tsserverLibraryFile,
languageServiceLibrarySources,
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
/*prefixes*/ [copyright],
@@ -571,7 +579,7 @@ compileFile(
// Local target to build the language service server library
desc("Builds language service server library");
task("lssl", [lsslFile]);
task("lssl", [tsserverLibraryFile, tsserverLibraryDefinitionFile]);
// Local target to build the compiler and services
desc("Builds the full compiler and services");
@@ -630,8 +638,8 @@ task("generate-spec", [specMd]);
// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory
desc("Makes a new LKG out of the built js files");
task("LKG", ["clean", "release", "local"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile].concat(libraryTargets);
task("LKG", ["clean", "release", "local", "lssl"].concat(libraryTargets), function() {
var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets);
var missingFiles = expectedFiles.filter(function (f) {
return !fs.existsSync(f);
});
@@ -891,6 +899,7 @@ function runConsoleTests(defaultReporter, defaultSubsets, dirty) {
colors = process.env.colors || process.env.color;
colors = colors ? ' --no-colors ' : ' --colors ';
reporter = process.env.reporter || process.env.r || defaultReporter;
var lintFlag = process.env.lint !== 'false';
// timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
@@ -903,22 +912,41 @@ function runConsoleTests(defaultReporter, defaultSubsets, dirty) {
subsetRegexes = subsets.map(function (sub) { return "^" + sub + ".*$"; });
subsetRegexes.push("^(?!" + subsets.join("|") + ").*$");
}
var counter = subsetRegexes.length;
var errorStatus;
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 () {
function finish(status) {
counter--;
// save first error status
if (status !== undefined && errorStatus === undefined) {
errorStatus = status;
}
deleteTemporaryProjectOutput();
if (i === 0 && !dirty) {
var lint = jake.Task['lint'];
lint.addListener('complete', function () {
if (counter !== 0 || errorStatus === undefined) {
// run linter when last worker is finished
if (lintFlag && counter === 0 && !dirty) {
var lint = jake.Task['lint'];
lint.addListener('complete', function () {
complete();
});
lint.invoke();
}
else {
complete();
});
lint.invoke();
}
}
else {
complete();
fail("Process exited with code " + status);
}
}
exec(cmd, function () {
finish();
}, function(e, status) {
finish(status);
});
});
}
@@ -929,7 +957,7 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio
runConsoleTests('min', ['compiler', 'conformance', 'Projects', 'fourslash']);
}, {async: true});
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false.");
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false lint=true.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function() {
runConsoleTests('mocha-fivemat-progress-reporter', []);
}, {async: true});
@@ -949,8 +977,8 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
}, { async: true });
// Browser tests
var nodeServerOutFile = 'tests/webTestServer.js';
var nodeServerInFile = 'tests/webTestServer.ts';
var nodeServerOutFile = "tests/webTestServer.js";
var nodeServerInFile = "tests/webTestServer.ts";
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true });
desc("Runs browserify on run.js to produce a file suitable for running tests in the browser");
@@ -1145,31 +1173,30 @@ 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(harnessSources)
// Other harness sources
.concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f) }))
.concat(serverCoreSources)
.concat(tslintRulesFiles)
.concat(servicesLintTargets);
.concat(servicesSources);
desc("Runs tslint on the compiler sources");
desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex");
task("lint", ["build-rules"], function() {
var lintOptions = getLinterOptions();
var failed = 0;
var fileMatcher = RegExp(process.env.f || process.env.file || process.env.files || "");
var done = {};
for (var i in lintTargets) {
var result = lintFile(lintOptions, lintTargets[i]);
if (result.failureCount > 0) {
console.log(result.output);
failed += result.failureCount;
var target = lintTargets[i];
if (!done[target] && fileMatcher.test(target)) {
var result = lintFile(lintOptions, target);
if (result.failureCount > 0) {
console.log(result.output);
failed += result.failureCount;
}
done[target] = true;
}
}
if (failed > 0) {
+1283 -1285
View File
File diff suppressed because it is too large. Load diff
+477 -479
View File
File diff suppressed because it is too large. Load diff
+8 -17
View File
@@ -20,13 +20,13 @@ interface Map<K, V> {
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
set(key: K, value?: V): this;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(entries?: [K, V][]): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
@@ -36,51 +36,42 @@ interface WeakMap<K, V> {
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
set(key: K, value?: V): this;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
new <T>(values?: T[]): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
new <T>(values?: T[]): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
+80 -67
View File
@@ -17,48 +17,48 @@ and limitations under the License.
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: T) => boolean, thisArg?: any): number;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
fill(value: T, start?: number, end?: number): this;
/**
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
copyWithin(target: number, start: number, end?: number): this;
}
interface ArrayConstructor {
@@ -130,7 +130,7 @@ interface Math {
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
@@ -206,14 +206,14 @@ interface Math {
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 10‍−‍16.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
@@ -226,7 +226,7 @@ interface NumberConstructor {
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
@@ -239,30 +239,30 @@ interface NumberConstructor {
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n − 1 are both exactly representable as
* a Number value.
/**
* The value of the smallest integer n such that n and n − 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
@@ -271,12 +271,12 @@ interface NumberConstructor {
interface Object {
/**
* Determines whether an object has a property with the specified name.
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
@@ -285,7 +285,7 @@ interface Object {
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
@@ -293,7 +293,7 @@ interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
@@ -302,7 +302,7 @@ interface ObjectConstructor {
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
@@ -312,7 +312,7 @@ interface ObjectConstructor {
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
@@ -340,17 +340,17 @@ interface ObjectConstructor {
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
@@ -374,47 +374,60 @@ interface RegExp {
*/
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.
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface RegExpConstructor {
new (pattern: RegExp, flags?: string): RegExp;
(pattern: RegExp, flags?: string): RegExp;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition – length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
@@ -422,15 +435,15 @@ interface String {
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
@@ -490,10 +503,10 @@ interface StringConstructor {
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
}
+55 -3
View File
@@ -16,9 +16,17 @@ and limitations under the License.
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
}
interface IteratorResult<T> {
done: boolean;
value?: T;
value: T;
}
interface Iterator<T> {
@@ -27,11 +35,18 @@ interface Iterator<T> {
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> { }
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -64,7 +79,13 @@ interface ArrayConstructor {
from<T>(iterable: Iterable<T>): Array<T>;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Map<K, V> {
[Symbol.iterator](): IterableIterator<[K,V]>;
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
@@ -80,6 +101,23 @@ interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Set<T> {
[Symbol.iterator](): IterableIterator<T>;
entries(): IterableIterator<[T, T]>;
keys(): IterableIterator<T>;
values(): IterableIterator<T>;
}
interface SetConstructor {
new <T>(iterable: Iterable<T>): Set<T>;
}
interface WeakSet<T> { }
interface WeakSetConstructor {
new <T>(iterable: Iterable<T>): WeakSet<T>;
}
interface Promise<T> { }
interface PromiseConstructor {
@@ -104,11 +142,17 @@ declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -140,6 +184,7 @@ interface Int8ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -171,6 +216,7 @@ interface Uint8ArrayConstructor {
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -205,6 +251,7 @@ interface Uint8ClampedArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -238,6 +285,7 @@ interface Int16ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -269,6 +317,7 @@ interface Uint16ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -300,6 +349,7 @@ interface Int32ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -331,6 +381,7 @@ interface Uint32ArrayConstructor {
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -362,6 +413,7 @@ interface Float32ArrayConstructor {
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
+8 -37
View File
@@ -29,12 +29,6 @@ interface SymbolConstructor {
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
@@ -89,9 +83,6 @@ interface Symbol {
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
@@ -132,7 +123,6 @@ interface Date {
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
@@ -140,6 +130,14 @@ interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface Set<T> {
readonly [Symbol.toStringTag]: "Set";
}
interface WeakSet<T> {
readonly [Symbol.toStringTag]: "WeakSet";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
@@ -159,21 +157,6 @@ interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
@@ -239,9 +222,6 @@ interface RegExpConstructor {
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
@@ -295,7 +275,6 @@ interface DataView {
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
@@ -304,7 +283,6 @@ interface Int8Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
@@ -313,7 +291,6 @@ interface Uint8Array {
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
@@ -322,7 +299,6 @@ interface Uint8ClampedArray {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
@@ -331,7 +307,6 @@ interface Int16Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
@@ -340,7 +315,6 @@ interface Uint16Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
@@ -349,7 +323,6 @@ interface Int32Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
@@ -358,7 +331,6 @@ interface Uint32Array {
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
@@ -367,6 +339,5 @@ interface Float32Array {
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}
+18
View File
@@ -0,0 +1,18 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
+30
View File
@@ -0,0 +1,30 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T }): T[];
values(o: any): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
entries(o: any): [string, any][];
}
+806 -806
View File
File diff suppressed because it is too large. Load diff
+1449 -1410
View File
File diff suppressed because it is too large. Load diff
File renamed without changes.
+18 -7
View File
@@ -24,6 +24,16 @@ interface EventInit {
cancelable?: boolean;
}
interface IDBIndexParameters {
multiEntry?: boolean;
unique?: boolean;
}
interface IDBObjectStoreParameters {
autoIncrement?: boolean;
keyPath?: IDBKeyPath;
}
interface EventListener {
(evt: Event): void;
}
@@ -100,12 +110,12 @@ declare var Console: {
interface Coordinates {
readonly accuracy: number;
readonly altitude: number;
readonly altitudeAccuracy: number;
readonly heading: number;
readonly altitude: number | null;
readonly altitudeAccuracy: number | null;
readonly heading: number | null;
readonly latitude: number;
readonly longitude: number;
readonly speed: number;
readonly speed: number | null;
}
declare var Coordinates: {
@@ -192,7 +202,7 @@ declare var DOMException: {
interface DOMStringList {
readonly length: number;
contains(str: string): boolean;
item(index: number): string;
item(index: number): string | null;
[index: number]: string;
}
@@ -475,7 +485,7 @@ declare var IDBTransaction: {
}
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number;
readonly newVersion: number | null;
readonly oldVersion: number;
}
@@ -728,7 +738,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
withCredentials: boolean;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string;
getResponseHeader(header: string): string | null;
msCachingEnabled(): boolean;
open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
overrideMimeType(mime: string): void;
@@ -1007,4 +1017,5 @@ declare var console: Console;
declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type IDBKeyPath = string;
type IDBValidKey = number | string | Date | IDBArrayKey;
+4304 -3482
View File
File diff suppressed because it is too large. Load diff
+5897 -4657
View File
File diff suppressed because it is too large. Load diff
+8618
View File
File diff suppressed because it is too large. Load diff
+51467
View File
File diff suppressed because it is too large. Load diff
+216 -165
View File
@@ -160,173 +160,174 @@ declare namespace ts {
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
ReadonlyKeyword = 127,
RequireKeyword = 128,
NumberKeyword = 129,
SetKeyword = 130,
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
NeverKeyword = 127,
ReadonlyKeyword = 128,
RequireKeyword = 129,
NumberKeyword = 130,
SetKeyword = 131,
StringKeyword = 132,
SymbolKeyword = 133,
TypeKeyword = 134,
UndefinedKeyword = 135,
FromKeyword = 136,
GlobalKeyword = 137,
OfKeyword = 138,
QualifiedName = 139,
ComputedPropertyName = 140,
TypeParameter = 141,
Parameter = 142,
Decorator = 143,
PropertySignature = 144,
PropertyDeclaration = 145,
MethodSignature = 146,
MethodDeclaration = 147,
Constructor = 148,
GetAccessor = 149,
SetAccessor = 150,
CallSignature = 151,
ConstructSignature = 152,
IndexSignature = 153,
TypePredicate = 154,
TypeReference = 155,
FunctionType = 156,
ConstructorType = 157,
TypeQuery = 158,
TypeLiteral = 159,
ArrayType = 160,
TupleType = 161,
UnionType = 162,
IntersectionType = 163,
ParenthesizedType = 164,
ThisType = 165,
StringLiteralType = 166,
ObjectBindingPattern = 167,
ArrayBindingPattern = 168,
BindingElement = 169,
ArrayLiteralExpression = 170,
ObjectLiteralExpression = 171,
PropertyAccessExpression = 172,
ElementAccessExpression = 173,
CallExpression = 174,
NewExpression = 175,
TaggedTemplateExpression = 176,
TypeAssertionExpression = 177,
ParenthesizedExpression = 178,
FunctionExpression = 179,
ArrowFunction = 180,
DeleteExpression = 181,
TypeOfExpression = 182,
VoidExpression = 183,
AwaitExpression = 184,
PrefixUnaryExpression = 185,
PostfixUnaryExpression = 186,
BinaryExpression = 187,
ConditionalExpression = 188,
TemplateExpression = 189,
YieldExpression = 190,
SpreadElementExpression = 191,
ClassExpression = 192,
OmittedExpression = 193,
ExpressionWithTypeArguments = 194,
AsExpression = 195,
NonNullExpression = 196,
TemplateSpan = 197,
SemicolonClassElement = 198,
Block = 199,
VariableStatement = 200,
EmptyStatement = 201,
ExpressionStatement = 202,
IfStatement = 203,
DoStatement = 204,
WhileStatement = 205,
ForStatement = 206,
ForInStatement = 207,
ForOfStatement = 208,
ContinueStatement = 209,
BreakStatement = 210,
ReturnStatement = 211,
WithStatement = 212,
SwitchStatement = 213,
LabeledStatement = 214,
ThrowStatement = 215,
TryStatement = 216,
DebuggerStatement = 217,
VariableDeclaration = 218,
VariableDeclarationList = 219,
FunctionDeclaration = 220,
ClassDeclaration = 221,
InterfaceDeclaration = 222,
TypeAliasDeclaration = 223,
EnumDeclaration = 224,
ModuleDeclaration = 225,
ModuleBlock = 226,
CaseBlock = 227,
GlobalModuleExportDeclaration = 228,
ImportEqualsDeclaration = 229,
ImportDeclaration = 230,
ImportClause = 231,
NamespaceImport = 232,
NamedImports = 233,
ImportSpecifier = 234,
ExportAssignment = 235,
ExportDeclaration = 236,
NamedExports = 237,
ExportSpecifier = 238,
MissingDeclaration = 239,
ExternalModuleReference = 240,
JsxElement = 241,
JsxSelfClosingElement = 242,
JsxOpeningElement = 243,
JsxText = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
JsxExpression = 248,
CaseClause = 249,
DefaultClause = 250,
HeritageClause = 251,
CatchClause = 252,
PropertyAssignment = 253,
ShorthandPropertyAssignment = 254,
EnumMember = 255,
SourceFile = 256,
JSDocTypeExpression = 257,
JSDocAllType = 258,
JSDocUnknownType = 259,
JSDocArrayType = 260,
JSDocUnionType = 261,
JSDocTupleType = 262,
JSDocNullableType = 263,
JSDocNonNullableType = 264,
JSDocRecordType = 265,
JSDocRecordMember = 266,
JSDocTypeReference = 267,
JSDocOptionalType = 268,
JSDocFunctionType = 269,
JSDocVariadicType = 270,
JSDocConstructorType = 271,
JSDocThisType = 272,
JSDocComment = 273,
JSDocTag = 274,
JSDocParameterTag = 275,
JSDocReturnTag = 276,
JSDocTypeTag = 277,
JSDocTemplateTag = 278,
SyntaxList = 279,
Count = 280,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 137,
LastKeyword = 138,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstTypeNode = 154,
LastTypeNode = 166,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 137,
LastToken = 138,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -335,7 +336,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 138,
FirstNode = 139,
}
enum NodeFlags {
None = 0,
@@ -370,8 +371,9 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
Modifier = 1023,
AccessibilityModifier = 28,
ParameterPropertyModifier = 92,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
@@ -405,9 +407,6 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@@ -1047,6 +1046,34 @@ declare namespace ts {
postParameterName?: Identifier;
isBracketed: boolean;
}
enum FlowFlags {
Unreachable = 1,
Start = 2,
BranchLabel = 4,
LoopLabel = 8,
Assignment = 16,
TrueCondition = 32,
FalseCondition = 64,
Referenced = 128,
Shared = 256,
Label = 12,
Condition = 96,
}
interface FlowNode {
flags: FlowFlags;
id?: number;
}
interface FlowLabel extends FlowNode {
antecedents: FlowNode[];
}
interface FlowAssignment extends FlowNode {
node: Expression | VariableDeclaration | BindingElement;
antecedent: FlowNode;
}
interface FlowCondition extends FlowNode {
expression: Expression;
antecedent: FlowNode;
}
interface AmdDependency {
path: string;
name: string;
@@ -1077,6 +1104,7 @@ declare namespace ts {
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile;
getSourceFileByPath(path: Path): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
@@ -1169,11 +1197,13 @@ declare namespace ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getNonNullableType(type: Type): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@@ -1233,6 +1263,7 @@ declare namespace ts {
WriteTypeArgumentsOfSignature = 32,
InElementType = 64,
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
}
enum SymbolFormatFlags {
None = 0,
@@ -1356,11 +1387,13 @@ declare namespace ts {
ESSymbol = 16777216,
ThisType = 33554432,
ObjectLiteralPatternWithComputedProperties = 67108864,
Never = 134217728,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
UnionOrIntersection = 49152,
StructuredType = 130048,
Narrowable = 97793,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -1525,13 +1558,13 @@ declare namespace ts {
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
[option: string]: CompilerOptionsValue | undefined;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
[option: string]: string[] | boolean | undefined;
}
interface DiscoverTypingsInfo {
fileNames: string[];
@@ -1585,6 +1618,7 @@ declare namespace ts {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
raw?: any;
errors: Diagnostic[];
}
interface ModuleResolutionHost {
@@ -1592,6 +1626,7 @@ declare namespace ts {
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
realpath?(path: string): string;
}
interface ResolvedModule {
resolvedFileName: string;
@@ -1611,6 +1646,7 @@ declare namespace ts {
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
@@ -1637,6 +1673,11 @@ declare namespace ts {
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface WatchedFile {
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
interface System {
args: string[];
newLine: string;
@@ -1657,6 +1698,7 @@ declare namespace ts {
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
}
interface FileWatcher {
close(): void;
@@ -1843,6 +1885,7 @@ declare namespace ts {
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
getNonNullableType(): Type;
}
interface Signature {
getDeclaration(): SignatureDeclaration;
@@ -1898,7 +1941,7 @@ declare namespace ts {
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -1951,6 +1994,7 @@ declare namespace ts {
getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -2266,6 +2310,7 @@ declare namespace ts {
* in the registry and a new one was created.
*/
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -2279,6 +2324,8 @@ declare namespace ts {
* @param version Current version of the file.
*/
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -2289,8 +2336,12 @@ declare namespace ts {
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
reportStats(): string;
}
type DocumentRegistryBucketKey = string & {
__bucketKey: any;
};
namespace ScriptElementKind {
const unknown: string;
const warning: string;
+6353 -5102
View File
File diff suppressed because it is too large. Load diff
+216 -165
View File
@@ -160,173 +160,174 @@ declare namespace ts {
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
ReadonlyKeyword = 127,
RequireKeyword = 128,
NumberKeyword = 129,
SetKeyword = 130,
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
NeverKeyword = 127,
ReadonlyKeyword = 128,
RequireKeyword = 129,
NumberKeyword = 130,
SetKeyword = 131,
StringKeyword = 132,
SymbolKeyword = 133,
TypeKeyword = 134,
UndefinedKeyword = 135,
FromKeyword = 136,
GlobalKeyword = 137,
OfKeyword = 138,
QualifiedName = 139,
ComputedPropertyName = 140,
TypeParameter = 141,
Parameter = 142,
Decorator = 143,
PropertySignature = 144,
PropertyDeclaration = 145,
MethodSignature = 146,
MethodDeclaration = 147,
Constructor = 148,
GetAccessor = 149,
SetAccessor = 150,
CallSignature = 151,
ConstructSignature = 152,
IndexSignature = 153,
TypePredicate = 154,
TypeReference = 155,
FunctionType = 156,
ConstructorType = 157,
TypeQuery = 158,
TypeLiteral = 159,
ArrayType = 160,
TupleType = 161,
UnionType = 162,
IntersectionType = 163,
ParenthesizedType = 164,
ThisType = 165,
StringLiteralType = 166,
ObjectBindingPattern = 167,
ArrayBindingPattern = 168,
BindingElement = 169,
ArrayLiteralExpression = 170,
ObjectLiteralExpression = 171,
PropertyAccessExpression = 172,
ElementAccessExpression = 173,
CallExpression = 174,
NewExpression = 175,
TaggedTemplateExpression = 176,
TypeAssertionExpression = 177,
ParenthesizedExpression = 178,
FunctionExpression = 179,
ArrowFunction = 180,
DeleteExpression = 181,
TypeOfExpression = 182,
VoidExpression = 183,
AwaitExpression = 184,
PrefixUnaryExpression = 185,
PostfixUnaryExpression = 186,
BinaryExpression = 187,
ConditionalExpression = 188,
TemplateExpression = 189,
YieldExpression = 190,
SpreadElementExpression = 191,
ClassExpression = 192,
OmittedExpression = 193,
ExpressionWithTypeArguments = 194,
AsExpression = 195,
NonNullExpression = 196,
TemplateSpan = 197,
SemicolonClassElement = 198,
Block = 199,
VariableStatement = 200,
EmptyStatement = 201,
ExpressionStatement = 202,
IfStatement = 203,
DoStatement = 204,
WhileStatement = 205,
ForStatement = 206,
ForInStatement = 207,
ForOfStatement = 208,
ContinueStatement = 209,
BreakStatement = 210,
ReturnStatement = 211,
WithStatement = 212,
SwitchStatement = 213,
LabeledStatement = 214,
ThrowStatement = 215,
TryStatement = 216,
DebuggerStatement = 217,
VariableDeclaration = 218,
VariableDeclarationList = 219,
FunctionDeclaration = 220,
ClassDeclaration = 221,
InterfaceDeclaration = 222,
TypeAliasDeclaration = 223,
EnumDeclaration = 224,
ModuleDeclaration = 225,
ModuleBlock = 226,
CaseBlock = 227,
GlobalModuleExportDeclaration = 228,
ImportEqualsDeclaration = 229,
ImportDeclaration = 230,
ImportClause = 231,
NamespaceImport = 232,
NamedImports = 233,
ImportSpecifier = 234,
ExportAssignment = 235,
ExportDeclaration = 236,
NamedExports = 237,
ExportSpecifier = 238,
MissingDeclaration = 239,
ExternalModuleReference = 240,
JsxElement = 241,
JsxSelfClosingElement = 242,
JsxOpeningElement = 243,
JsxText = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
JsxExpression = 248,
CaseClause = 249,
DefaultClause = 250,
HeritageClause = 251,
CatchClause = 252,
PropertyAssignment = 253,
ShorthandPropertyAssignment = 254,
EnumMember = 255,
SourceFile = 256,
JSDocTypeExpression = 257,
JSDocAllType = 258,
JSDocUnknownType = 259,
JSDocArrayType = 260,
JSDocUnionType = 261,
JSDocTupleType = 262,
JSDocNullableType = 263,
JSDocNonNullableType = 264,
JSDocRecordType = 265,
JSDocRecordMember = 266,
JSDocTypeReference = 267,
JSDocOptionalType = 268,
JSDocFunctionType = 269,
JSDocVariadicType = 270,
JSDocConstructorType = 271,
JSDocThisType = 272,
JSDocComment = 273,
JSDocTag = 274,
JSDocParameterTag = 275,
JSDocReturnTag = 276,
JSDocTypeTag = 277,
JSDocTemplateTag = 278,
SyntaxList = 279,
Count = 280,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 137,
LastKeyword = 138,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstTypeNode = 154,
LastTypeNode = 166,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 137,
LastToken = 138,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@@ -335,7 +336,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 138,
FirstNode = 139,
}
enum NodeFlags {
None = 0,
@@ -370,8 +371,9 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
Modifier = 1023,
AccessibilityModifier = 28,
ParameterPropertyModifier = 92,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
@@ -405,9 +407,6 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@@ -1047,6 +1046,34 @@ declare namespace ts {
postParameterName?: Identifier;
isBracketed: boolean;
}
enum FlowFlags {
Unreachable = 1,
Start = 2,
BranchLabel = 4,
LoopLabel = 8,
Assignment = 16,
TrueCondition = 32,
FalseCondition = 64,
Referenced = 128,
Shared = 256,
Label = 12,
Condition = 96,
}
interface FlowNode {
flags: FlowFlags;
id?: number;
}
interface FlowLabel extends FlowNode {
antecedents: FlowNode[];
}
interface FlowAssignment extends FlowNode {
node: Expression | VariableDeclaration | BindingElement;
antecedent: FlowNode;
}
interface FlowCondition extends FlowNode {
expression: Expression;
antecedent: FlowNode;
}
interface AmdDependency {
path: string;
name: string;
@@ -1077,6 +1104,7 @@ declare namespace ts {
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile;
getSourceFileByPath(path: Path): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
@@ -1169,11 +1197,13 @@ declare namespace ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getNonNullableType(type: Type): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@@ -1233,6 +1263,7 @@ declare namespace ts {
WriteTypeArgumentsOfSignature = 32,
InElementType = 64,
UseFullyQualifiedType = 128,
InFirstTypeArgument = 256,
}
enum SymbolFormatFlags {
None = 0,
@@ -1356,11 +1387,13 @@ declare namespace ts {
ESSymbol = 16777216,
ThisType = 33554432,
ObjectLiteralPatternWithComputedProperties = 67108864,
Never = 134217728,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
UnionOrIntersection = 49152,
StructuredType = 130048,
Narrowable = 97793,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -1525,13 +1558,13 @@ declare namespace ts {
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
[option: string]: CompilerOptionsValue | undefined;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
[option: string]: string[] | boolean | undefined;
}
interface DiscoverTypingsInfo {
fileNames: string[];
@@ -1585,6 +1618,7 @@ declare namespace ts {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
raw?: any;
errors: Diagnostic[];
}
interface ModuleResolutionHost {
@@ -1592,6 +1626,7 @@ declare namespace ts {
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
realpath?(path: string): string;
}
interface ResolvedModule {
resolvedFileName: string;
@@ -1611,6 +1646,7 @@ declare namespace ts {
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
@@ -1637,6 +1673,11 @@ declare namespace ts {
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface WatchedFile {
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
interface System {
args: string[];
newLine: string;
@@ -1657,6 +1698,7 @@ declare namespace ts {
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
}
interface FileWatcher {
close(): void;
@@ -1843,6 +1885,7 @@ declare namespace ts {
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
getNonNullableType(): Type;
}
interface Signature {
getDeclaration(): SignatureDeclaration;
@@ -1898,7 +1941,7 @@ declare namespace ts {
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -1951,6 +1994,7 @@ declare namespace ts {
getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -2266,6 +2310,7 @@ declare namespace ts {
* in the registry and a new one was created.
*/
acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -2279,6 +2324,8 @@ declare namespace ts {
* @param version Current version of the file.
*/
updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -2289,8 +2336,12 @@ declare namespace ts {
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
reportStats(): string;
}
type DocumentRegistryBucketKey = string & {
__bucketKey: any;
};
namespace ScriptElementKind {
const unknown: string;
const warning: string;
+6353 -5102
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -45,6 +45,7 @@
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "jake local",
"build:tests": "jake tests",
"start": "node lib/tsc",
"clean": "jake clean",
"jake": "jake",
"lint": "jake lint",
+1 -1
View File
@@ -67,7 +67,7 @@ function getNightlyVersionString(versionString: string): string {
const now = new Date();
const timeStr = now.toISOString().replace(/:|T|\.|-/g, "").slice(0, 8);
return `${versionString}-dev.${timeStr}`;
return `${versionString}-dev.${timeStr}-1.0`;
}
main();
+9 -2
View File
@@ -28,8 +28,15 @@ class IncrementDecrementWalker extends Lint.RuleWalker {
}
visitIncrementDecrement(node: ts.UnaryExpression) {
if (node.parent && (node.parent.kind === ts.SyntaxKind.ExpressionStatement ||
node.parent.kind === ts.SyntaxKind.ForStatement)) {
if (node.parent && (
// Can be a statement
node.parent.kind === ts.SyntaxKind.ExpressionStatement ||
// Can be directly in a for-statement
node.parent.kind === ts.SyntaxKind.ForStatement ||
// Can be in a comma operator in a for statement (`for (let a = 0, b = 10; a < b; a++, b--)`)
node.parent.kind === ts.SyntaxKind.BinaryExpression &&
(<ts.BinaryExpression>node.parent).operatorToken.kind === ts.SyntaxKind.CommaToken &&
node.parent.parent.kind === ts.SyntaxKind.ForStatement)) {
return;
}
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.POSTFIX_FAILURE_STRING));
+588 -302
View File
File diff suppressed because it is too large. Load diff
+1378 -911
View File
File diff suppressed because it is too large. Load diff
+33 -13
View File
@@ -42,6 +42,11 @@ namespace ts {
type: "boolean",
description: Diagnostics.Print_this_message,
},
{
name: "help",
shortName: "?",
type: "boolean"
},
{
name: "init",
type: "boolean",
@@ -144,11 +149,16 @@ namespace ts {
name: "skipDefaultLibCheck",
type: "boolean",
},
{
name: "skipLibCheck",
type: "boolean",
description: Diagnostics.Skip_type_checking_of_declaration_files,
},
{
name: "out",
type: "string",
isFilePath: false, // This is intentionally broken to support compatability with existing tsconfig files
// for correct behaviour, please use outFile
// for correct behaviour, please use outFile
paramType: Diagnostics.FILE,
},
{
@@ -386,6 +396,7 @@ namespace ts {
"es2015": "lib.es2015.d.ts",
"es7": "lib.es2016.d.ts",
"es2016": "lib.es2016.d.ts",
"es2017": "lib.es2017.d.ts",
// Host only
"dom": "lib.dom.d.ts",
"webworker": "lib.webworker.d.ts",
@@ -400,7 +411,8 @@ namespace ts {
"es2015.reflect": "lib.es2015.reflect.d.ts",
"es2015.symbol": "lib.es2015.symbol.d.ts",
"es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts",
"es2016.array.include": "lib.es2016.array.include.d.ts"
"es2016.array.include": "lib.es2016.array.include.d.ts",
"es2017.object": "lib.es2017.object.d.ts"
},
},
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
@@ -475,7 +487,7 @@ namespace ts {
/* @internal */
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = (value || "").trim().toLowerCase();
const key = trimString((value || "")).toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
return map[key];
@@ -487,7 +499,7 @@ namespace ts {
/* @internal */
export function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] {
const values = (value || "").trim().split(",");
const values = trimString((value || "")).split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
@@ -612,7 +624,7 @@ namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string, readFile: (path: string) => string): { config?: any; error?: Diagnostic } {
export function readConfigFile(fileName: string, readFile: (path: string) => string): { config?: any; error?: Diagnostic } {
let text = "";
try {
text = readFile(fileName);
@@ -663,6 +675,9 @@ namespace ts {
return output;
}
// Skip over any minified JavaScript files (ending in ".min.js")
// Skip over dotted files and folders as well
const IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/;
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
@@ -675,6 +690,7 @@ namespace ts {
const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const options = extend(existingOptions, compilerOptions);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
options.configFilePath = configFileName;
const fileNames = getFileNames(errors);
@@ -683,6 +699,7 @@ namespace ts {
options,
fileNames,
typingOptions,
raw: json,
errors
};
@@ -705,11 +722,11 @@ namespace ts {
}
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 = ["node_modules", "bower_components", "jspm_packages"];
}
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
}
exclude = map(exclude, normalizeSlashes);
@@ -726,8 +743,7 @@ namespace ts {
continue;
}
// Skip over any minified JavaScript files (ending in ".min.js")
if (/\.min\.js$/.test(fileName)) {
if (IgnoreFileNamePattern.test(fileName)) {
continue;
}
@@ -786,7 +802,7 @@ namespace ts {
defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
if (!jsonOptions) {
return ;
return;
}
const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name);
@@ -840,4 +856,8 @@ namespace ts {
function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: any[], basePath: string, errors: Diagnostic[]): any[] {
return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v);
}
function trimString(s: string) {
return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
}
}
+4 -4
View File
@@ -108,10 +108,10 @@ namespace ts {
return true;
}
export function contains<T>(array: T[], value: T): boolean {
export function contains<T>(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean {
if (array) {
for (const v of array) {
if (v === value) {
if (areEqual ? areEqual(v, value) : v === value) {
return true;
}
}
@@ -290,12 +290,12 @@ namespace ts {
return [...array1, ...array2];
}
export function deduplicate<T>(array: T[]): T[] {
export function deduplicate<T>(array: T[], areEqual?: (a: T, b: T) => boolean): T[] {
let result: T[];
if (array) {
result = [];
for (const item of array) {
if (!contains(result, item)) {
if (!contains(result, item, areEqual)) {
result.push(item);
}
}
+18 -3
View File
@@ -395,6 +395,7 @@ namespace ts {
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.StringLiteralType:
return writeTextOfNode(currentText, type);
@@ -1052,7 +1053,7 @@ namespace ts {
function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) {
if (constructorDeclaration) {
forEach(constructorDeclaration.parameters, param => {
if (hasModifier(param, ModifierFlags.AccessibilityModifier)) {
if (hasModifier(param, ModifierFlags.ParameterPropertyModifier)) {
emitPropertyDeclaration(param);
}
});
@@ -1130,7 +1131,7 @@ namespace ts {
// what we want, namely the name expression enclosed in brackets.
writeTextOfNode(currentText, node.name);
// If optional property emit ?
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && hasQuestionToken(node)) {
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || node.kind === SyntaxKind.Parameter) && hasQuestionToken(node)) {
write("?");
}
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) {
@@ -1378,6 +1379,7 @@ namespace ts {
function emitSignatureDeclaration(node: SignatureDeclaration) {
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
let closeParenthesizedFunctionType = false;
if (node.kind === SyntaxKind.IndexSignature) {
// Index signature can have readonly modifier
@@ -1389,6 +1391,16 @@ namespace ts {
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
}
else if (node.kind === SyntaxKind.FunctionType) {
const currentOutput = writer.getText();
// Do not generate incorrect type when function type with type parameters is type argument
// This could happen if user used space between two '<' making it error free
// e.g var x: A< <Tany>(a: Tany)=>Tany>;
if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") {
closeParenthesizedFunctionType = true;
write("(");
}
}
emitTypeParameters(node.typeParameters);
write("(");
}
@@ -1422,6 +1434,9 @@ namespace ts {
write(";");
writeLine();
}
else if (closeParenthesizedFunctionType) {
write(")");
}
function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
@@ -1740,7 +1755,7 @@ namespace ts {
if (!emitSkipped) {
const declarationOutput = emitDeclarationResult.referencesOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM);
writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles);
}
return emitSkipped;
+42 -13
View File
@@ -315,10 +315,6 @@
"category": "Error",
"code": 1110
},
"A class member cannot be declared optional.": {
"category": "Error",
"code": 1112
},
"A 'default' clause cannot appear more than once in a 'switch' statement.": {
"category": "Error",
"code": 1113
@@ -447,7 +443,7 @@
"category": "Error",
"code": 1147
},
"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.": {
"Cannot use imports, exports, or module augmentations when '--module' is 'none'.": {
"category": "Error",
"code": 1148
},
@@ -1739,10 +1735,22 @@
"category": "Error",
"code": 2530
},
"Object is possibly 'null' or 'undefined'.": {
"Object is possibly 'null'.": {
"category": "Error",
"code": 2531
},
"Object is possibly 'undefined'.": {
"category": "Error",
"code": 2532
},
"Object is possibly 'null' or 'undefined'.": {
"category": "Error",
"code": 2533
},
"A function returning 'never' cannot have a reachable end point.": {
"category": "Error",
"code": 2534
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -1835,10 +1843,6 @@
"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
@@ -1903,7 +1907,7 @@
"category": "Error",
"code": 2681
},
"A setter cannot have a 'this' parameter.": {
"'get' and 'set' accessor must have the same 'this' type.": {
"category": "Error",
"code": 2682
},
@@ -1919,6 +1923,14 @@
"category": "Error",
"code": 2685
},
"Identifier '{0}' must be imported from a module": {
"category": "Error",
"code": 2686
},
"All declarations of '{0}' must have identical modifiers.": {
"category": "Error",
"code": 2687
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2292,7 +2304,7 @@
"category": "Error",
"code": 5062
},
"Substututions for pattern '{0}' should be an array.": {
"Substitutions for pattern '{0}' should be an array.": {
"category": "Error",
"code": 5063
},
@@ -2344,6 +2356,10 @@
"category": "Message",
"code": 6011
},
"Skip type checking of declaration files.": {
"category": "Message",
"code": 6012
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": {
"category": "Message",
"code": 6015
@@ -2740,9 +2756,22 @@
"category": "Message",
"code": 6128
},
"The config file '{0}' found doesn't contain any source files.": {
"category": "Error",
"code": 6129
},
"Resolving real path for '{0}', result '{1}'": {
"category": "Message",
"code": 6130
},
"Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'.": {
"category": "Error",
"code": 6131
},
"Use the legacy emitter instead of the transforming emitter.": {
"category": "Message",
"code": 6129
"code": 6132
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
+4 -3
View File
@@ -1488,6 +1488,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
switch (parent.kind) {
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.AwaitExpression:
case SyntaxKind.BinaryExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.CaseClause:
@@ -1916,7 +1917,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write("Object.defineProperty(");
emit(tempVar);
write(", ");
emitStart(node.name);
emitStart(property.name);
emitExpressionForPropertyName(property.name);
emitEnd(property.name);
write(", {");
@@ -4958,7 +4959,7 @@ const _super = (function (geti, seti) {
function emitParameterPropertyAssignments(node: ConstructorDeclaration) {
forEach(node.parameters, param => {
if (hasModifier(param, ModifierFlags.AccessibilityModifier)) {
if (hasModifier(param, ModifierFlags.ParameterPropertyModifier)) {
writeLine();
emitStart(param);
emitStart(param.name);
@@ -7883,7 +7884,7 @@ const _super = (function (geti, seti) {
node.parent &&
node.parent.kind === SyntaxKind.ArrowFunction &&
(<ArrowFunction>node.parent).body === node &&
compilerOptions.target <= ScriptTarget.ES5) {
languageVersion <= ScriptTarget.ES5) {
return false;
}
+75 -20
View File
@@ -304,8 +304,8 @@ namespace ts {
case SyntaxKind.ImportClause:
return visitNode(cbNode, (<ImportClause>node).name) ||
visitNode(cbNode, (<ImportClause>node).namedBindings);
case SyntaxKind.GlobalModuleExportDeclaration:
return visitNode(cbNode, (<GlobalModuleExportDeclaration>node).name);
case SyntaxKind.NamespaceExportDeclaration:
return visitNode(cbNode, (<NamespaceExportDeclaration>node).name);
case SyntaxKind.NamespaceImport:
return visitNode(cbNode, (<NamespaceImport>node).name);
@@ -1818,7 +1818,7 @@ namespace ts {
function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName {
let entity: EntityName = parseIdentifier(diagnosticMessage);
while (parseOptional(SyntaxKind.DotToken)) {
const node = <QualifiedName>createNode(SyntaxKind.QualifiedName, entity.pos);
const node: QualifiedName = <QualifiedName>createNode(SyntaxKind.QualifiedName, entity.pos); // !!!
node.left = entity;
node.right = parseRightSideOfDot(allowReservedWords);
entity = finishNode(node);
@@ -2367,6 +2367,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NeverKeyword:
// If these are followed by a dot, then parse these out as a dotted type reference instead.
const node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReference();
@@ -2409,6 +2410,7 @@ namespace ts {
case SyntaxKind.NullKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.NeverKeyword:
case SyntaxKind.OpenBraceToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.LessThanToken:
@@ -2683,7 +2685,8 @@ namespace ts {
// 2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
// 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
// 4) ArrowFunctionExpression[?in,?yield]
// 5) [+Yield] YieldExpression[?In]
// 5) AsyncArrowFunctionExpression[in,yield,await]
// 6) [+Yield] YieldExpression[?In]
//
// Note: for ease of implementation we treat productions '2' and '3' as the same thing.
// (i.e. they're both BinaryExpressions with an assignment operator in it).
@@ -2693,11 +2696,18 @@ namespace ts {
return parseYieldExpression();
}
// Then, check if we have an arrow function (production '4') that starts with a parenthesized
// parameter list. If we do, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
// Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
// parameter list or is an async arrow function.
// AsyncArrowFunctionExpression:
// 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
// 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
// Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
// And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
//
// If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
// not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done
// with AssignmentExpression if we see one.
const arrowExpression = tryParseParenthesizedArrowFunctionExpression();
const arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
if (arrowExpression) {
return arrowExpression;
}
@@ -2789,10 +2799,17 @@ namespace ts {
}
}
function parseSimpleArrowFunctionExpression(identifier: Identifier): Expression {
function parseSimpleArrowFunctionExpression(identifier: Identifier, asyncModifier?: NodeArray<Modifier>): ArrowFunction {
Debug.assert(token === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
const node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction, identifier.pos);
let node: ArrowFunction;
if (asyncModifier) {
node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction, asyncModifier.pos);
node.modifiers = asyncModifier;
}
else {
node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction, identifier.pos);
}
const parameter = <ParameterDeclaration>createNode(SyntaxKind.Parameter, identifier.pos);
parameter.name = identifier;
@@ -2802,7 +2819,7 @@ namespace ts {
node.parameters.end = parameter.end;
node.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, "=>");
node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false);
node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
return finishNode(node);
}
@@ -2970,6 +2987,40 @@ namespace ts {
return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
}
function tryParseAsyncSimpleArrowFunctionExpression(): ArrowFunction {
// We do a check here so that we won't be doing unnecessarily call to "lookAhead"
if (token === SyntaxKind.AsyncKeyword) {
const isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker);
if (isUnParenthesizedAsyncArrowFunction === Tristate.True) {
const asyncModifier = parseModifiersForArrowFunction();
const expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
return parseSimpleArrowFunctionExpression(<Identifier>expr, asyncModifier);
}
}
return undefined;
}
function isUnParenthesizedAsyncArrowFunctionWorker(): Tristate {
// AsyncArrowFunctionExpression:
// 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
// 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
if (token === SyntaxKind.AsyncKeyword) {
nextToken();
// If the "async" is followed by "=>" token then it is not a begining of an async arrow-function
// but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
if (scanner.hasPrecedingLineBreak() || token === SyntaxKind.EqualsGreaterThanToken) {
return Tristate.False;
}
// Check for un-parenthesized AsyncArrowFunction
const expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
if (!scanner.hasPrecedingLineBreak() && expr.kind === SyntaxKind.Identifier && token === SyntaxKind.EqualsGreaterThanToken) {
return Tristate.True;
}
}
return Tristate.False;
}
function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction {
const node = <ArrowFunction>createNode(SyntaxKind.ArrowFunction);
node.modifiers = parseModifiersForArrowFunction();
@@ -3639,7 +3690,7 @@ namespace ts {
let elementName: EntityName = parseIdentifierName();
while (parseOptional(SyntaxKind.DotToken)) {
scanJsxIdentifier();
const node = <QualifiedName>createNode(SyntaxKind.QualifiedName, elementName.pos);
const node: QualifiedName = <QualifiedName>createNode(SyntaxKind.QualifiedName, elementName.pos); // !!!
node.left = elementName;
node.right = parseIdentifierName();
elementName = finishNode(node);
@@ -5288,8 +5339,8 @@ namespace ts {
return nextToken() === SyntaxKind.SlashToken;
}
function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): GlobalModuleExportDeclaration {
const exportDeclaration = <GlobalModuleExportDeclaration>createNode(SyntaxKind.GlobalModuleExportDeclaration, fullStart);
function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: NodeArray<Modifier>): NamespaceExportDeclaration {
const exportDeclaration = <NamespaceExportDeclaration>createNode(SyntaxKind.NamespaceExportDeclaration, fullStart);
exportDeclaration.decorators = decorators;
exportDeclaration.modifiers = modifiers;
parseExpected(SyntaxKind.AsKeyword);
@@ -6080,7 +6131,7 @@ namespace ts {
atToken.end = scanner.getTextPos();
nextJSDocToken();
const tagName = parseJSDocIdentifier();
const tagName = parseJSDocIdentifierName();
if (!tagName) {
return;
}
@@ -6143,7 +6194,7 @@ namespace ts {
let isBracketed: boolean;
// Looking for something like '[foo]' or 'foo'
if (parseOptionalToken(SyntaxKind.OpenBracketToken)) {
name = parseJSDocIdentifier();
name = parseJSDocIdentifierName();
isBracketed = true;
// May have an optional default, e.g. '[foo = 42]'
@@ -6153,8 +6204,8 @@ namespace ts {
parseExpected(SyntaxKind.CloseBracketToken);
}
else if (token === SyntaxKind.Identifier) {
name = parseJSDocIdentifier();
else if (tokenIsIdentifierOrKeyword(token)) {
name = parseJSDocIdentifierName();
}
if (!name) {
@@ -6217,7 +6268,7 @@ namespace ts {
const typeParameters = createNodeArray<TypeParameterDeclaration>();
while (true) {
const name = parseJSDocIdentifier();
const name = parseJSDocIdentifierName();
if (!name) {
parseErrorAtPosition(scanner.getStartPos(), 0, Diagnostics.Identifier_expected);
return undefined;
@@ -6250,8 +6301,12 @@ namespace ts {
return token = scanner.scanJSDocToken();
}
function parseJSDocIdentifier(): Identifier {
if (token !== SyntaxKind.Identifier) {
function parseJSDocIdentifierName(): Identifier {
return createJSDocIdentifier(tokenIsIdentifierOrKeyword(token));
}
function createJSDocIdentifier(isIdentifier: boolean): Identifier {
if (!isIdentifier) {
parseErrorAtCurrentToken(Diagnostics.Identifier_expected);
return undefined;
}
+89 -48
View File
@@ -192,8 +192,8 @@ namespace ts {
traceEnabled
};
// use typesRoot and fallback to directory that contains tsconfig if typesRoot is not set
const rootDir = options.typesRoot || (options.configFilePath ? getDirectoryPath(options.configFilePath) : undefined);
// use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set
const rootDir = options.typesRoot || (options.configFilePath ? getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory()));
if (traceEnabled) {
if (containingFile === undefined) {
@@ -566,22 +566,29 @@ namespace ts {
let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName,
failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
let isExternalLibraryImport = false;
if (!resolvedFileName) {
if (moduleHasNonRelativeName(moduleName)) {
if (traceEnabled) {
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
}
resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
isExternalLibraryImport = resolvedFileName !== undefined;
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
}
let isExternalLibraryImport = false;
if (moduleHasNonRelativeName(moduleName)) {
if (resolvedFileName && host.realpath) {
const originalFileName = resolvedFileName;
resolvedFileName = normalizePath(host.realpath(resolvedFileName));
if (traceEnabled) {
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
trace(host, Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName);
}
resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
isExternalLibraryImport = resolvedFileName !== undefined;
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
}
@@ -864,13 +871,28 @@ namespace ts {
}
}
function getDefaultTypeDirectiveNames(rootPath: string): string[] {
const localTypes = combinePaths(rootPath, "types");
const npmTypes = combinePaths(rootPath, "node_modules/@types");
let result: string[] = [];
if (sys.directoryExists(localTypes)) {
result = result.concat(sys.getDirectories(localTypes));
}
if (sys.directoryExists(npmTypes)) {
result = result.concat(sys.getDirectories(npmTypes));
}
return result;
}
function getDefaultLibLocation(): string {
return getDirectoryPath(normalizePath(sys.getExecutingFilePath()));
}
const newLine = getNewLineCharacter(options);
const realpath = sys.realpath && ((path: string) => sys.realpath(path));
return {
getDefaultTypeDirectiveNames,
getSourceFile,
getDefaultLibLocation,
getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)),
@@ -883,6 +905,7 @@ namespace ts {
readFile: fileName => sys.readFile(fileName),
trace: (s: string) => sys.write(s + newLine),
directoryExists: directoryName => sys.directoryExists(directoryName),
realpath,
getEnvironmentVariable: name => getEnvironmentVariable(name, /*host*/ undefined)
};
}
@@ -946,6 +969,23 @@ namespace ts {
return resolutions;
}
export function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[] {
// Use explicit type list from tsconfig.json
if (options.types) {
return options.types;
}
// or load all types from the automatic type import fields
if (host && host.getDefaultTypeDirectiveNames) {
const commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), f => host.getCanonicalFileName(f));
if (commonRoot) {
return host.getDefaultTypeDirectiveNames(commonRoot);
}
}
return undefined;
}
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
@@ -993,15 +1033,18 @@ namespace ts {
const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined;
if (!tryReuseStructureFromOldProgram()) {
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// load type declarations specified via 'types' argument
if (options.types && options.types.length) {
const resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, /*containingFile*/ undefined);
for (let i = 0; i < options.types.length; i++) {
processTypeReferenceDirective(options.types[i], resolutions[i]);
const typeReferences: string[] = getDefaultTypeDirectiveNames(options, rootNames, host);
if (typeReferences) {
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined);
for (let i = 0; i < typeReferences.length; i++) {
processTypeReferenceDirective(typeReferences[i], resolutions[i]);
}
}
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// Do not process the default library if:
// - The '--noLib' flag is used.
// - A 'no-default-lib' reference comment is encountered in
@@ -1027,6 +1070,7 @@ namespace ts {
program = {
getRootFileNames: () => rootNames,
getSourceFile,
getSourceFileByPath,
getSourceFiles: () => files,
getCompilerOptions: () => options,
getSyntacticDiagnostics,
@@ -1103,7 +1147,11 @@ namespace ts {
(oldOptions.allowJs !== options.allowJs) ||
(oldOptions.rootDir !== options.rootDir) ||
(oldOptions.typesSearchPaths !== options.typesSearchPaths) ||
(oldOptions.configFilePath !== options.configFilePath)) {
(oldOptions.configFilePath !== options.configFilePath) ||
(oldOptions.baseUrl !== options.baseUrl) ||
(oldOptions.typesRoot !== options.typesRoot) ||
!arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) ||
!mapIsEqualTo(oldOptions.paths, options.paths)) {
return false;
}
@@ -1125,7 +1173,10 @@ namespace ts {
const modifiedSourceFiles: SourceFile[] = [];
for (const oldSourceFile of oldProgram.getSourceFiles()) {
let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
let newSourceFile = host.getSourceFileByPath
? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target)
: host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
return false;
}
@@ -1220,6 +1271,7 @@ namespace ts {
getCurrentDirectory: () => currentDirectory,
getNewLine: () => host.getNewLine(),
getSourceFile: program.getSourceFile,
getSourceFileByPath: program.getSourceFileByPath,
getSourceFiles: program.getSourceFiles,
writeFile: writeFileCallback || (
(fileName, data, writeByteOrderMark, onError, sourceFiles) => host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles)),
@@ -1303,7 +1355,11 @@ namespace ts {
}
function getSourceFile(fileName: string): SourceFile {
return filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName));
return getSourceFileByPath(toPath(fileName, currentDirectory, getCanonicalFileName));
}
function getSourceFileByPath(path: Path): SourceFile {
return filesByName.get(path);
}
function getDiagnosticsHelper(
@@ -1745,10 +1801,6 @@ namespace ts {
reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd);
}
if (file) {
file.wasReferenced = file.wasReferenced || isReference;
}
return file;
}
@@ -1765,7 +1817,6 @@ namespace ts {
filesByName.set(path, file);
if (file) {
file.wasReferenced = file.wasReferenced || isReference;
file.path = path;
if (host.useCaseSensitiveFileNames()) {
@@ -1891,26 +1942,13 @@ namespace ts {
// add file to program only if:
// - resolution was successful
// - noResolve is falsy
// - module name come from the list fo imports
// - module name comes from the list of imports
const shouldAddFile = resolution &&
!options.noResolve &&
i < file.imports.length;
if (shouldAddFile) {
const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
if (importedFile && resolution.isExternalLibraryImport) {
// Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files,
// this check is ok. Otherwise this would be never true for javascript file
if (!isExternalModule(importedFile) && importedFile.statements.length) {
const start = getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
}
else if (importedFile.referencedFiles.length) {
const firstRef = importedFile.referencedFiles[0];
fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition));
}
}
findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
}
}
}
@@ -2004,7 +2042,7 @@ namespace ts {
}
}
else {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substututions_for_pattern_0_should_be_an_array, key));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key));
}
}
}
@@ -2063,7 +2101,7 @@ namespace ts {
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
}
// Cannot specify module gen target of es6 when below es6
@@ -2072,11 +2110,14 @@ namespace ts {
}
// Cannot specify module gen that isn't amd or system with --out
// Report this error if user specified --module moduleKind
// or if there is external module in compilation which defaults to commonjs
const emitModuleKind = getEmitModuleKind(options);
if (outFile && (options.module || firstExternalModuleSourceFile) && !(emitModuleKind === ModuleKind.AMD || emitModuleKind === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
if (outFile) {
if (options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
else if (options.module === undefined && firstExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
// there has to be common source directory if user specified --outdir || --sourceRoot
+1
View File
@@ -91,6 +91,7 @@ namespace ts {
"let": SyntaxKind.LetKeyword,
"module": SyntaxKind.ModuleKeyword,
"namespace": SyntaxKind.NamespaceKeyword,
"never": SyntaxKind.NeverKeyword,
"new": SyntaxKind.NewKeyword,
"null": SyntaxKind.NullKeyword,
"number": SyntaxKind.NumberKeyword,
+50 -111
View File
@@ -3,6 +3,11 @@
namespace ts {
export type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
export type DirectoryWatcherCallback = (directoryName: string) => void;
export interface WatchedFile {
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
export interface System {
args: string[];
@@ -19,21 +24,17 @@ namespace ts {
createDirectory(path: string): void;
getExecutingFilePath(): string;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
realpath?(path: string): string;
/*@internal*/ getEnvironmentVariable(name: string): string;
/*@internal*/ tryEnableSourceMapsForHost?(): void;
}
interface WatchedFile {
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
export interface FileWatcher {
close(): void;
}
@@ -73,9 +74,11 @@ namespace ts {
resolvePath(path: string): string;
readFile(path: string): string;
writeFile(path: string, contents: string): void;
getDirectories(path: string): string[];
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
realpath(path: string): string;
getEnvironmentVariable?(name: string): string;
};
@@ -163,6 +166,11 @@ namespace ts {
return result.sort();
}
function getDirectories(path: string): string[] {
const folder = fso.GetFolder(path);
return getNames(folder.subfolders);
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
@@ -216,6 +224,7 @@ namespace ts {
getCurrentDirectory() {
return new ActiveXObject("WScript.Shell").CurrentDirectory;
},
getDirectories,
getEnvironmentVariable(name: string) {
return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings(`%${name}%`);
},
@@ -236,83 +245,7 @@ namespace ts {
const _os = require("os");
const _crypto = require("crypto");
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
function createPollingWatchedFileSet(interval = 2500, chunkSize = 30) {
let watchedFiles: WatchedFile[] = [];
let nextFileToCheck = 0;
let watchTimer: any;
function getModifiedTime(fileName: string): Date {
return _fs.statSync(fileName).mtime;
}
function poll(checkedIndex: number) {
const watchedFile = watchedFiles[checkedIndex];
if (!watchedFile) {
return;
}
_fs.stat(watchedFile.fileName, (err: any, stats: any) => {
if (err) {
watchedFile.callback(watchedFile.fileName);
}
else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
watchedFile.mtime = getModifiedTime(watchedFile.fileName);
watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);
}
});
}
// this implementation uses polling and
// stat due to inconsistencies of fs.watch
// and efficiency of stat on modern filesystems
function startWatchTimer() {
watchTimer = setInterval(() => {
let count = 0;
let nextToCheck = nextFileToCheck;
let firstCheck = -1;
while ((count < chunkSize) && (nextToCheck !== firstCheck)) {
poll(nextToCheck);
if (firstCheck < 0) {
firstCheck = nextToCheck;
}
nextToCheck++;
if (nextToCheck === watchedFiles.length) {
nextToCheck = 0;
}
count++;
}
nextFileToCheck = nextToCheck;
}, interval);
}
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
const file: WatchedFile = {
fileName,
callback,
mtime: getModifiedTime(fileName)
};
watchedFiles.push(file);
if (watchedFiles.length === 1) {
startWatchTimer();
}
return file;
}
function removeFile(file: WatchedFile) {
watchedFiles = copyListRemovingItem(file, watchedFiles);
}
return {
getModifiedTime: getModifiedTime,
poll: poll,
startWatchTimer: startWatchTimer,
addFile: addFile,
removeFile: removeFile
};
}
const useNonPollingWatchers = process.env["TSC_NONPOLLING_WATCHER"];
function createWatchedFileSet() {
const dirWatchers: Map<DirectoryWatcher> = {};
@@ -395,26 +328,11 @@ namespace ts {
}
}
}
// 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
// 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
// pause less than 1.5 milliseconds); question is
// do we anticipate reference sets in the 100s and
// do we care about waiting 10-20 seconds to detect
// 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;
}
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
@@ -498,6 +416,10 @@ namespace ts {
return fileSystemEntryExists(path, FileSystemEntryKind.Directory);
}
function getDirectories(path: string): string[] {
return filter<string>(_fs.readdirSync(path), p => fileSystemEntryExists(combinePaths(path, p), FileSystemEntryKind.Directory));
}
function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
@@ -507,7 +429,7 @@ 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
// 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;
@@ -541,15 +463,26 @@ namespace ts {
readFile,
writeFile,
watchFile: (fileName, callback) => {
// Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling
// and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
const watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet;
const watchedFile = watchSet.addFile(fileName, callback);
return {
close: () => watchSet.removeFile(watchedFile)
};
if (useNonPollingWatchers) {
const watchedFile = watchedFileSet.addFile(fileName, callback);
return {
close: () => watchedFileSet.removeFile(watchedFile)
};
}
else {
_fs.watchFile(fileName, { persistent: true, interval: 250 }, fileChanged);
return {
close: () => _fs.unwatchFile(fileName, fileChanged)
};
}
function fileChanged(curr: any, prev: any) {
if (+curr.mtime <= +prev.mtime) {
return;
}
callback(fileName);
}
},
watchDirectory: (directoryName, callback, recursive) => {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
@@ -592,6 +525,7 @@ namespace ts {
getCurrentDirectory() {
return process.cwd();
},
getDirectories,
getEnvironmentVariable(name: string) {
return process.env[name] || "";
},
@@ -618,6 +552,9 @@ namespace ts {
exit(exitCode?: number): void {
process.exit(exitCode);
},
realpath(path: string): string {
return _fs.realpathSync(path);
},
tryEnableSourceMapsForHost() {
try {
require("source-map-support").install();
@@ -630,7 +567,7 @@ namespace ts {
}
function getChakraSystem(): System {
const realpath = ChakraHost.realpath && ((path: string) => ChakraHost.realpath(path));
return {
newLine: ChakraHost.newLine || "\r\n",
args: ChakraHost.args,
@@ -654,9 +591,11 @@ namespace ts {
createDirectory: ChakraHost.createDirectory,
getExecutingFilePath: () => ChakraHost.executingFile,
getCurrentDirectory: () => ChakraHost.currentDirectory,
getDirectories: ChakraHost.getDirectories,
getEnvironmentVariable: ChakraHost.getEnvironmentVariable || ((name: string) => ""),
readDirectory: ChakraHost.readDirectory,
exit: ChakraHost.quit,
realpath
};
}
+3 -2
View File
@@ -244,7 +244,8 @@ namespace ts {
case SyntaxKind.AsyncKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DeclareKeyword:
// TypeScript accessibility modifiers are elided.
case SyntaxKind.ReadonlyKeyword:
// TypeScript accessibility and readonly modifiers are elided.
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
@@ -920,7 +921,7 @@ namespace ts {
* @param parameter The parameter node.
*/
function isParameterWithPropertyAssignment(parameter: ParameterDeclaration) {
return hasModifier(parameter, ModifierFlags.AccessibilityModifier)
return hasModifier(parameter, ModifierFlags.ParameterPropertyModifier)
&& isIdentifier(parameter.name);
}
+18 -8
View File
@@ -59,11 +59,9 @@ namespace ts {
const territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
if (!trySetLanguageAndTerritory(language, territory, errors) &&
!trySetLanguageAndTerritory(language, undefined, errors)) {
errors.push(createCompilerDiagnostic(Diagnostics.Unsupported_locale_0, locale));
return false;
// Either ways do not fail, and fallback to the English diagnostic strings.
if (!trySetLanguageAndTerritory(language, territory, errors)) {
trySetLanguageAndTerritory(language, undefined, errors);
}
return true;
@@ -396,9 +394,21 @@ namespace ts {
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);
if (isWatchSet(configParseResult.options)) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (!directoryWatcher && 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 directory; if there is a given "project" parameter, then the configFileName
// is an absolute file name.
directory == "" ? "." : directory,
watchedDirectoryChanged, /*recursive*/ true);
};
}
return configParseResult;
}
+64 -20
View File
@@ -164,6 +164,7 @@ namespace ts {
IsKeyword,
ModuleKeyword,
NamespaceKeyword,
NeverKeyword,
ReadonlyKeyword,
RequireKeyword,
NumberKeyword,
@@ -276,7 +277,7 @@ namespace ts {
ModuleDeclaration,
ModuleBlock,
CaseBlock,
GlobalModuleExportDeclaration,
NamespaceExportDeclaration,
ImportEqualsDeclaration,
ImportDeclaration,
ImportClause,
@@ -433,6 +434,8 @@ namespace ts {
HasComputedFlags = 1 << 31, // Modifier flags have been computed
AccessibilityModifier = Public | Private | Protected,
// Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
ParameterPropertyModifier = AccessibilityModifier | Readonly,
NonPublicAccessibilityModifier = Private | Protected,
}
@@ -470,6 +473,7 @@ namespace ts {
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
/* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
/* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding)
/* @internal */ transformId?: number; // Associates transient transformation properties with a specific transformation (initialized by transformation).
/* @internal */ emitFlags?: NodeEmitFlags; // Transient emit flags for a synthesized node (initialized by transformation).
/* @internal */ sourceMapRange?: TextRange; // Transient custom sourcemap range for a synthesized node (initialized by transformation).
@@ -503,10 +507,10 @@ namespace ts {
// @kind(SyntaxKind.Identifier)
export interface Identifier extends PrimaryExpression {
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
text: string; // Text of identifier (with escapes converted to characters)
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
}
// Transient identifier node (marked by id === -1)
@@ -1405,8 +1409,8 @@ namespace ts {
name: Identifier;
}
// @kind(SyntaxKind.GlobalModuleImport)
export interface GlobalModuleExportDeclaration extends DeclarationStatement {
// @kind(SyntaxKind.NamespaceExportDeclaration)
export interface NamespaceExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
@@ -1582,6 +1586,44 @@ namespace ts {
isBracketed: boolean;
}
export const enum FlowFlags {
Unreachable = 1 << 0, // Unreachable code
Start = 1 << 1, // Start of flow graph
BranchLabel = 1 << 2, // Non-looping junction
LoopLabel = 1 << 3, // Looping junction
Assignment = 1 << 4, // Assignment
TrueCondition = 1 << 5, // Condition known to be true
FalseCondition = 1 << 6, // Condition known to be false
Referenced = 1 << 7, // Referenced as antecedent once
Shared = 1 << 8, // Referenced as antecedent more than once
Label = BranchLabel | LoopLabel,
Condition = TrueCondition | FalseCondition
}
export interface FlowNode {
flags: FlowFlags;
id?: number; // Node id used by flow type cache in checker
}
// FlowLabel represents a junction with multiple possible preceding control flows.
export interface FlowLabel extends FlowNode {
antecedents: FlowNode[];
}
// FlowAssignment represents a node that assigns a value to a narrowable reference,
// i.e. an identifier or a dotted name that starts with an identifier or 'this'.
export interface FlowAssignment extends FlowNode {
node: Expression | VariableDeclaration | BindingElement;
antecedent: FlowNode;
}
// FlowCondition represents a condition that is known to be true or false at the
// node's location in the control flow.
export interface FlowCondition extends FlowNode {
expression: Expression;
antecedent: FlowNode;
}
export interface AmdDependency {
path: string;
name: string;
@@ -1625,8 +1667,6 @@ namespace ts {
/* @internal */ externalModuleIndicator: Node;
// The first node that causes this file to be a CommonJS module
/* @internal */ commonJsModuleIndicator: Node;
// True if the file was a root file in a compilation or a /// reference targets
/* @internal */ wasReferenced?: boolean;
/* @internal */ identifiers: Map<string>;
/* @internal */ nodeCount: number;
@@ -1656,6 +1696,7 @@ namespace ts {
export interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile;
getSourceFileByPath(path: Path): SourceFile;
getCurrentDirectory(): string;
}
@@ -1798,6 +1839,7 @@ namespace ts {
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getNonNullableType(type: Type): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
@@ -1883,6 +1925,7 @@ namespace ts {
WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature
InElementType = 0x00000040, // Writing an array or union element type
UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
}
export const enum SymbolFormatFlags {
@@ -2050,7 +2093,7 @@ namespace ts {
BlockScopedVariableExcludes = Value,
ParameterExcludes = Value,
PropertyExcludes = Value,
PropertyExcludes = None,
EnumMemberExcludes = Value,
FunctionExcludes = Value & ~(Function | ValueModule),
ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts
@@ -2116,8 +2159,6 @@ namespace ts {
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // True if module exports some value (not just types)
firstAssignmentChecked?: boolean; // True if first assignment node has been computed
firstAssignment?: Node; // First assignment node (undefined if no assignments)
}
/* @internal */
@@ -2151,18 +2192,13 @@ namespace ts {
/* @internal */
export interface NodeLinks {
resolvedType?: Type; // Cached type of type node
resolvedAwaitedType?: Type; // Cached awaited type of type node
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
flags?: NodeCheckFlags; // Set of flags specific to Node
enumMemberValue?: number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
generatedName?: string; // Generated name for module, enum, or import declaration
generatedNames?: Map<string>; // Generated names table for source file
assignmentMap?: Map<boolean>; // Cached map of references assigned within this node
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
importOnRightSide?: Symbol; // for import declarations - import that appear on the right side
jsxFlags?: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
resolvedJsxType?: Type; // resolved element attributes type of a JSX openinglike element
hasSuperCall?: boolean; // recorded result when we try to find super-call. We only try to find one if this flag is undefined, indicating that we haven't made an attempt.
@@ -2202,11 +2238,12 @@ namespace ts {
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
Never = 0x08000000, // Never type
/* @internal */
Nullable = Undefined | Null,
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null | Never,
/* @internal */
Primitive = String | Number | Boolean | ESSymbol | Void | Undefined | Null | StringLiteral | Enum,
StringLike = String | StringLiteral,
@@ -2214,6 +2251,7 @@ namespace ts {
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
Narrowable = Any | ObjectType | Union | TypeParameter,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
/* @internal */
@@ -2534,6 +2572,7 @@ namespace ts {
allowJs?: boolean;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
skipLibCheck?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
/* @internal */ stripInternal?: boolean;
@@ -2553,14 +2592,14 @@ namespace ts {
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
[option: string]: CompilerOptionsValue | undefined;
}
export interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
[option: string]: string[] | boolean | undefined;
}
export interface DiscoverTypingsInfo {
@@ -2632,6 +2671,7 @@ namespace ts {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
raw?: any;
errors: Diagnostic[];
}
@@ -2815,6 +2855,8 @@ namespace ts {
readFile(fileName: string): string;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
realpath?(path: string): string;
getCurrentDirectory?(): string;
}
export interface ResolvedModule {
@@ -2847,9 +2889,11 @@ namespace ts {
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
getDefaultTypeDirectiveNames?(rootPath: string): string[];
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
+86 -10
View File
@@ -78,6 +78,25 @@ namespace ts {
return node.end - node.pos;
}
export function mapIsEqualTo<T>(map1: Map<T>, map2: Map<T>): boolean {
if (!map1 || !map2) {
return map1 === map2;
}
return containsAll(map1, map2) && containsAll(map2, map1);
}
function containsAll<T>(map: Map<T>, other: Map<T>): boolean {
for (const key in map) {
if (!hasProperty(map, key)) {
continue;
}
if (!hasProperty(other, key) || map[key] !== other[key]) {
return false;
}
}
return true;
}
export function arrayIsEqualTo<T>(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean {
if (!array1 || !array2) {
return array1 === array2;
@@ -688,6 +707,7 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NeverKeyword:
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.VoidExpression;
@@ -935,6 +955,15 @@ namespace ts {
}
}
export function getContainingFunctionOrModule(node: Node): Node {
while (true) {
node = node.parent;
if (isFunctionLike(node) || node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.SourceFile) {
return node;
}
}
}
export function getContainingClass(node: Node): ClassLikeDeclaration {
while (true) {
node = node.parent;
@@ -1157,6 +1186,7 @@ namespace ts {
export function isPartOfExpression(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.ThisKeyword:
case SyntaxKind.SuperKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
@@ -1306,6 +1336,10 @@ namespace ts {
return isRequire && (!checkArgumentIsStringLiteral || (<CallExpression>expression).arguments[0].kind === SyntaxKind.StringLiteral);
}
export function isSingleOrDoubleQuote(charCode: number) {
return charCode === CharacterCodes.singleQuote || charCode === CharacterCodes.doubleQuote;
}
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
export function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind {
@@ -1337,8 +1371,15 @@ namespace ts {
else if (lhs.expression.kind === SyntaxKind.PropertyAccessExpression) {
// chained dot, e.g. x.y.z = expr; this var is the 'x.y' part
const innerPropertyAccess = <PropertyAccessExpression>lhs.expression;
if (innerPropertyAccess.expression.kind === SyntaxKind.Identifier && innerPropertyAccess.name.text === "prototype") {
return SpecialPropertyAssignmentKind.PrototypeProperty;
if (innerPropertyAccess.expression.kind === SyntaxKind.Identifier) {
// module.exports.name = expr
const innerPropertyAccessIdentifier = <Identifier>innerPropertyAccess.expression;
if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") {
return SpecialPropertyAssignmentKind.ExportsProperty;
}
if (innerPropertyAccess.name.text === "prototype") {
return SpecialPropertyAssignmentKind.PrototypeProperty;
}
}
}
@@ -1522,7 +1563,30 @@ namespace ts {
return node && node.dotDotDotToken !== undefined;
}
// A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
// assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
// an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'.
export function isAssignmentTarget(node: Node): boolean {
while (node.parent.kind === SyntaxKind.ParenthesizedExpression) {
node = node.parent;
}
while (true) {
const parent = node.parent;
if (parent.kind === SyntaxKind.ArrayLiteralExpression || parent.kind === SyntaxKind.SpreadElementExpression) {
node = parent;
continue;
}
if (parent.kind === SyntaxKind.PropertyAssignment || parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
node = parent.parent;
continue;
}
return parent.kind === SyntaxKind.BinaryExpression &&
(<BinaryExpression>parent).operatorToken.kind === SyntaxKind.EqualsToken &&
(<BinaryExpression>parent).left === node ||
(parent.kind === SyntaxKind.ForInStatement || parent.kind === SyntaxKind.ForOfStatement) &&
(<ForInStatement | ForOfStatement>parent).initializer === node;
}
}
export function isNodeDescendantOf(node: Node, ancestor: Node): boolean {
while (node) {
@@ -1543,7 +1607,7 @@ namespace ts {
}
// True if the given identifier, string literal, or number literal is the name of a declaration node
export function isDeclarationName(name: Node): name is Identifier | StringLiteral | LiteralExpression {
export function isDeclarationName(name: Node): boolean {
if (name.kind !== SyntaxKind.Identifier && name.kind !== SyntaxKind.StringLiteral && name.kind !== SyntaxKind.NumericLiteral) {
return false;
}
@@ -1562,6 +1626,12 @@ namespace ts {
return false;
}
export function isLiteralComputedPropertyDeclarationName(node: Node) {
return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) &&
node.parent.kind === SyntaxKind.ComputedPropertyName &&
isDeclaration(node.parent.parent);
}
// Return true if the given identifier is classified as an IdentifierName
export function isIdentifierName(node: Identifier): boolean {
let parent = node.parent;
@@ -1607,7 +1677,7 @@ namespace ts {
// export default ...
export function isAliasSymbolDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.GlobalModuleExportDeclaration ||
node.kind === SyntaxKind.NamespaceExportDeclaration ||
node.kind === SyntaxKind.ImportClause && !!(<ImportClause>node).name ||
node.kind === SyntaxKind.NamespaceImport ||
node.kind === SyntaxKind.ImportSpecifier ||
@@ -1738,7 +1808,7 @@ namespace ts {
}
export function getPropertyNameForPropertyNameNode(name: DeclarationName): string {
if (name.kind === SyntaxKind.Identifier || name.kind === SyntaxKind.StringLiteral || name.kind === SyntaxKind.NumericLiteral) {
if (name.kind === SyntaxKind.Identifier || name.kind === SyntaxKind.StringLiteral || name.kind === SyntaxKind.NumericLiteral || name.kind === SyntaxKind.Parameter) {
return (<Identifier | LiteralExpression>name).text;
}
if (name.kind === SyntaxKind.ComputedPropertyName) {
@@ -1747,7 +1817,7 @@ namespace ts {
const rightHandSideName = (<PropertyAccessExpression>nameExpression).name.text;
return getPropertyNameForKnownSymbolName(rightHandSideName);
}
if (isStringOrNumericLiteral(nameExpression.kind)) {
else if (nameExpression.kind === SyntaxKind.StringLiteral || nameExpression.kind === SyntaxKind.NumericLiteral) {
return (<LiteralExpression>nameExpression).text;
}
}
@@ -2454,7 +2524,12 @@ namespace ts {
}
export function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode {
return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type;
if (accessor && accessor.parameters.length > 0) {
const hasThis = accessor.parameters.length === 2 &&
accessor.parameters[0].name.kind === SyntaxKind.Identifier &&
(accessor.parameters[0].name as Identifier).originalKeywordKind === SyntaxKind.ThisKeyword;
return accessor.parameters[hasThis ? 1 : 0].type;
}
}
export interface AllAccessorDeclarations {
@@ -3442,6 +3517,7 @@ namespace ts {
|| kind === SyntaxKind.StringKeyword
|| kind === SyntaxKind.SymbolKeyword
|| kind === SyntaxKind.VoidKeyword
|| kind === SyntaxKind.NeverKeyword
|| kind === SyntaxKind.ExpressionWithTypeArguments;
}
@@ -3703,7 +3779,7 @@ namespace ts {
|| kind === SyntaxKind.ImportEqualsDeclaration
|| kind === SyntaxKind.ExportDeclaration
|| kind === SyntaxKind.ExportAssignment
|| kind === SyntaxKind.GlobalModuleExportDeclaration;
|| kind === SyntaxKind.NamespaceExportDeclaration;
}
function isStatementKindButNotDeclarationKind(kind: SyntaxKind) {
@@ -4074,7 +4150,7 @@ namespace ts {
}
export function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean {
return hasModifier(node, ModifierFlags.AccessibilityModifier) && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent);
return hasModifier(node, ModifierFlags.ParameterPropertyModifier) && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent);
}
export function startsWith(str: string, prefix: string): boolean {
+1
View File
@@ -1,5 +1,6 @@
/// <reference path="checker.ts" />
/// <reference path="factory.ts" />
/// <reference path="utilities.ts" />
/* @internal */
namespace ts {
+4 -4
View File
@@ -89,16 +89,16 @@ class CompilerBaselineRunner extends RunnerBase {
otherFiles = [];
if (testCaseContent.settings["noImplicitReferences"] || /require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content });
toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content, fileOptions: lastUnit.fileOptions });
units.forEach(unit => {
if (unit.name !== lastUnit.name) {
otherFiles.push({ unitName: this.makeUnitName(unit.name, rootDir), content: unit.content });
otherFiles.push({ unitName: this.makeUnitName(unit.name, rootDir), content: unit.content, fileOptions: unit.fileOptions });
}
});
}
else {
toBeCompiled = units.map(unit => {
return { unitName: this.makeUnitName(unit.name, rootDir), content: unit.content };
return { unitName: this.makeUnitName(unit.name, rootDir), content: unit.content, fileOptions: unit.fileOptions };
});
}
@@ -107,7 +107,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
const output = Harness.Compiler.compileFiles(
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ undefined);
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ harnessSettings["currentDirectory"]);
options = output.options;
result = output.result;
+72 -54
View File
@@ -362,14 +362,14 @@ namespace FourSlash {
}
// Opens a file given its 0-based index or fileName
public openFile(index: number, content?: string): void;
public openFile(name: string, content?: string): void;
public openFile(indexOrName: any, content?: string) {
public openFile(index: number, content?: string, scriptKindName?: string): void;
public openFile(name: string, content?: string, scriptKindName?: string): void;
public openFile(indexOrName: any, content?: string, scriptKindName?: string) {
const fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
// Let the host know that this file is now open
this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content);
this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content, scriptKindName);
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
@@ -747,7 +747,7 @@ namespace FourSlash {
}
const missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess };
this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(references)})`);
this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(references, undefined, 2)})`);
}
public verifyReferencesCountIs(count: number, localFilesOnly = true) {
@@ -801,7 +801,7 @@ namespace FourSlash {
private testDiagnostics(expected: string, diagnostics: ts.Diagnostic[]) {
const realized = ts.realizeDiagnostics(diagnostics, "\r\n");
const actual = JSON.stringify(realized, null, " ");
const actual = JSON.stringify(realized, undefined, 2);
assert.equal(actual, expected);
}
@@ -876,7 +876,7 @@ namespace FourSlash {
}
if (ranges.length !== references.length) {
this.raiseError("Rename location count does not match result.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
this.raiseError("Rename location count does not match result.\n\nExpected: " + JSON.stringify(ranges, undefined, 2) + "\n\nActual:" + JSON.stringify(references, undefined, 2));
}
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
@@ -889,7 +889,7 @@ namespace FourSlash {
if (reference.textSpan.start !== range.start ||
ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError("Rename location results do not match.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
this.raiseError("Rename location results do not match.\n\nExpected: " + JSON.stringify(ranges, undefined, 2) + "\n\nActual:" + JSON.stringify(references, undefined, 2));
}
}
}
@@ -973,7 +973,7 @@ namespace FourSlash {
}
else {
if (actual) {
this.raiseError(`Expected no signature help, but got "${JSON.stringify(actual)}"`);
this.raiseError(`Expected no signature help, but got "${JSON.stringify(actual, undefined, 2)}"`);
}
}
}
@@ -1096,14 +1096,6 @@ namespace FourSlash {
}
addSpanInfoString();
return resultString;
function repeatString(count: number, char: string) {
let result = "";
for (let i = 0; i < count; i++) {
result += char;
}
return result;
}
}
public getBreakpointStatementLocation(pos: number) {
@@ -1185,7 +1177,7 @@ namespace FourSlash {
public printCurrentParameterHelp() {
const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
Harness.IO.log(JSON.stringify(help));
Harness.IO.log(JSON.stringify(help, undefined, 2));
}
public printCurrentQuickInfo() {
@@ -1227,7 +1219,7 @@ namespace FourSlash {
public printCurrentSignatureHelp() {
const sigHelp = this.getActiveSignatureHelpItem();
Harness.IO.log(JSON.stringify(sigHelp));
Harness.IO.log(JSON.stringify(sigHelp, undefined, 2));
}
public printMemberListMembers() {
@@ -1257,7 +1249,7 @@ namespace FourSlash {
public printReferences() {
const references = this.getReferencesAtCaret();
ts.forEach(references, entry => {
Harness.IO.log(JSON.stringify(entry));
Harness.IO.log(JSON.stringify(entry, undefined, 2));
});
}
@@ -1748,8 +1740,8 @@ namespace FourSlash {
function jsonMismatchString() {
return Harness.IO.newLine() +
"expected: '" + Harness.IO.newLine() + JSON.stringify(expected, (k, v) => v, 2) + "'" + Harness.IO.newLine() +
"actual: '" + Harness.IO.newLine() + JSON.stringify(actual, (k, v) => v, 2) + "'";
"expected: '" + Harness.IO.newLine() + JSON.stringify(expected, undefined, 2) + "'" + Harness.IO.newLine() +
"actual: '" + Harness.IO.newLine() + JSON.stringify(actual, undefined, 2) + "'";
}
}
@@ -1964,16 +1956,16 @@ namespace FourSlash {
// if there was an explicit match kind specified, then it should be validated.
if (matchKind !== undefined) {
const missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName };
this.raiseError(`verifyNavigationItemsListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items)})`);
this.raiseError(`verifyNavigationItemsListContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(items, undefined, 2)})`);
}
}
public verifyGetScriptLexicalStructureListCount(expected: number) {
public verifyNavigationBarCount(expected: number) {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
const actual = this.getNavigationBarItemsCount(items);
if (expected !== actual) {
this.raiseError(`verifyGetScriptLexicalStructureListCount failed - found: ${actual} navigation items, expected: ${expected}.`);
this.raiseError(`verifyNavigationBarCount failed - found: ${actual} navigation items, expected: ${expected}.`);
}
}
@@ -1989,36 +1981,50 @@ namespace FourSlash {
return result;
}
public verifyGetScriptLexicalStructureListContains(name: string, kind: string) {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
public verifyNavigationBarContains(name: string, kind: string, fileName?: string, parentName?: string, isAdditionalSpan?: boolean, markerPosition?: number) {
fileName = fileName || this.activeFile.fileName;
const items = this.languageService.getNavigationBarItems(fileName);
if (!items || items.length === 0) {
this.raiseError("verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one.");
this.raiseError("verifyNavigationBarContains failed - found 0 navigation items, expected at least one.");
}
if (this.navigationBarItemsContains(items, name, kind)) {
if (this.navigationBarItemsContains(items, name, kind, parentName)) {
return;
}
const missingItem = { name: name, kind: kind };
this.raiseError(`verifyGetScriptLexicalStructureListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items, null, " ")})`);
const missingItem = { name, kind, parentName };
this.raiseError(`verifyNavigationBarContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(items, undefined, 2)})`);
}
private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) {
if (items) {
private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string, parentName?: string) {
function recur(items: ts.NavigationBarItem[], curParentName: string) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item && item.text === name && item.kind === kind) {
if (item && item.text === name && item.kind === kind && (!parentName || curParentName === parentName)) {
return true;
}
if (this.navigationBarItemsContains(item.childItems, name, kind)) {
if (recur(item.childItems, item.text)) {
return true;
}
}
return false;
}
return recur(items, "");
}
return false;
public verifyNavigationBarChildItem(parent: string, name: string, kind: string) {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.text === parent) {
if (this.navigationBarItemsContains(item.childItems, name, kind))
return;
const missingItem = { name, kind };
this.raiseError(`verifyNavigationBarChildItem failed - could not find the item: ${JSON.stringify(missingItem)} in the children list: (${JSON.stringify(item.childItems, undefined, 2)})`);
}
}
}
public printNavigationItems(searchValue: string) {
@@ -2033,15 +2039,15 @@ namespace FourSlash {
}
}
public printScriptLexicalStructureItems() {
public printNavigationBar() {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
const length = items && items.length;
Harness.IO.log(`NavigationItems list (${length} items)`);
Harness.IO.log(`Navigation bar (${length} items)`);
for (let i = 0; i < length; i++) {
const item = items[i];
Harness.IO.log(`name: ${item.text}, kind: ${item.kind}`);
Harness.IO.log(`${repeatString(item.indent, " ")}name: ${item.text}, kind: ${item.kind}, childItems: ${item.childItems.map(child => child.text)}`);
}
}
@@ -2066,7 +2072,7 @@ namespace FourSlash {
}
const missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess };
this.raiseError(`verifyOccurrencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(occurrences)})`);
this.raiseError(`verifyOccurrencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(occurrences, undefined, 2)})`);
}
public verifyOccurrencesAtPositionListCount(expectedCount: number) {
@@ -2105,7 +2111,7 @@ namespace FourSlash {
}
const missingItem = { fileName: fileName, start: start, end: end, kind: kind };
this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(documentHighlights)})`);
this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem, undefined, 2)} in the returned list: (${JSON.stringify(documentHighlights, undefined, 2)})`);
}
public verifyDocumentHighlightsAtPositionListCount(expectedCount: number, fileNamesToSearch: string[]) {
@@ -2171,9 +2177,9 @@ namespace FourSlash {
}
}
const itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n");
const itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind }, undefined, 2)).join(",\n");
this.raiseError(`Expected "${JSON.stringify({ name, text, documentation, kind })}" to be in list [${itemsString}]`);
this.raiseError(`Expected "${JSON.stringify({ name, text, documentation, kind }, undefined, 2)}" to be in list [${itemsString}]`);
}
private findFile(indexOrName: any) {
@@ -2728,6 +2734,14 @@ ${code}
fileName: fileName
};
}
function repeatString(count: number, char: string) {
let result = "";
for (let i = 0; i < count; i++) {
result += char;
}
return result;
}
}
namespace FourSlashInterface {
@@ -2790,10 +2804,10 @@ namespace FourSlashInterface {
// Opens a file, given either its index as it
// appears in the test source, or its filename
// as specified in the test metadata
public file(index: number, content?: string): void;
public file(name: string, content?: string): void;
public file(indexOrName: any, content?: string): void {
this.state.openFile(indexOrName, content);
public file(index: number, content?: string, scriptKindName?: string): void;
public file(name: string, content?: string, scriptKindName?: string): void;
public file(indexOrName: any, content?: string, scriptKindName?: string): void {
this.state.openFile(indexOrName, content, scriptKindName);
}
}
@@ -3029,19 +3043,23 @@ namespace FourSlashInterface {
this.DocCommentTemplate(/*expectedText*/ undefined, /*expectedOffset*/ undefined, /*empty*/ true);
}
public getScriptLexicalStructureListCount(count: number) {
this.state.verifyGetScriptLexicalStructureListCount(count);
public navigationBarCount(count: number) {
this.state.verifyNavigationBarCount(count);
}
// TODO: figure out what to do with the unused arguments.
public getScriptLexicalStructureListContains(
public navigationBarContains(
name: string,
kind: string,
fileName?: string,
parentName?: string,
isAdditionalSpan?: boolean,
markerPosition?: number) {
this.state.verifyGetScriptLexicalStructureListContains(name, kind);
this.state.verifyNavigationBarContains(name, kind, fileName, parentName, isAdditionalSpan, markerPosition);
}
public navigationBarChildItem(parent: string, name: string, kind: string) {
this.state.verifyNavigationBarChildItem(parent, name, kind);
}
public navigationItemsListCount(count: number, searchValue: string, matchKind?: string) {
@@ -3234,8 +3252,8 @@ namespace FourSlashInterface {
this.state.printNavigationItems(searchValue);
}
public printScriptLexicalStructureItems() {
this.state.printScriptLexicalStructureItems();
public printNavigationBar() {
this.state.printNavigationBar();
}
public printReferences() {
+54 -24
View File
@@ -127,7 +127,7 @@ namespace Utils {
export function memoize<T extends Function>(f: T): T {
const cache: { [idx: string]: any } = {};
return <any>(function () {
return <any>(function() {
const key = Array.prototype.join.call(arguments);
const cachedResult = cache[key];
if (cachedResult) {
@@ -673,7 +673,7 @@ namespace Harness {
export const getCurrentDirectory = () => "";
export const args = () => <string[]>[];
export const getExecutingFilePath = () => "";
export const exit = (exitCode: number) => {};
export const exit = (exitCode: number) => { };
export let log = (s: string) => console.log(s);
@@ -901,7 +901,7 @@ namespace Harness {
}
if (!libFileNameSourceFileMap[fileName]) {
libFileNameSourceFileMap[fileName] = createSourceFileAndAssertInvariants(fileName, IO.readFile(libFolder + fileName), ts.ScriptTarget.Latest);
libFileNameSourceFileMap[fileName] = createSourceFileAndAssertInvariants(fileName, IO.readFile(libFolder + fileName), ts.ScriptTarget.Latest);
}
return libFileNameSourceFileMap[fileName];
}
@@ -930,13 +930,23 @@ namespace Harness {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
const getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
const fileMap: ts.FileMap<ts.SourceFile> = ts.createFileMap<ts.SourceFile>();
let realPathMap: ts.FileMap<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);
const path = ts.toPath(file.unitName, currentDirectory, getCanonicalFileName);
fileMap.set(path, sourceFile);
if (file.fileOptions && file.fileOptions["symlink"]) {
const link = file.fileOptions["symlink"];
const linkPath = ts.toPath(link, currentDirectory, getCanonicalFileName);
if (!realPathMap) {
realPathMap = ts.createFileMap<string>();
}
realPathMap.set(linkPath, fileName);
fileMap.set(path, (): ts.SourceFile => { throw new Error("Symlinks should always be resolved to a realpath first"); });
}
const sourceFile = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget);
fileMap.set(path, () => sourceFile);
}
}
@@ -944,7 +954,7 @@ namespace Harness {
fileName = ts.normalizePath(fileName);
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
return fileMap.get(path);
return fileMap.get(path)();
}
else if (fileName === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
@@ -965,6 +975,20 @@ namespace Harness {
return {
getDefaultTypeDirectiveNames: (path: string) => {
const results: string[] = [];
fileMap.forEachValue((key, value) => {
const rx = /node_modules\/@types\/(\w+)/;
const typeNameResult = rx.exec(key);
if (typeNameResult) {
const typeName = typeNameResult[1];
if (results.indexOf(typeName) < 0) {
results.push(typeName);
}
}
});
return results;
},
getCurrentDirectory: () => currentDirectory,
getSourceFile,
getDefaultLibFileName,
@@ -973,11 +997,16 @@ namespace Harness {
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => newLine,
fileExists: fileName => {
return fileMap.contains(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
return fileMap.contains(path) || (realPathMap && realPathMap.contains(path));
},
readFile: (fileName: string): string => {
return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)).getText();
}
return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName))().getText();
},
realpath: realPathMap && ((f: string) => {
const path = ts.toPath(f, currentDirectory, getCanonicalFileName);
return realPathMap.contains(path) ? realPathMap.get(path) : path;
})
};
}
@@ -998,7 +1027,9 @@ namespace Harness {
{ name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" },
{ name: "suppressOutputPathCheck", type: "boolean" },
{ name: "noImplicitReferences", type: "boolean" }
{ name: "noImplicitReferences", type: "boolean" },
{ name: "currentDirectory", type: "string" },
{ name: "symlink", type: "string" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
@@ -1053,6 +1084,7 @@ namespace Harness {
export interface TestFile {
unitName: string;
content: string;
fileOptions?: any;
}
export interface CompilationOutput {
@@ -1490,10 +1522,8 @@ namespace Harness {
// Comment line, check for global/file @options and record them
optionRegex.lastIndex = 0;
const metaDataName = testMetaData[1].toLowerCase();
if (metaDataName === "filename") {
currentFileOptions[testMetaData[1]] = testMetaData[2];
}
else {
currentFileOptions[testMetaData[1]] = testMetaData[2];
if (metaDataName !== "filename") {
continue;
}
@@ -1501,12 +1531,12 @@ namespace Harness {
if (currentFileName) {
// Store result file
const newTestFile = {
content: currentFileContent,
name: currentFileName,
fileOptions: currentFileOptions,
originalFilePath: fileName,
references: refs
};
content: currentFileContent,
name: currentFileName,
fileOptions: currentFileOptions,
originalFilePath: fileName,
references: refs
};
testUnitData.push(newTestFile);
// Reset local data
@@ -1604,10 +1634,10 @@ namespace Harness {
function baselinePath(fileName: string, type: string, baselineFolder: string, subfolder?: string) {
if (subfolder !== undefined) {
return Harness.userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName;
return Harness.userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName;
}
else {
return Harness.userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName;
return Harness.userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName;
}
}
@@ -1676,7 +1706,7 @@ namespace Harness {
}
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
const encoded_actual = Utils.encodeString(actual);
const encoded_actual = Utils.encodeString(actual);
if (expected != encoded_actual) {
// Overwrite & issue error
const errMsg = "The baseline file " + relativeFileName + " has changed.";
+18 -4
View File
@@ -163,7 +163,7 @@ namespace Harness.LanguageService {
throw new Error("No script with name '" + fileName + "'");
}
public openFile(fileName: string, content?: string): void {
public openFile(fileName: string, content?: string, scriptKindName?: string): void {
}
/**
@@ -182,6 +182,7 @@ namespace Harness.LanguageService {
class NativeLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceHost {
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getDirectories(path: string): string[] { return []; }
getCurrentDirectory(): string { return ""; }
getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; }
getScriptFileNames(): string[] { return this.getFilenames(); }
@@ -268,6 +269,7 @@ namespace Harness.LanguageService {
getCompilationSettings(): string { return JSON.stringify(this.nativeHost.getCompilationSettings()); }
getCancellationToken(): ts.HostCancellationToken { return this.nativeHost.getCancellationToken(); }
getCurrentDirectory(): string { return this.nativeHost.getCurrentDirectory(); }
getDirectories(path: string) { return this.nativeHost.getDirectories(path); }
getDefaultLibFileName(): string { return this.nativeHost.getDefaultLibFileName(); }
getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); }
getScriptSnapshot(fileName: string): ts.ScriptSnapshotShim {
@@ -528,9 +530,9 @@ namespace Harness.LanguageService {
this.client = client;
}
openFile(fileName: string, content?: string): void {
super.openFile(fileName, content);
this.client.openFile(fileName, content);
openFile(fileName: string, content?: string, scriptKindName?: "TS" | "JS" | "TSX" | "JSX"): void {
super.openFile(fileName, content, scriptKindName);
this.client.openFile(fileName, content, scriptKindName);
}
editScript(fileName: string, start: number, end: number, newText: string) {
@@ -600,6 +602,10 @@ namespace Harness.LanguageService {
return this.host.getCurrentDirectory();
}
getDirectories(path: string): string[] {
return [];
}
getEnvironmentVariable(name: string): string {
return ts.sys.getEnvironmentVariable(name);
}
@@ -645,6 +651,14 @@ namespace Harness.LanguageService {
startGroup(): void {
}
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any {
return setTimeout(callback, ms, args);
}
clearTimeout(timeoutId: any): void {
clearTimeout(timeoutId);
}
}
export class ServerLanguageServiceAdapter implements LanguageServiceAdapter {
+20 -19
View File
@@ -1,6 +1,6 @@
declare var require: any, process: any;
var fs: any = require('fs');
var path: any = require('path');
declare const require: any, process: any;
const fs: any = require("fs");
const path: any = require("path");
function instrumentForRecording(fn: string, tscPath: string) {
instrument(tscPath, `
@@ -14,31 +14,31 @@ ts.sys = Playback.wrapSystem(ts.sys);
ts.sys.startReplay("${ logFilename }");`);
}
function instrument(tscPath: string, prepareCode: string, cleanupCode: string = '') {
var bak = tscPath + '.bak';
function instrument(tscPath: string, prepareCode: string, cleanupCode = "") {
const bak = `${tscPath}.bak`;
fs.exists(bak, (backupExists: boolean) => {
var filename = tscPath;
let filename = tscPath;
if (backupExists) {
filename = bak;
}
fs.readFile(filename, 'utf-8', (err: any, tscContent: string) => {
fs.readFile(filename, "utf-8", (err: any, tscContent: string) => {
if (err) throw err;
fs.writeFile(bak, tscContent, (err: any) => {
if (err) throw err;
fs.readFile(path.resolve(path.dirname(tscPath) + '/loggedIO.js'), 'utf-8', (err: any, loggerContent: string) => {
fs.readFile(path.resolve(path.dirname(tscPath) + "/loggedIO.js"), "utf-8", (err: any, loggerContent: string) => {
if (err) throw err;
var invocationLine = 'ts.executeCommandLine(ts.sys.args);';
var index1 = tscContent.indexOf(invocationLine);
const invocationLine = "ts.executeCommandLine(ts.sys.args);";
const index1 = tscContent.indexOf(invocationLine);
if (index1 < 0) {
throw new Error("Could not find " + invocationLine);
throw new Error(`Could not find ${invocationLine}`);
}
var index2 = index1 + invocationLine.length;
var newContent = tscContent.substr(0, index1) + loggerContent + prepareCode + invocationLine + cleanupCode + tscContent.substr(index2) + '\r\n';
const index2 = index1 + invocationLine.length;
const newContent = tscContent.substr(0, index1) + loggerContent + prepareCode + invocationLine + cleanupCode + tscContent.substr(index2) + "\r\n";
fs.writeFile(tscPath, newContent);
});
});
@@ -46,15 +46,16 @@ function instrument(tscPath: string, prepareCode: string, cleanupCode: string =
});
}
var isJson = (arg: string) => arg.indexOf(".json") > 0;
const isJson = (arg: string) => arg.indexOf(".json") > 0;
var record = process.argv.indexOf('record');
var tscPath = process.argv[process.argv.length - 1];
const record = process.argv.indexOf("record");
const tscPath = process.argv[process.argv.length - 1];
if (record >= 0) {
console.log('Instrumenting ' + tscPath + ' for recording');
console.log(`Instrumenting ${tscPath} for recording`);
instrumentForRecording(process.argv[record + 1], tscPath);
} else if (process.argv.some(isJson)) {
var filename = process.argv.filter(isJson)[0];
}
else if (process.argv.some(isJson)) {
const filename = process.argv.filter(isJson)[0];
instrumentForReplay(filename, tscPath);
}
+1 -1
View File
@@ -149,7 +149,7 @@ namespace Playback {
recordLog = createEmptyLog();
if (typeof underlying.args !== "function") {
recordLog.arguments = <string[]>underlying.args;
recordLog.arguments = underlying.args;
}
};
+477 -479
View File
File diff suppressed because it is too large. Load diff
+8 -17
View File
@@ -4,13 +4,13 @@ interface Map<K, V> {
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
set(key: K, value?: V): this;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(entries?: [K, V][]): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
@@ -20,51 +20,42 @@ interface WeakMap<K, V> {
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
set(key: K, value?: V): this;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
new <T>(values?: T[]): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
new <T>(values?: T[]): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
+80 -67
View File
@@ -1,48 +1,48 @@
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
findIndex(predicate: (value: T) => boolean, thisArg?: any): number;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
fill(value: T, start?: number, end?: number): this;
/**
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
copyWithin(target: number, start: number, end?: number): this;
}
interface ArrayConstructor {
@@ -114,7 +114,7 @@ interface Math {
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
@@ -190,14 +190,14 @@ interface Math {
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 10‍−‍16.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
@@ -210,7 +210,7 @@ interface NumberConstructor {
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
@@ -223,30 +223,30 @@ interface NumberConstructor {
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n − 1 are both exactly representable as
* a Number value.
/**
* The value of the smallest integer n such that n and n − 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
@@ -255,12 +255,12 @@ interface NumberConstructor {
interface Object {
/**
* Determines whether an object has a property with the specified name.
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
@@ -269,7 +269,7 @@ interface Object {
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
@@ -277,7 +277,7 @@ interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
@@ -286,7 +286,7 @@ interface ObjectConstructor {
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
@@ -296,7 +296,7 @@ interface ObjectConstructor {
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
@@ -324,17 +324,17 @@ interface ObjectConstructor {
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
@@ -358,47 +358,60 @@ interface RegExp {
*/
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.
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface RegExpConstructor {
new (pattern: RegExp, flags?: string): RegExp;
(pattern: RegExp, flags?: string): RegExp;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition – length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
@@ -406,15 +419,15 @@ interface String {
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
@@ -474,10 +487,10 @@ interface StringConstructor {
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
}
+55 -3
View File
@@ -1,8 +1,16 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
}
interface IteratorResult<T> {
done: boolean;
value?: T;
value: T;
}
interface Iterator<T> {
@@ -11,11 +19,18 @@ interface Iterator<T> {
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> { }
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -48,7 +63,13 @@ interface ArrayConstructor {
from<T>(iterable: Iterable<T>): Array<T>;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Map<K, V> {
[Symbol.iterator](): IterableIterator<[K,V]>;
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
@@ -64,6 +85,23 @@ interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Set<T> {
[Symbol.iterator](): IterableIterator<T>;
entries(): IterableIterator<[T, T]>;
keys(): IterableIterator<T>;
values(): IterableIterator<T>;
}
interface SetConstructor {
new <T>(iterable: Iterable<T>): Set<T>;
}
interface WeakSet<T> { }
interface WeakSetConstructor {
new <T>(iterable: Iterable<T>): WeakSet<T>;
}
interface Promise<T> { }
interface PromiseConstructor {
@@ -88,11 +126,17 @@ declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -124,6 +168,7 @@ interface Int8ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -155,6 +200,7 @@ interface Uint8ArrayConstructor {
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -189,6 +235,7 @@ interface Uint8ClampedArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -222,6 +269,7 @@ interface Int16ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -253,6 +301,7 @@ interface Uint16ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -284,6 +333,7 @@ interface Int32ArrayConstructor {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -315,6 +365,7 @@ interface Uint32ArrayConstructor {
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
@@ -346,6 +397,7 @@ interface Float32ArrayConstructor {
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
+8 -37
View File
@@ -13,12 +13,6 @@ interface SymbolConstructor {
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
@@ -73,9 +67,6 @@ interface Symbol {
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
@@ -116,7 +107,6 @@ interface Date {
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
@@ -124,6 +114,14 @@ interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface Set<T> {
readonly [Symbol.toStringTag]: "Set";
}
interface WeakSet<T> {
readonly [Symbol.toStringTag]: "WeakSet";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
@@ -143,21 +141,6 @@ interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
@@ -223,9 +206,6 @@ interface RegExpConstructor {
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
@@ -279,7 +259,6 @@ interface DataView {
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
@@ -288,7 +267,6 @@ interface Int8Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
@@ -297,7 +275,6 @@ interface Uint8Array {
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
@@ -306,7 +283,6 @@ interface Uint8ClampedArray {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
@@ -315,7 +291,6 @@ interface Int16Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
@@ -324,7 +299,6 @@ interface Uint16Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
@@ -333,7 +307,6 @@ interface Int32Array {
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
@@ -342,7 +315,6 @@ interface Uint32Array {
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
@@ -351,6 +323,5 @@ interface Float32Array {
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
+14
View File
@@ -0,0 +1,14 @@
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T }): T[];
values(o: any): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
entries(o: any): [string, any][];
}
+810 -826
View File
File diff suppressed because it is too large. Load diff
+18 -7
View File
@@ -8,6 +8,16 @@ interface EventInit {
cancelable?: boolean;
}
interface IDBIndexParameters {
multiEntry?: boolean;
unique?: boolean;
}
interface IDBObjectStoreParameters {
autoIncrement?: boolean;
keyPath?: IDBKeyPath;
}
interface EventListener {
(evt: Event): void;
}
@@ -84,12 +94,12 @@ declare var Console: {
interface Coordinates {
readonly accuracy: number;
readonly altitude: number;
readonly altitudeAccuracy: number;
readonly heading: number;
readonly altitude: number | null;
readonly altitudeAccuracy: number | null;
readonly heading: number | null;
readonly latitude: number;
readonly longitude: number;
readonly speed: number;
readonly speed: number | null;
}
declare var Coordinates: {
@@ -176,7 +186,7 @@ declare var DOMException: {
interface DOMStringList {
readonly length: number;
contains(str: string): boolean;
item(index: number): string;
item(index: number): string | null;
[index: number]: string;
}
@@ -459,7 +469,7 @@ declare var IDBTransaction: {
}
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number;
readonly newVersion: number | null;
readonly oldVersion: number;
}
@@ -712,7 +722,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
withCredentials: boolean;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string;
getResponseHeader(header: string): string | null;
msCachingEnabled(): boolean;
open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
overrideMimeType(mime: string): void;
@@ -991,4 +1001,5 @@ declare var console: Console;
declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type IDBKeyPath = string;
type IDBValidKey = number | string | Date | IDBArrayKey;
+168 -155
View File
@@ -1,5 +1,5 @@
/// <reference path="session.ts" />
namespace ts.server {
export interface SessionClientHost extends LanguageServiceHost {
@@ -21,27 +21,26 @@ namespace ts.server {
export class SessionClient implements LanguageService {
private sequence: number = 0;
private fileMapping: ts.Map<string> = {};
private lineMaps: ts.Map<number[]> = {};
private messages: string[] = [];
private lastRenameEntry: RenameEntry;
constructor(private host: SessionClientHost) {
}
public onMessage(message: string): void {
public onMessage(message: string): void {
this.messages.push(message);
}
private writeMessage(message: string): void {
private writeMessage(message: string): void {
this.host.writeMessage(message);
}
private getLineMap(fileName: string): number[] {
var lineMap = ts.lookUp(this.lineMaps, fileName);
private getLineMap(fileName: string): number[] {
let lineMap = ts.lookUp(this.lineMaps, fileName);
if (!lineMap) {
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
lineMap = this.lineMaps[fileName] = ts.computeLineStarts(scriptSnapshot.getText(0, scriptSnapshot.getLength()));
const scriptSnapshot = this.host.getScriptSnapshot(fileName);
lineMap = this.lineMaps[fileName] = ts.computeLineStarts(scriptSnapshot.getText(0, scriptSnapshot.getLength()));
}
return lineMap;
}
@@ -51,7 +50,7 @@ namespace ts.server {
}
private positionToOneBasedLineOffset(fileName: string, position: number): protocol.Location {
var lineOffset = ts.computeLineAndCharacterOfPosition(this.getLineMap(fileName), position);
const lineOffset = ts.computeLineAndCharacterOfPosition(this.getLineMap(fileName), position);
return {
line: lineOffset.line + 1,
offset: lineOffset.character + 1
@@ -59,8 +58,8 @@ namespace ts.server {
}
private convertCodeEditsToTextChange(fileName: string, codeEdit: protocol.CodeEdit): ts.TextChange {
var start = this.lineOffsetToPosition(fileName, codeEdit.start);
var end = this.lineOffsetToPosition(fileName, codeEdit.end);
const start = this.lineOffsetToPosition(fileName, codeEdit.start);
const end = this.lineOffsetToPosition(fileName, codeEdit.end);
return {
span: ts.createTextSpanFromBounds(start, end),
@@ -69,12 +68,13 @@ namespace ts.server {
}
private processRequest<T extends protocol.Request>(command: string, args?: any): T {
var request: protocol.Request = {
seq: this.sequence++,
const request: protocol.Request = {
seq: this.sequence,
type: "request",
arguments: args,
command
};
this.sequence++;
this.writeMessage(JSON.stringify(request));
@@ -82,34 +82,29 @@ namespace ts.server {
}
private processResponse<T extends protocol.Response>(request: protocol.Request): T {
var lastMessage = this.messages.shift();
Debug.assert(!!lastMessage, "Did not receive any responses.");
// Read the content length
var contentLengthPrefix = "Content-Length: ";
var lines = lastMessage.split("\r\n");
Debug.assert(lines.length >= 2, "Malformed response: Expected 3 lines in the response.");
var contentLengthText = lines[0];
Debug.assert(contentLengthText.indexOf(contentLengthPrefix) === 0, "Malformed response: Response text did not contain content-length header.");
var contentLength = parseInt(contentLengthText.substring(contentLengthPrefix.length));
// Read the body
var responseBody = lines[2];
// Verify content length
Debug.assert(responseBody.length + 1 === contentLength, "Malformed response: Content length did not match the response's body length.");
try {
var response: T = JSON.parse(responseBody);
}
catch (e) {
throw new Error("Malformed response: Failed to parse server response: " + lastMessage + ". \r\n Error details: " + e.message);
let foundResponseMessage = false;
let lastMessage: string;
let response: T;
while (!foundResponseMessage) {
lastMessage = this.messages.shift();
Debug.assert(!!lastMessage, "Did not receive any responses.");
const responseBody = processMessage(lastMessage);
try {
response = JSON.parse(responseBody);
// the server may emit events before emitting the response. We
// want to ignore these events for testing purpose.
if (response.type === "response") {
foundResponseMessage = true;
}
}
catch (e) {
throw new Error("Malformed response: Failed to parse server response: " + lastMessage + ". \r\n Error details: " + e.message);
}
}
// verify the sequence numbers
Debug.assert(response.request_seq === request.seq, "Malformed response: response sequence number did not match request sequence number.");
// unmarshal errors
if (!response.success) {
throw new Error("Error " + response.message);
@@ -118,15 +113,33 @@ namespace ts.server {
Debug.assert(!!response.body, "Malformed response: Unexpected empty response body.");
return response;
function processMessage(message: string) {
// Read the content length
const contentLengthPrefix = "Content-Length: ";
const lines = message.split("\r\n");
Debug.assert(lines.length >= 2, "Malformed response: Expected 3 lines in the response.");
const contentLengthText = lines[0];
Debug.assert(contentLengthText.indexOf(contentLengthPrefix) === 0, "Malformed response: Response text did not contain content-length header.");
const contentLength = parseInt(contentLengthText.substring(contentLengthPrefix.length));
// Read the body
const responseBody = lines[2];
// Verify content length
Debug.assert(responseBody.length + 1 === contentLength, "Malformed response: Content length did not match the response's body length.");
return responseBody;
}
}
openFile(fileName: string, content?: string): void {
var args: protocol.OpenRequestArgs = { file: fileName, fileContent: content };
openFile(fileName: string, content?: string, scriptKindName?: "TS" | "JS" | "TSX" | "JSX"): void {
const args: protocol.OpenRequestArgs = { file: fileName, fileContent: content, scriptKindName };
this.processRequest(CommandNames.Open, args);
}
closeFile(fileName: string): void {
var args: protocol.FileRequestArgs = { file: fileName };
const args: protocol.FileRequestArgs = { file: fileName };
this.processRequest(CommandNames.Close, args);
}
@@ -134,10 +147,10 @@ namespace ts.server {
// clear the line map after an edit
this.lineMaps[fileName] = undefined;
var lineOffset = this.positionToOneBasedLineOffset(fileName, start);
var endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
const lineOffset = this.positionToOneBasedLineOffset(fileName, start);
const endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
var args: protocol.ChangeRequestArgs = {
const args: protocol.ChangeRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
@@ -150,18 +163,18 @@ namespace ts.server {
}
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset
};
var request = this.processRequest<protocol.QuickInfoRequest>(CommandNames.Quickinfo, args);
var response = this.processResponse<protocol.QuickInfoResponse>(request);
const request = this.processRequest<protocol.QuickInfoRequest>(CommandNames.Quickinfo, args);
const response = this.processResponse<protocol.QuickInfoResponse>(request);
var start = this.lineOffsetToPosition(fileName, response.body.start);
var end = this.lineOffsetToPosition(fileName, response.body.end);
const start = this.lineOffsetToPosition(fileName, response.body.start);
const end = this.lineOffsetToPosition(fileName, response.body.end);
return {
kind: response.body.kind,
@@ -173,68 +186,68 @@ namespace ts.server {
}
getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo {
var args: protocol.ProjectInfoRequestArgs = {
const args: protocol.ProjectInfoRequestArgs = {
file: fileName,
needFileNameList: needFileNameList
};
var request = this.processRequest<protocol.ProjectInfoRequest>(CommandNames.ProjectInfo, args);
var response = this.processResponse<protocol.ProjectInfoResponse>(request);
const request = this.processRequest<protocol.ProjectInfoRequest>(CommandNames.ProjectInfo, args);
const response = this.processResponse<protocol.ProjectInfoResponse>(request);
return {
configFileName: response.body.configFileName,
fileNames: response.body.fileNames
};
}
getCompletionsAtPosition(fileName: string, position: number): CompletionInfo {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.CompletionsRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.CompletionsRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
prefix: undefined
};
var request = this.processRequest<protocol.CompletionsRequest>(CommandNames.Completions, args);
var response = this.processResponse<protocol.CompletionsResponse>(request);
const request = this.processRequest<protocol.CompletionsRequest>(CommandNames.Completions, args);
const response = this.processResponse<protocol.CompletionsResponse>(request);
return {
return {
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: response.body
};
}
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.CompletionDetailsRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.CompletionDetailsRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
entryNames: [entryName]
};
var request = this.processRequest<protocol.CompletionDetailsRequest>(CommandNames.CompletionDetails, args);
var response = this.processResponse<protocol.CompletionDetailsResponse>(request);
const request = this.processRequest<protocol.CompletionDetailsRequest>(CommandNames.CompletionDetails, args);
const response = this.processResponse<protocol.CompletionDetailsResponse>(request);
Debug.assert(response.body.length === 1, "Unexpected length of completion details response body.");
return response.body[0];
}
getNavigateToItems(searchValue: string): NavigateToItem[] {
var args: protocol.NavtoRequestArgs = {
const args: protocol.NavtoRequestArgs = {
searchValue,
file: this.host.getScriptFileNames()[0]
};
var request = this.processRequest<protocol.NavtoRequest>(CommandNames.Navto, args);
var response = this.processResponse<protocol.NavtoResponse>(request);
const request = this.processRequest<protocol.NavtoRequest>(CommandNames.Navto, args);
const response = this.processResponse<protocol.NavtoResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
name: entry.name,
containerName: entry.containerName || "",
@@ -250,9 +263,9 @@ namespace ts.server {
}
getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): ts.TextChange[] {
var startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
var endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
var args: protocol.FormatRequestArgs = {
const startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
const endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
const args: protocol.FormatRequestArgs = {
file: fileName,
line: startLineOffset.line,
offset: startLineOffset.offset,
@@ -261,10 +274,10 @@ namespace ts.server {
};
// TODO: handle FormatCodeOptions
var request = this.processRequest<protocol.FormatRequest>(CommandNames.Format, args);
var response = this.processResponse<protocol.FormatResponse>(request);
const request = this.processRequest<protocol.FormatRequest>(CommandNames.Format, args);
const response = this.processResponse<protocol.FormatResponse>(request);
return response.body.map(entry=> this.convertCodeEditsToTextChange(fileName, entry));
return response.body.map(entry => this.convertCodeEditsToTextChange(fileName, entry));
}
getFormattingEditsForDocument(fileName: string, options: ts.FormatCodeOptions): ts.TextChange[] {
@@ -272,8 +285,8 @@ namespace ts.server {
}
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): ts.TextChange[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FormatOnKeyRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FormatOnKeyRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
@@ -281,27 +294,27 @@ namespace ts.server {
};
// TODO: handle FormatCodeOptions
var request = this.processRequest<protocol.FormatOnKeyRequest>(CommandNames.Formatonkey, args);
var response = this.processResponse<protocol.FormatResponse>(request);
const request = this.processRequest<protocol.FormatOnKeyRequest>(CommandNames.Formatonkey, args);
const response = this.processResponse<protocol.FormatResponse>(request);
return response.body.map(entry=> this.convertCodeEditsToTextChange(fileName, entry));
return response.body.map(entry => this.convertCodeEditsToTextChange(fileName, entry));
}
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.DefinitionRequest>(CommandNames.Definition, args);
var response = this.processResponse<protocol.DefinitionResponse>(request);
const request = this.processRequest<protocol.DefinitionRequest>(CommandNames.Definition, args);
const response = this.processResponse<protocol.DefinitionResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerName: "",
@@ -314,20 +327,20 @@ namespace ts.server {
}
getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.TypeDefinitionRequest>(CommandNames.TypeDefinition, args);
var response = this.processResponse<protocol.TypeDefinitionResponse>(request);
const request = this.processRequest<protocol.TypeDefinitionRequest>(CommandNames.TypeDefinition, args);
const response = this.processResponse<protocol.TypeDefinitionResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerName: "",
@@ -339,26 +352,26 @@ namespace ts.server {
});
}
findReferences(fileName: string, position: number): ReferencedSymbol[]{
findReferences(fileName: string, position: number): ReferencedSymbol[] {
// Not yet implemented.
return [];
}
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.ReferencesRequest>(CommandNames.References, args);
var response = this.processResponse<protocol.ReferencesResponse>(request);
const request = this.processRequest<protocol.ReferencesRequest>(CommandNames.References, args);
const response = this.processResponse<protocol.ReferencesResponse>(request);
return response.body.refs.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
fileName: fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
@@ -384,8 +397,8 @@ namespace ts.server {
}
getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.RenameRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.RenameRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
@@ -393,14 +406,14 @@ namespace ts.server {
findInComments
};
var request = this.processRequest<protocol.RenameRequest>(CommandNames.Rename, args);
var response = this.processResponse<protocol.RenameResponse>(request);
var locations: RenameLocation[] = [];
const request = this.processRequest<protocol.RenameRequest>(CommandNames.Rename, args);
const response = this.processResponse<protocol.RenameResponse>(request);
const locations: RenameLocation[] = [];
response.body.locs.map((entry: protocol.SpanGroup) => {
var fileName = entry.file;
const fileName = entry.file;
entry.locs.map((loc: protocol.TextSpan) => {
var start = this.lineOffsetToPosition(fileName, loc.start);
var end = this.lineOffsetToPosition(fileName, loc.end);
const start = this.lineOffsetToPosition(fileName, loc.start);
const end = this.lineOffsetToPosition(fileName, loc.end);
locations.push({
textSpan: ts.createTextSpanFromBounds(start, end),
fileName: fileName
@@ -444,7 +457,7 @@ namespace ts.server {
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers || "",
spans: item.spans.map(span=> createTextSpanFromBounds(this.lineOffsetToPosition(fileName, span.start), this.lineOffsetToPosition(fileName, span.end))),
spans: item.spans.map(span => createTextSpanFromBounds(this.lineOffsetToPosition(fileName, span.start), this.lineOffsetToPosition(fileName, span.end))),
childItems: this.decodeNavigationBarItems(item.childItems, fileName),
indent: 0,
bolded: false,
@@ -453,12 +466,12 @@ namespace ts.server {
}
getNavigationBarItems(fileName: string): NavigationBarItem[] {
var args: protocol.FileRequestArgs = {
const args: protocol.FileRequestArgs = {
file: fileName
};
var request = this.processRequest<protocol.NavBarRequest>(CommandNames.NavBar, args);
var response = this.processResponse<protocol.NavBarResponse>(request);
const request = this.processRequest<protocol.NavBarRequest>(CommandNames.NavBar, args);
const response = this.processResponse<protocol.NavBarResponse>(request);
return this.decodeNavigationBarItems(response.body, fileName);
}
@@ -472,26 +485,26 @@ namespace ts.server {
}
getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.SignatureHelpRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.SignatureHelpRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset
};
var request = this.processRequest<protocol.SignatureHelpRequest>(CommandNames.SignatureHelp, args);
var response = this.processResponse<protocol.SignatureHelpResponse>(request);
const request = this.processRequest<protocol.SignatureHelpRequest>(CommandNames.SignatureHelp, args);
const response = this.processResponse<protocol.SignatureHelpResponse>(request);
if (!response.body) {
return undefined;
}
var helpItems: protocol.SignatureHelpItems = response.body;
var span = helpItems.applicableSpan;
var start = this.lineOffsetToPosition(fileName, span.start);
var end = this.lineOffsetToPosition(fileName, span.end);
var result: SignatureHelpItems = {
const helpItems: protocol.SignatureHelpItems = response.body;
const span = helpItems.applicableSpan;
const start = this.lineOffsetToPosition(fileName, span.start);
const end = this.lineOffsetToPosition(fileName, span.end);
const result: SignatureHelpItems = {
items: helpItems.items,
applicableSpan: {
start: start,
@@ -499,26 +512,26 @@ namespace ts.server {
},
selectedItemIndex: helpItems.selectedItemIndex,
argumentIndex: helpItems.argumentIndex,
argumentCount: helpItems.argumentCount,
}
argumentCount: helpItems.argumentCount,
};
return result;
}
getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.OccurrencesRequest>(CommandNames.Occurrences, args);
var response = this.processResponse<protocol.OccurrencesResponse>(request);
const request = this.processRequest<protocol.OccurrencesRequest>(CommandNames.Occurrences, args);
const response = this.processResponse<protocol.OccurrencesResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const fileName = entry.file;
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
@@ -528,17 +541,17 @@ namespace ts.server {
}
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
let { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
let args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
const { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
let request = this.processRequest<protocol.DocumentHighlightsRequest>(CommandNames.DocumentHighlights, args);
let response = this.processResponse<protocol.DocumentHighlightsResponse>(request);
const request = this.processRequest<protocol.DocumentHighlightsRequest>(CommandNames.DocumentHighlights, args);
const response = this.processResponse<protocol.DocumentHighlightsResponse>(request);
let self = this;
const self = this;
return response.body.map(convertToDocumentHighlights);
function convertToDocumentHighlights(item: ts.server.protocol.DocumentHighlightsItem): ts.DocumentHighlights {
let { file, highlightSpans } = item;
const { file, highlightSpans } = item;
return {
fileName: file,
@@ -546,8 +559,8 @@ namespace ts.server {
};
function convertHighlightSpan(span: ts.server.protocol.HighlightSpan): ts.HighlightSpan {
let start = self.lineOffsetToPosition(file, span.start);
let end = self.lineOffsetToPosition(file, span.end);
const start = self.lineOffsetToPosition(file, span.start);
const end = self.lineOffsetToPosition(file, span.end);
return {
textSpan: ts.createTextSpanFromBounds(start, end),
kind: span.kind
@@ -561,31 +574,31 @@ namespace ts.server {
}
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[] {
throw new Error("Not Implemented Yet.");
throw new Error("Not Implemented Yet.");
}
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion {
throw new Error("Not Implemented Yet.");
throw new Error("Not Implemented Yet.");
}
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
throw new Error("Not Implemented Yet.");
throw new Error("Not Implemented Yet.");
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.BraceRequest>(CommandNames.Brace, args);
var response = this.processResponse<protocol.BraceResponse>(request);
const request = this.processRequest<protocol.BraceRequest>(CommandNames.Brace, args);
const response = this.processResponse<protocol.BraceResponse>(request);
return response.body.map(entry => {
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
start: start,
length: end - start,
+78 -44
View File
@@ -32,8 +32,9 @@ namespace ts.server {
children: ScriptInfo[] = []; // files referenced by this file
defaultProject: Project; // project to use by default for file
fileWatcher: FileWatcher;
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host));
path: Path;
scriptKind: ScriptKind;
constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) {
this.path = toPath(fileName, host.getCurrentDirectory(), createGetCanonicalFileName(host.useCaseSensitiveFileNames));
@@ -215,8 +216,16 @@ namespace ts.server {
return this.roots.map(root => root.fileName);
}
getScriptKind() {
return ScriptKind.Unknown;
getScriptKind(fileName: string) {
const info = this.getScriptInfo(fileName);
if (!info) {
return undefined;
}
if (!info.scriptKind) {
info.scriptKind = getScriptKindFromFileName(fileName);
}
return info.scriptKind;
}
getScriptVersion(filename: string) {
@@ -489,6 +498,14 @@ namespace ts.server {
return copiedList;
}
/**
* This helper funciton processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project.
*/
export function combineProjectOutput<T>(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean) {
const result = projects.reduce<T[]>((previous, current) => concatenate(previous, action(current)), []).sort(comparer);
return projects.length > 1 ? deduplicate(result, areEqual) : result;
}
export interface ProjectServiceEventHandler {
(eventName: string, project: Project, fileName: string): void;
}
@@ -516,7 +533,7 @@ namespace ts.server {
// number becomes 0 for a watcher, then we should close it.
directoryWatchersRefCount: ts.Map<number> = {};
hostConfiguration: HostConfiguration;
timerForDetectingProjectFileListChanges: Map<NodeJS.Timer> = {};
timerForDetectingProjectFileListChanges: Map<any> = {};
constructor(public host: ServerHost, public psLogger: Logger, public eventHandler?: ProjectServiceEventHandler) {
// ts.disableIncrementalParsing = true;
@@ -525,7 +542,7 @@ namespace ts.server {
addDefaultHostConfiguration() {
this.hostConfiguration = {
formatCodeOptions: ts.clone(CompilerService.defaultFormatCodeOptions),
formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)),
hostInfo: "Unknown host"
};
}
@@ -576,9 +593,9 @@ namespace ts.server {
startTimerForDetectingProjectFileListChanges(project: Project) {
if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) {
clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]);
}
this.timerForDetectingProjectFileListChanges[project.projectFilename] = setTimeout(
this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(
() => this.handleProjectFileListChanges(project),
250
);
@@ -902,6 +919,7 @@ namespace ts.server {
configuredProject.updateGraph();
if (configuredProject.getSourceFile(info)) {
info.defaultProject = configuredProject;
referencingProjects.push(configuredProject);
}
}
return referencingProjects;
@@ -1013,7 +1031,7 @@ 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, fileContent?: string) {
openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind) {
fileName = ts.normalizePath(fileName);
let info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
@@ -1028,6 +1046,7 @@ namespace ts.server {
}
if (content !== undefined) {
info = new ScriptInfo(this.host, fileName, content, openedByClient);
info.scriptKind = scriptKind;
info.setFormatOptions(this.getFormatCodeOptions());
this.filenameToScriptInfo[fileName] = info;
if (!info.isOpen) {
@@ -1077,12 +1096,12 @@ 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
*/
openClientFile(fileName: string, fileContent?: string) {
this.openOrUpdateConfiguredProjectForFile(fileName);
const info = this.openFile(fileName, /*openedByClient*/ true, fileContent);
openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): { configFileName?: string, configFileErrors?: Diagnostic[] } {
const { configFileName, configFileErrors } = this.openOrUpdateConfiguredProjectForFile(fileName);
const info = this.openFile(fileName, /*openedByClient*/ true, fileContent, scriptKind);
this.addOpenFile(info);
this.printProjects();
return info;
return { configFileName, configFileErrors };
}
/**
@@ -1090,7 +1109,7 @@ namespace ts.server {
* 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.
*/
openOrUpdateConfiguredProjectForFile(fileName: string) {
openOrUpdateConfiguredProjectForFile(fileName: string): { configFileName?: string, configFileErrors?: Diagnostic[] } {
const searchPath = ts.normalizePath(getDirectoryPath(fileName));
this.log("Search path: " + searchPath, "Info");
const configFileName = this.findConfigFile(searchPath);
@@ -1100,11 +1119,16 @@ namespace ts.server {
if (!project) {
const configResult = this.openConfigFile(configFileName, fileName);
if (!configResult.success) {
this.log("Error opening config file " + configFileName + " " + configResult.errorMsg);
return { configFileName, configFileErrors: configResult.errors };
}
else {
// even if opening config file was successful, it could still
// contain errors that were tolerated.
this.log("Opened configuration file " + configFileName, "Info");
this.configuredProjects.push(configResult.project);
if (configResult.errors && configResult.errors.length > 0) {
return { configFileName, configFileErrors: configResult.errors };
}
}
}
else {
@@ -1114,6 +1138,7 @@ namespace ts.server {
else {
this.log("No config files found.");
}
return {};
}
/**
@@ -1203,24 +1228,25 @@ namespace ts.server {
return undefined;
}
configFileToProjectOptions(configFilename: string): { succeeded: boolean, projectOptions?: ProjectOptions, error?: ProjectOpenResult } {
configFileToProjectOptions(configFilename: string): { succeeded: boolean, projectOptions?: ProjectOptions, errors?: Diagnostic[] } {
configFilename = ts.normalizePath(configFilename);
// file references will be relative to dirPath (or absolute)
const dirPath = ts.getDirectoryPath(configFilename);
const contents = this.host.readFile(configFilename);
const rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.parseConfigFileTextToJson(configFilename, contents);
if (rawConfig.error) {
return { succeeded: false, error: rawConfig.error };
return { succeeded: false, errors: [rawConfig.error] };
}
else {
const parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath, /*existingOptions*/ {}, configFilename);
Debug.assert(!!parsedCommandLine.fileNames);
if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) {
return { succeeded: false, error: { errorMsg: "tsconfig option errors" } };
return { succeeded: false, errors: parsedCommandLine.errors };
}
else if (parsedCommandLine.fileNames.length === 0) {
return { succeeded: false, error: { errorMsg: "no files found" } };
const error = createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename);
return { succeeded: false, errors: [error] };
}
else {
const projectOptions: ProjectOptions = {
@@ -1233,20 +1259,21 @@ namespace ts.server {
}
openConfigFile(configFilename: string, clientFileName?: string): ProjectOpenResult {
const { succeeded, projectOptions, error } = this.configFileToProjectOptions(configFilename);
openConfigFile(configFilename: string, clientFileName?: string): { success: boolean, project?: Project, errors?: Diagnostic[] } {
const { succeeded, projectOptions, errors } = this.configFileToProjectOptions(configFilename);
if (!succeeded) {
return error;
return { success: false, errors };
}
else {
const project = this.createProject(configFilename, projectOptions);
let errors: Diagnostic[];
for (const rootFilename of projectOptions.files) {
if (this.host.fileExists(rootFilename)) {
const info = this.openFile(rootFilename, /*openedByClient*/ clientFileName == rootFilename);
project.addRoot(info);
}
else {
return { errorMsg: "specified file " + rootFilename + " not found" };
(errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.File_0_not_found, rootFilename));
}
}
project.finishGraph();
@@ -1257,7 +1284,7 @@ namespace ts.server {
path => this.directoryWatchedForSourceFilesChanged(project, path),
/*recursive*/ true
);
return { success: true, project: project };
return { success: true, project: project, errors };
}
}
@@ -1267,13 +1294,13 @@ namespace ts.server {
this.removeProject(project);
}
else {
const { succeeded, projectOptions, error } = this.configFileToProjectOptions(project.projectFilename);
const { succeeded, projectOptions, errors } = this.configFileToProjectOptions(project.projectFilename);
if (!succeeded) {
return error;
return errors;
}
else {
const oldFileNames = project.compilerService.host.roots.map(info => info.fileName);
const newFileNames = projectOptions.files;
const newFileNames = ts.filter(projectOptions.files, f => this.host.fileExists(f));
const fileNamesToRemove = oldFileNames.filter(f => newFileNames.indexOf(f) < 0);
const fileNamesToAdd = newFileNames.filter(f => oldFileNames.indexOf(f) < 0);
@@ -1355,23 +1382,25 @@ namespace ts.server {
return ts.isExternalModule(sourceFile);
}
static defaultFormatCodeOptions: ts.FormatCodeOptions = {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: ts.sys ? ts.sys.newLine : "\n",
ConvertTabsToSpaces: true,
IndentStyle: ts.IndentStyle.Smart,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
};
static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions {
return ts.clone({
IndentSize: 4,
TabSize: 4,
NewLineCharacter: host.newLine || "\n",
ConvertTabsToSpaces: true,
IndentStyle: ts.IndentStyle.Smart,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
InsertSpaceBeforeAndAfterBinaryOperators: true,
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
});
}
}
export interface LineCollection {
@@ -1666,7 +1695,12 @@ namespace ts.server {
}
reloadFromFile(filename: string, cb?: () => any) {
const content = this.host.readFile(filename);
let content = this.host.readFile(filename);
// If the file doesn't exist or cannot be read, we should
// wipe out its cached content on the server to avoid side effects.
if (!content) {
content = "";
}
this.reload(content);
if (cb)
cb();
+31
View File
@@ -518,6 +518,11 @@ declare namespace ts.server.protocol {
* Then the known content will be used upon opening instead of the disk copy
*/
fileContent?: string;
/**
* Used to specify the script kind of the file explicitly. It could be one of the following:
* "TS", "JS", "TSX", "JSX"
*/
scriptKindName?: "TS" | "JS" | "TSX" | "JSX";
}
/**
@@ -1005,6 +1010,32 @@ declare namespace ts.server.protocol {
body?: DiagnosticEventBody;
}
export interface ConfigFileDiagnosticEventBody {
/**
* The file which trigged the searching and error-checking of the config file
*/
triggerFile: string;
/**
* The name of the found config file.
*/
configFile: string;
/**
* An arry of diagnostic information items for the found config file.
*/
diagnostics: Diagnostic[];
}
/**
* Event message for "configFileDiag" event type.
* This event provides errors for a found config file.
*/
export interface ConfigFileDiagnosticEvent extends Event {
body?: ConfigFileDiagnosticEventBody;
event: "configFileDiag";
}
/**
* Arguments for reload request.
*/
+106 -3
View File
@@ -153,6 +153,98 @@ namespace ts.server {
// This places log file in the directory containing editorServices.js
// TODO: check that this location is writable
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
function createPollingWatchedFileSet(interval = 2500, chunkSize = 30) {
let watchedFiles: WatchedFile[] = [];
let nextFileToCheck = 0;
let watchTimer: any;
function getModifiedTime(fileName: string): Date {
return fs.statSync(fileName).mtime;
}
function poll(checkedIndex: number) {
const watchedFile = watchedFiles[checkedIndex];
if (!watchedFile) {
return;
}
fs.stat(watchedFile.fileName, (err: any, stats: any) => {
if (err) {
watchedFile.callback(watchedFile.fileName);
}
else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
watchedFile.mtime = getModifiedTime(watchedFile.fileName);
watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);
}
});
}
// this implementation uses polling and
// stat due to inconsistencies of fs.watch
// and efficiency of stat on modern filesystems
function startWatchTimer() {
watchTimer = setInterval(() => {
let count = 0;
let nextToCheck = nextFileToCheck;
let firstCheck = -1;
while ((count < chunkSize) && (nextToCheck !== firstCheck)) {
poll(nextToCheck);
if (firstCheck < 0) {
firstCheck = nextToCheck;
}
nextToCheck++;
if (nextToCheck === watchedFiles.length) {
nextToCheck = 0;
}
count++;
}
nextFileToCheck = nextToCheck;
}, interval);
}
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
const file: WatchedFile = {
fileName,
callback,
mtime: getModifiedTime(fileName)
};
watchedFiles.push(file);
if (watchedFiles.length === 1) {
startWatchTimer();
}
return file;
}
function removeFile(file: WatchedFile) {
watchedFiles = copyListRemovingItem(file, watchedFiles);
}
return {
getModifiedTime: getModifiedTime,
poll: poll,
startWatchTimer: startWatchTimer,
addFile: addFile,
removeFile: removeFile
};
}
// 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
// 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
// pause less than 1.5 milliseconds); question is
// do we anticipate reference sets in the 100s and
// do we care about waiting 10-20 seconds to detect
// 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 logger = createLoggerFromEnv();
const pending: string[] = [];
@@ -174,10 +266,21 @@ namespace ts.server {
}
}
// Override sys.write because fs.writeSync is not reliable on Node 4
ts.sys.write = (s: string) => writeMessage(s);
const sys = <ServerHost>ts.sys;
const ioSession = new IOSession(ts.sys, logger);
// Override sys.write because fs.writeSync is not reliable on Node 4
sys.write = (s: string) => writeMessage(s);
sys.watchFile = (fileName, callback) => {
const watchedFile = pollingWatchedFileSet.addFile(fileName, callback);
return {
close: () => pollingWatchedFileSet.removeFile(watchedFile)
};
};
sys.setTimeout = setTimeout;
sys.clearTimeout = clearTimeout;
const ioSession = new IOSession(sys, logger);
process.on("uncaughtException", function(err: Error) {
ioSession.logError(err, "unknown");
});
+223 -129
View File
@@ -68,7 +68,7 @@ namespace ts.server {
}
}
function formatDiag(fileName: string, project: Project, diag: ts.Diagnostic) {
function formatDiag(fileName: string, project: Project, diag: ts.Diagnostic): protocol.Diagnostic {
return {
start: project.compilerService.host.positionToLineOffset(fileName, diag.start),
end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length),
@@ -76,6 +76,14 @@ namespace ts.server {
};
}
function formatConfigFileDiag(diag: ts.Diagnostic): protocol.Diagnostic {
return {
start: undefined,
end: undefined,
text: ts.flattenDiagnosticMessageText(diag.messageText, "\n")
};
}
export interface PendingErrorCheck {
fileName: string;
project: Project;
@@ -125,6 +133,8 @@ namespace ts.server {
}
export interface ServerHost extends ts.System {
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
clearTimeout(timeoutId: any): void;
}
export class Session {
@@ -141,8 +151,8 @@ namespace ts.server {
) {
this.projectService =
new ProjectService(host, logger, (eventName, project, fileName) => {
this.handleEvent(eventName, project, fileName);
});
this.handleEvent(eventName, project, fileName);
});
}
private handleEvent(eventName: string, project: Project, fileName: string) {
@@ -178,6 +188,21 @@ namespace ts.server {
"\r\n\r\n" + json);
}
public configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]) {
const bakedDiags = ts.map(diagnostics, formatConfigFileDiag);
const ev: protocol.ConfigFileDiagnosticEvent = {
seq: 0,
type: "event",
event: "configFileDiag",
body: {
triggerFile,
configFile,
diagnostics: bakedDiags
}
};
this.send(ev);
}
public event(info: any, eventName: string) {
const ev: protocol.Event = {
seq: 0,
@@ -412,14 +437,17 @@ namespace ts.server {
private getRenameLocations(line: number, offset: number, fileName: string, findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody {
const file = ts.normalizePath(fileName);
const project = this.projectService.getProjectForFile(file);
if (!project) {
const info = this.projectService.getScriptInfo(file);
const projects = this.projectService.findReferencingProjects(info);
if (!projects.length) {
throw Errors.NoProject;
}
const compilerService = project.compilerService;
const position = compilerService.host.lineOffsetToPosition(file, line, offset);
const renameInfo = compilerService.languageService.getRenameInfo(file, position);
const defaultProject = projects[0];
// The rename info should be the same for every project
const defaultProjectCompilerService = defaultProject.compilerService;
const position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset);
const renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position);
if (!renameInfo) {
return undefined;
}
@@ -431,16 +459,43 @@ namespace ts.server {
};
}
const renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments);
if (!renameLocations) {
return undefined;
}
const fileSpans = combineProjectOutput(
projects,
(project: Project) => {
const compilerService = project.compilerService;
const renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments);
if (!renameLocations) {
return [];
}
const bakedRenameLocs = renameLocations.map(location => (<protocol.FileSpan>{
file: location.fileName,
start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start),
end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)),
})).sort((a, b) => {
return renameLocations.map(location => (<protocol.FileSpan>{
file: location.fileName,
start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start),
end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)),
}));
},
compareRenameLocation,
(a, b) => a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset
);
const locs = fileSpans.reduce<protocol.SpanGroup[]>((accum, cur) => {
let curFileAccum: protocol.SpanGroup;
if (accum.length > 0) {
curFileAccum = accum[accum.length - 1];
if (curFileAccum.file !== cur.file) {
curFileAccum = undefined;
}
}
if (!curFileAccum) {
curFileAccum = { file: cur.file, locs: [] };
accum.push(curFileAccum);
}
curFileAccum.locs.push({ start: cur.start, end: cur.end });
return accum;
}, []);
return { info: renameInfo, locs };
function compareRenameLocation(a: protocol.FileSpan, b: protocol.FileSpan) {
if (a.file < b.file) {
return -1;
}
@@ -459,79 +514,82 @@ namespace ts.server {
return b.start.offset - a.start.offset;
}
}
}).reduce<protocol.SpanGroup[]>((accum: protocol.SpanGroup[], cur: protocol.FileSpan) => {
let curFileAccum: protocol.SpanGroup;
if (accum.length > 0) {
curFileAccum = accum[accum.length - 1];
if (curFileAccum.file != cur.file) {
curFileAccum = undefined;
}
}
if (!curFileAccum) {
curFileAccum = { file: cur.file, locs: [] };
accum.push(curFileAccum);
}
curFileAccum.locs.push({ start: cur.start, end: cur.end });
return accum;
}, []);
return { info: renameInfo, locs: bakedRenameLocs };
}
}
private getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody {
// TODO: get all projects for this file; report refs for all projects deleting duplicates
// can avoid duplicates by eliminating same ref file from subsequent projects
const file = ts.normalizePath(fileName);
const project = this.projectService.getProjectForFile(file);
if (!project) {
const info = this.projectService.getScriptInfo(file);
const projects = this.projectService.findReferencingProjects(info);
if (!projects.length) {
throw Errors.NoProject;
}
const compilerService = project.compilerService;
const position = compilerService.host.lineOffsetToPosition(file, line, offset);
const references = compilerService.languageService.getReferencesAtPosition(file, position);
if (!references) {
return undefined;
}
const nameInfo = compilerService.languageService.getQuickInfoAtPosition(file, position);
const defaultProject = projects[0];
const position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset);
const nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position);
if (!nameInfo) {
return undefined;
}
const displayString = ts.displayPartsToString(nameInfo.displayParts);
const nameSpan = nameInfo.textSpan;
const nameColStart = compilerService.host.positionToLineOffset(file, nameSpan.start).offset;
const nameText = compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan));
const bakedRefs: protocol.ReferencesResponseItem[] = references.map(ref => {
const start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start);
const refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1);
const snap = compilerService.host.getScriptSnapshot(ref.fileName);
const lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
return {
file: ref.fileName,
start: start,
lineText: lineText,
end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)),
isWriteAccess: ref.isWriteAccess
};
}).sort(compareFileStart);
const nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset;
const nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan));
const refs = combineProjectOutput<protocol.ReferencesResponseItem>(
projects,
(project: Project) => {
const compilerService = project.compilerService;
const references = compilerService.languageService.getReferencesAtPosition(file, position);
if (!references) {
return [];
}
return references.map(ref => {
const start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start);
const refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1);
const snap = compilerService.host.getScriptSnapshot(ref.fileName);
const lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, "");
return {
file: ref.fileName,
start: start,
lineText: lineText,
end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)),
isWriteAccess: ref.isWriteAccess
};
});
},
compareFileStart,
areReferencesResponseItemsForTheSameLocation
);
return {
refs: bakedRefs,
refs,
symbolName: nameText,
symbolStartOffset: nameColStart,
symbolDisplayString: displayString
};
function areReferencesResponseItemsForTheSameLocation(a: protocol.ReferencesResponseItem, b: protocol.ReferencesResponseItem) {
if (a && b) {
return a.file === b.file &&
a.start === b.start &&
a.end === b.end;
}
return false;
}
}
/**
* @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) {
private openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind) {
const file = ts.normalizePath(fileName);
this.projectService.openClientFile(file, fileContent);
const { configFileName, configFileErrors } = this.projectService.openClientFile(file, fileContent, scriptKind);
if (configFileErrors) {
this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors);
}
}
private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
@@ -617,7 +675,7 @@ namespace ts.server {
const editorOptions: ts.EditorOptions = {
IndentSize: formatOptions.IndentSize,
TabSize: formatOptions.TabSize,
NewLineCharacter: "\n",
NewLineCharacter: formatOptions.NewLineCharacter,
ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces,
IndentStyle: ts.IndentStyle.Smart,
};
@@ -836,41 +894,60 @@ namespace ts.server {
private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] {
const file = ts.normalizePath(fileName);
const project = this.projectService.getProjectForFile(file);
if (!project) {
const info = this.projectService.getScriptInfo(file);
const projects = this.projectService.findReferencingProjects(info);
const defaultProject = projects[0];
if (!defaultProject) {
throw Errors.NoProject;
}
const compilerService = project.compilerService;
const navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount);
if (!navItems) {
return undefined;
}
const allNavToItems = combineProjectOutput(
projects,
(project: Project) => {
const compilerService = project.compilerService;
const navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount);
if (!navItems) {
return [];
}
return navItems.map((navItem) => {
const start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start);
const end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan));
const bakedItem: protocol.NavtoItem = {
name: navItem.name,
kind: navItem.kind,
file: navItem.fileName,
start: start,
end: end,
};
if (navItem.kindModifiers && (navItem.kindModifiers != "")) {
bakedItem.kindModifiers = navItem.kindModifiers;
return navItems.map((navItem) => {
const start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start);
const end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan));
const bakedItem: protocol.NavtoItem = {
name: navItem.name,
kind: navItem.kind,
file: navItem.fileName,
start: start,
end: end,
};
if (navItem.kindModifiers && (navItem.kindModifiers !== "")) {
bakedItem.kindModifiers = navItem.kindModifiers;
}
if (navItem.matchKind !== "none") {
bakedItem.matchKind = navItem.matchKind;
}
if (navItem.containerName && (navItem.containerName.length > 0)) {
bakedItem.containerName = navItem.containerName;
}
if (navItem.containerKind && (navItem.containerKind.length > 0)) {
bakedItem.containerKind = navItem.containerKind;
}
return bakedItem;
});
},
/*comparer*/ undefined,
areNavToItemsForTheSameLocation
);
return allNavToItems;
function areNavToItemsForTheSameLocation(a: protocol.NavtoItem, b: protocol.NavtoItem) {
if (a && b) {
return a.file === b.file &&
a.start === b.start &&
a.end === b.end;
}
if (navItem.matchKind !== "none") {
bakedItem.matchKind = navItem.matchKind;
}
if (navItem.containerName && (navItem.containerName.length > 0)) {
bakedItem.containerName = navItem.containerName;
}
if (navItem.containerKind && (navItem.containerKind.length > 0)) {
bakedItem.containerKind = navItem.containerKind;
}
return bakedItem;
});
return false;
}
}
private getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] {
@@ -944,129 +1021,146 @@ namespace ts.server {
exit() {
}
private handlers: Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = {
private handlers: Map<(request: protocol.Request) => { response?: any, responseRequired?: boolean }> = {
[CommandNames.Exit]: () => {
this.exit();
return { responseRequired: false};
return { responseRequired: false };
},
[CommandNames.Definition]: (request: protocol.Request) => {
const defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true};
return { response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
[CommandNames.TypeDefinition]: (request: protocol.Request) => {
const defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true};
return { response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
[CommandNames.References]: (request: protocol.Request) => {
const defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true};
return { response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true };
},
[CommandNames.Rename]: (request: protocol.Request) => {
const renameArgs = <protocol.RenameRequestArgs>request.arguments;
return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true};
return { response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true };
},
[CommandNames.Open]: (request: protocol.Request) => {
const openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file, openArgs.fileContent);
return {responseRequired: false};
let scriptKind: ScriptKind;
switch (openArgs.scriptKindName) {
case "TS":
scriptKind = ScriptKind.TS;
break;
case "JS":
scriptKind = ScriptKind.JS;
break;
case "TSX":
scriptKind = ScriptKind.TSX;
break;
case "JSX":
scriptKind = ScriptKind.JSX;
break;
}
this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind);
return { responseRequired: false };
},
[CommandNames.Quickinfo]: (request: protocol.Request) => {
const quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true};
return { response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true };
},
[CommandNames.Format]: (request: protocol.Request) => {
const formatArgs = <protocol.FormatRequestArgs>request.arguments;
return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true};
return { response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true };
},
[CommandNames.Formatonkey]: (request: protocol.Request) => {
const formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments;
return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true};
return { response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true };
},
[CommandNames.Completions]: (request: protocol.Request) => {
const completionsArgs = <protocol.CompletionsRequestArgs>request.arguments;
return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true};
return { response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true };
},
[CommandNames.CompletionDetails]: (request: protocol.Request) => {
const completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments;
return {response: this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset,
completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true};
return {
response: this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset,
completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true
};
},
[CommandNames.SignatureHelp]: (request: protocol.Request) => {
const signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments;
return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true};
return { response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true };
},
[CommandNames.Geterr]: (request: protocol.Request) => {
const geterrArgs = <protocol.GeterrRequestArgs>request.arguments;
return {response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false};
return { response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false };
},
[CommandNames.GeterrForProject]: (request: protocol.Request) => {
const { file, delay } = <protocol.GeterrForProjectRequestArgs>request.arguments;
return {response: this.getDiagnosticsForProject(delay, file), responseRequired: false};
return { response: this.getDiagnosticsForProject(delay, file), responseRequired: false };
},
[CommandNames.Change]: (request: protocol.Request) => {
const changeArgs = <protocol.ChangeRequestArgs>request.arguments;
this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset,
changeArgs.insertString, changeArgs.file);
return {responseRequired: false};
changeArgs.insertString, changeArgs.file);
return { responseRequired: false };
},
[CommandNames.Configure]: (request: protocol.Request) => {
const configureArgs = <protocol.ConfigureRequestArguments>request.arguments;
this.projectService.setHostConfiguration(configureArgs);
this.output(undefined, CommandNames.Configure, request.seq);
return {responseRequired: false};
return { responseRequired: false };
},
[CommandNames.Reload]: (request: protocol.Request) => {
const reloadArgs = <protocol.ReloadRequestArgs>request.arguments;
this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq);
return {responseRequired: false};
return {response: { reloadFinished: true }, responseRequired: true};
},
[CommandNames.Saveto]: (request: protocol.Request) => {
const savetoArgs = <protocol.SavetoRequestArgs>request.arguments;
this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile);
return {responseRequired: false};
return { responseRequired: false };
},
[CommandNames.Close]: (request: protocol.Request) => {
const closeArgs = <protocol.FileRequestArgs>request.arguments;
this.closeClientFile(closeArgs.file);
return {responseRequired: false};
return { responseRequired: false };
},
[CommandNames.Navto]: (request: protocol.Request) => {
const navtoArgs = <protocol.NavtoRequestArgs>request.arguments;
return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true};
return { response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true };
},
[CommandNames.Brace]: (request: protocol.Request) => {
const braceArguments = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true};
return { response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true };
},
[CommandNames.NavBar]: (request: protocol.Request) => {
const navBarArgs = <protocol.FileRequestArgs>request.arguments;
return {response: this.getNavigationBarItems(navBarArgs.file), responseRequired: true};
return { response: this.getNavigationBarItems(navBarArgs.file), responseRequired: true };
},
[CommandNames.Occurrences]: (request: protocol.Request) => {
const { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getOccurrences(line, offset, fileName), responseRequired: true};
return { response: this.getOccurrences(line, offset, fileName), responseRequired: true };
},
[CommandNames.DocumentHighlights]: (request: protocol.Request) => {
const { line, offset, file: fileName, filesToSearch } = <protocol.DocumentHighlightsRequestArgs>request.arguments;
return {response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true};
return { response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true };
},
[CommandNames.ProjectInfo]: (request: protocol.Request) => {
const { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments;
return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true};
return { response: this.getProjectInfo(file, needFileNameList), responseRequired: true };
},
[CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => {
this.reloadProjects();
return {responseRequired: false};
return { responseRequired: false };
}
};
public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) {
public addProtocolHandler(command: string, handler: (request: protocol.Request) => { response?: any, responseRequired: boolean }) {
if (this.handlers[command]) {
throw new Error(`Protocol handler already exists for command "${command}"`);
}
this.handlers[command] = handler;
}
public executeCommand(request: protocol.Request): {response?: any, responseRequired?: boolean} {
public executeCommand(request: protocol.Request): { response?: any, responseRequired?: boolean } {
const handler = this.handlers[request.command];
if (handler) {
return handler(request);
@@ -1074,7 +1168,7 @@ namespace ts.server {
else {
this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request));
this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command);
return {responseRequired: false};
return { responseRequired: false };
}
}
+21 -21
View File
@@ -15,7 +15,7 @@ namespace ts.BreakpointResolver {
}
let tokenAtLocation = getTokenAtPosition(sourceFile, position);
let lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
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
@@ -24,7 +24,7 @@ namespace ts.BreakpointResolver {
// token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
tokenAtLocation = findPrecedingToken(tokenAtLocation.pos, sourceFile);
// Its a blank line
// It's a blank line
if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) {
return undefined;
}
@@ -216,7 +216,7 @@ namespace ts.BreakpointResolver {
return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile));
case SyntaxKind.CommaToken:
return spanInPreviousNode(node)
return spanInPreviousNode(node);
case SyntaxKind.OpenBraceToken:
return spanInOpenBraceToken(node);
@@ -312,7 +312,7 @@ namespace ts.BreakpointResolver {
case SyntaxKind.BinaryExpression:
if ((<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.CommaToken) {
// if this is comma expression, the breakpoint is possible in this expression
// If this is a comma expression, the breakpoint is possible in this expression
return textSpan(node);
}
break;
@@ -370,7 +370,7 @@ namespace ts.BreakpointResolver {
}
function textSpanFromVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan {
let declarations = variableDeclaration.parent.declarations;
const declarations = variableDeclaration.parent.declarations;
if (declarations && declarations[0] === variableDeclaration) {
// First declaration - include let keyword
return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
@@ -387,7 +387,7 @@ namespace ts.BreakpointResolver {
return spanInNode(variableDeclaration.parent.parent);
}
// If this is a destructuring pattern set breakpoint in binding pattern
// If this is a destructuring pattern, set breakpoint in binding pattern
if (isBindingPattern(variableDeclaration.name)) {
return spanInBindingPattern(<BindingPattern>variableDeclaration.name);
}
@@ -400,11 +400,11 @@ namespace ts.BreakpointResolver {
return textSpanFromVariableDeclaration(variableDeclaration);
}
let declarations = variableDeclaration.parent.declarations;
const declarations = variableDeclaration.parent.declarations;
if (declarations && declarations[0] !== variableDeclaration) {
// If we cant set breakpoint on this declaration, set it on previous one
// If we cannot set breakpoint on this declaration, set it on previous one
// Because the variable declaration may be binding pattern and
// we would like to set breakpoint in last binding element if thats the case,
// we would like to set breakpoint in last binding element if that's the case,
// use preceding token instead
return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
}
@@ -418,15 +418,15 @@ namespace ts.BreakpointResolver {
function spanInParameterDeclaration(parameter: ParameterDeclaration): TextSpan {
if (isBindingPattern(parameter.name)) {
// set breakpoint in binding pattern
// Set breakpoint in binding pattern
return spanInBindingPattern(<BindingPattern>parameter.name);
}
else if (canHaveSpanInParameterDeclaration(parameter)) {
return textSpan(parameter);
}
else {
let functionDeclaration = <FunctionLikeDeclaration>parameter.parent;
let indexOfParameter = indexOf(functionDeclaration.parameters, parameter);
const functionDeclaration = <FunctionLikeDeclaration>parameter.parent;
const indexOfParameter = indexOf(functionDeclaration.parameters, parameter);
if (indexOfParameter) {
// Not a first parameter, go to previous parameter
return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
@@ -459,7 +459,7 @@ namespace ts.BreakpointResolver {
}
function spanInFunctionBlock(block: Block): TextSpan {
let nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
if (canFunctionHaveSpanInWholeDeclaration(<FunctionLikeDeclaration>block.parent)) {
return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
}
@@ -492,8 +492,8 @@ namespace ts.BreakpointResolver {
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;
// Declaration list - set breakpoint in first declaration
const variableDeclarationList = <VariableDeclarationList>forLikeStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
}
@@ -519,7 +519,7 @@ namespace ts.BreakpointResolver {
function spanInBindingPattern(bindingPattern: BindingPattern): TextSpan {
// Set breakpoint in first binding element
let firstBindingElement = forEach(bindingPattern.elements,
const firstBindingElement = forEach(bindingPattern.elements,
element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);
if (firstBindingElement) {
@@ -578,7 +578,7 @@ namespace ts.BreakpointResolver {
function spanInCloseBraceToken(node: Node): TextSpan {
switch (node.parent.kind) {
case SyntaxKind.ModuleBlock:
// If this is not instantiated module block no bp span
// If this is not an instantiated module block, no bp span
if (getModuleInstanceState(node.parent.parent) !== ModuleInstanceState.Instantiated) {
return undefined;
}
@@ -593,7 +593,7 @@ namespace ts.BreakpointResolver {
// Span on close brace token
return textSpan(node);
}
// fall through.
// fall through
case SyntaxKind.CatchClause:
return spanInNode(lastOrUndefined((<Block>node.parent).statements));
@@ -616,7 +616,7 @@ namespace ts.BreakpointResolver {
default:
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Breakpoint in last binding element or binding pattern if it contains no elements
let objectLiteral = <ObjectLiteralExpression>node.parent;
const objectLiteral = <ObjectLiteralExpression>node.parent;
return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral);
}
return spanInNode(node.parent);
@@ -633,7 +633,7 @@ namespace ts.BreakpointResolver {
default:
if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
// Breakpoint in last binding element or binding pattern if it contains no elements
let arrayLiteral = <ArrayLiteralExpression>node.parent;
const arrayLiteral = <ArrayLiteralExpression>node.parent;
return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
}
@@ -714,7 +714,7 @@ namespace ts.BreakpointResolver {
function spanInOfKeyword(node: Node): TextSpan {
if (node.parent.kind === SyntaxKind.ForOfStatement) {
// set using next token
// Set using next token
return spanInNextNode(node);
}
+147 -148
View File
@@ -20,14 +20,14 @@ namespace ts.formatting {
Unknown = -1
}
/*
/*
* Indentation for the scope that can be dynamically recomputed.
* i.e
* i.e
* while(true)
* { let x;
* }
* Normally indentation is applied only to the first token in line so at glance 'var' should not be touched.
* However if some format rule adds new line between '}' and 'var' 'var' will become
* Normally indentation is applied only to the first token in line so at glance 'let' should not be touched.
* However if some format rule adds new line between '}' and 'let' 'let' will become
* the first token in line so it should be indented
*/
interface DynamicIndentation {
@@ -48,15 +48,15 @@ namespace ts.formatting {
* foo(bar({
* $
* }))
* Both 'foo', 'bar' introduce new indentation with delta = 4, but total indentation in $ is not 8.
* Both 'foo', 'bar' introduce new indentation with delta = 4, but total indentation in $ is not 8.
* foo: { indentation: 0, delta: 4 }
* bar: { indentation: foo.indentation + foo.delta = 4, delta: 4} however 'foo' and 'bar' are on the same line
* so bar inherits indentation from foo and bar.delta will be 4
*
*
*/
getDelta(child: TextRangeWithKind): number;
/**
* Formatter calls this function when rule adds or deletes new lines from the text
* Formatter calls this function when rule adds or deletes new lines from the text
* so indentation scope can adjust values of indentation and delta.
*/
recomputeIndentation(lineAddedByFormatting: boolean): void;
@@ -64,11 +64,11 @@ namespace ts.formatting {
interface Indentation {
indentation: number;
delta: number
delta: number;
}
export function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[] {
let line = sourceFile.getLineAndCharacterOfPosition(position).line;
const line = sourceFile.getLineAndCharacterOfPosition(position).line;
if (line === 0) {
return [];
}
@@ -81,12 +81,12 @@ namespace ts.formatting {
while (isWhiteSpace(sourceFile.text.charCodeAt(endOfFormatSpan)) && !isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
let span = {
const span = {
// get start position for the previous line
pos: getStartPositionOfLine(line - 1, sourceFile),
// end value is exclusive so add 1 to the result
end: endOfFormatSpan + 1
}
};
return formatSpan(span, sourceFile, options, rulesProvider, FormattingRequestKind.FormatOnEnter);
}
@@ -99,7 +99,7 @@ namespace ts.formatting {
}
export function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[] {
let span = {
const span = {
pos: 0,
end: sourceFile.text.length
};
@@ -108,7 +108,7 @@ namespace ts.formatting {
export function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[] {
// format from the beginning of the line
let span = {
const span = {
pos: getLineStartPositionForPosition(start, sourceFile),
end: end
};
@@ -116,11 +116,11 @@ namespace ts.formatting {
}
function formatOutermostParent(position: number, expectedLastToken: SyntaxKind, sourceFile: SourceFile, options: FormatCodeOptions, rulesProvider: RulesProvider, requestKind: FormattingRequestKind): TextChange[] {
let parent = findOutermostParent(position, expectedLastToken, sourceFile);
const parent = findOutermostParent(position, expectedLastToken, sourceFile);
if (!parent) {
return [];
}
let span = {
const span = {
pos: getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile),
end: parent.end
};
@@ -128,11 +128,11 @@ namespace ts.formatting {
}
function findOutermostParent(position: number, expectedTokenKind: SyntaxKind, sourceFile: SourceFile): Node {
let precedingToken = findPrecedingToken(position, sourceFile);
const precedingToken = findPrecedingToken(position, sourceFile);
// when it is claimed that trigger character was typed at given position
// 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,
// If this condition is not hold - then trigger character was typed in some other context,
// i.e.in comment and thus should not trigger autoformatting
if (!precedingToken ||
precedingToken.kind !== expectedTokenKind ||
@@ -142,12 +142,12 @@ namespace ts.formatting {
// walk up and search for the parent node that ends at the same position with precedingToken.
// for cases like this
//
//
// let x = 1;
// while (true) {
// }
// }
// after typing close curly in while statement we want to reformat just the while statement.
// However if we just walk upwards searching for the parent that has the same end value -
// However if we just walk upwards searching for the parent that has the same end value -
// we'll end up with the whole source file. isListElement allows to stop on the list element level
let current = precedingToken;
while (current &&
@@ -168,7 +168,7 @@ namespace ts.formatting {
case SyntaxKind.InterfaceDeclaration:
return rangeContainsRange((<InterfaceDeclaration>parent).members, node);
case SyntaxKind.ModuleDeclaration:
let body = (<ModuleDeclaration>parent).body;
const body = (<ModuleDeclaration>parent).body;
return body && body.kind === SyntaxKind.Block && rangeContainsRange((<Block>body).statements, node);
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
@@ -186,9 +186,9 @@ namespace ts.formatting {
return find(sourceFile);
function find(n: Node): Node {
let candidate = forEachChild(n, c => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c);
const candidate = forEachChild(n, c => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c);
if (candidate) {
let result = find(candidate);
const result = find(candidate);
if (result) {
return result;
}
@@ -208,7 +208,7 @@ namespace ts.formatting {
}
// pick only errors that fall in range
let sorted = errors
const sorted = errors
.filter(d => rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length))
.sort((e1, e2) => e1.start - e2.start);
@@ -223,11 +223,11 @@ namespace ts.formatting {
// 'index' tracks the index of the most recent error that was checked.
while (true) {
if (index >= sorted.length) {
// all errors in the range were already checked -> no error in specified range
// all errors in the range were already checked -> no error in specified range
return false;
}
let error = sorted[index];
const error = sorted[index];
if (r.end <= error.start) {
// specified range ends before the error refered by 'index' - no error in range
return false;
@@ -249,16 +249,16 @@ namespace ts.formatting {
/**
* Start of the original range might fall inside the comment - scanner will not yield appropriate results
* This function will look for token that is located before the start of target range
* This function will look for token that is located before the start of target range
* and return its end as start position for the scanner.
*/
function getScanStartPosition(enclosingNode: Node, originalRange: TextRange, sourceFile: SourceFile): number {
let start = enclosingNode.getStart(sourceFile);
const start = enclosingNode.getStart(sourceFile);
if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
return start;
}
let precedingToken = findPrecedingToken(originalRange.pos, sourceFile);
const precedingToken = findPrecedingToken(originalRange.pos, sourceFile);
if (!precedingToken) {
// no preceding token found - start from the beginning of enclosing node
return enclosingNode.pos;
@@ -274,7 +274,7 @@ namespace ts.formatting {
}
/*
* For cases like
* For cases like
* if (a ||
* b ||$
* c) {...}
@@ -284,15 +284,15 @@ namespace ts.formatting {
* Initial indentation for this node will be 0.
* Binary expressions don't introduce new indentation scopes, however it is possible
* that some parent node on the same line does - like if statement in this case.
* Note that we are considering parents only from the same line with initial node -
* if parent is on the different line - its delta was already contributed
* Note that we are considering parents only from the same line with initial node -
* if parent is on the different line - its delta was already contributed
* to the initial indentation.
*/
function getOwnOrInheritedDelta(n: Node, options: FormatCodeOptions, sourceFile: SourceFile): number {
let previousLine = Constants.Unknown;
let child: Node;
while (n) {
let line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
const line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
if (previousLine !== Constants.Unknown && line !== previousLine) {
break;
}
@@ -314,17 +314,17 @@ namespace ts.formatting {
rulesProvider: RulesProvider,
requestKind: FormattingRequestKind): TextChange[] {
let rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange);
const rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange);
// formatting context is used by rules provider
let formattingContext = new FormattingContext(sourceFile, requestKind);
const formattingContext = new FormattingContext(sourceFile, requestKind);
// find the smallest node that fully wraps the range and compute the initial indentation for the node
let enclosingNode = findEnclosingNode(originalRange, sourceFile);
const enclosingNode = findEnclosingNode(originalRange, sourceFile);
let formattingScanner = getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end);
const formattingScanner = getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end);
let initialIndentation = SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options);
const initialIndentation = SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options);
let previousRangeHasError: boolean;
let previousRange: TextRangeWithKind;
@@ -334,23 +334,23 @@ namespace ts.formatting {
let lastIndentedLine: number;
let indentationOnLastIndentedLine: number;
let edits: TextChange[] = [];
const edits: TextChange[] = [];
formattingScanner.advance();
if (formattingScanner.isOnToken()) {
let startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
const startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
let undecoratedStartLine = startLine;
if (enclosingNode.decorators) {
undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
}
let delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile);
const delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile);
processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
}
if (!formattingScanner.isOnToken()) {
let leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
const leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
if (leadingTrivia) {
processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined);
trimTrailingWhitespacesForRemainingRange();
@@ -364,10 +364,10 @@ namespace ts.formatting {
// local functions
/** Tries to compute the indentation for a list element.
* If list element is not in range then
* function will pick its actual indentation
* If list element is not in range then
* function will pick its actual indentation
* so it can be pushed downstream as inherited indentation.
* If list element is in the range - its indentation will be equal
* If list element is in the range - its indentation will be equal
* to inherited indentation from its predecessors.
*/
function tryComputeIndentationForListItem(startPos: number,
@@ -378,17 +378,17 @@ namespace ts.formatting {
if (rangeOverlapsWithStartEnd(range, startPos, endPos) ||
rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
if (inheritedIndentation !== Constants.Unknown) {
return inheritedIndentation;
}
}
else {
let startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
let startLinePosition = getLineStartPositionForPosition(startPos, sourceFile);
let column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
const startLinePosition = getLineStartPositionForPosition(startPos, sourceFile);
const column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
if (startLine !== parentStartLine || startPos === column) {
return column
return column;
}
}
@@ -404,7 +404,7 @@ namespace ts.formatting {
effectiveParentStartLine: number): Indentation {
let indentation = inheritedIndentation;
var delta = SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
let delta = SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0;
if (effectiveParentStartLine === startLine) {
// if node is located on the same line with the parent
@@ -427,7 +427,7 @@ namespace ts.formatting {
return {
indentation,
delta
}
};
}
function getFirstNonDecoratorTokenOfNode(node: Node) {
@@ -511,7 +511,7 @@ namespace ts.formatting {
}
}
}
}
};
function getEffectiveDelta(delta: number, child: TextRangeWithKind) {
// Delta value should be zero when the node explicitly prevents indentation of the child node
@@ -524,17 +524,17 @@ namespace ts.formatting {
return;
}
let nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
const nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
// a useful observations when tracking context node
// /
// [a]
// / | \
// / | \
// [b] [c] [d]
// node 'a' is a context node for nodes 'b', 'c', 'd'
// node 'a' is a context node for nodes 'b', 'c', 'd'
// except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
// this rule can be applied recursively to child nodes of 'a'.
//
//
// context node is set to parent node value after processing every child node
// context node is set to parent of the token after processing every token
@@ -545,7 +545,7 @@ namespace ts.formatting {
forEachChild(
node,
child => {
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false)
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
},
(nodes: NodeArray<Node>) => {
processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
@@ -553,7 +553,7 @@ namespace ts.formatting {
// proceed any tokens in the node that are located after child nodes
while (formattingScanner.isOnToken()) {
let tokenInfo = formattingScanner.readTokenInfo(node);
const tokenInfo = formattingScanner.readTokenInfo(node);
if (tokenInfo.token.end > node.end) {
break;
}
@@ -567,11 +567,12 @@ namespace ts.formatting {
parentDynamicIndentation: DynamicIndentation,
parentStartLine: number,
undecoratedParentStartLine: number,
isListItem: boolean): number {
isListItem: boolean,
isFirstListItem?: boolean): number {
let childStartPos = child.getStart(sourceFile);
const childStartPos = child.getStart(sourceFile);
let childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
const childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
let undecoratedChildStartLine = childStartLine;
if (child.decorators) {
@@ -598,7 +599,7 @@ namespace ts.formatting {
while (formattingScanner.isOnToken()) {
// proceed any parent tokens that are located prior to child.getStart()
let tokenInfo = formattingScanner.readTokenInfo(node);
const tokenInfo = formattingScanner.readTokenInfo(node);
if (tokenInfo.token.end > childStartPos) {
// stop when formatting scanner advances past the beginning of the child
break;
@@ -613,19 +614,23 @@ namespace ts.formatting {
if (isToken(child)) {
// if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
let tokenInfo = formattingScanner.readTokenInfo(child);
const tokenInfo = formattingScanner.readTokenInfo(child);
Debug.assert(tokenInfo.token.end === child.end);
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
return inheritedIndentation;
}
let effectiveParentStartLine = child.kind === SyntaxKind.Decorator ? childStartLine : undecoratedParentStartLine;
let childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
const effectiveParentStartLine = child.kind === SyntaxKind.Decorator ? childStartLine : undecoratedParentStartLine;
const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
childContextNode = node;
if (isFirstListItem && parent.kind === SyntaxKind.ArrayLiteralExpression && inheritedIndentation === Constants.Unknown) {
inheritedIndentation = childIndentation.indentation;
}
return inheritedIndentation;
}
@@ -634,8 +639,8 @@ namespace ts.formatting {
parentStartLine: number,
parentDynamicIndentation: DynamicIndentation): void {
let listStartToken = getOpenTokenForList(parent, nodes);
let listEndToken = getCloseTokenForOpenToken(listStartToken);
const listStartToken = getOpenTokenForList(parent, nodes);
const listEndToken = getCloseTokenForOpenToken(listStartToken);
let listDynamicIndentation = parentDynamicIndentation;
let startLine = parentStartLine;
@@ -643,7 +648,7 @@ namespace ts.formatting {
if (listStartToken !== SyntaxKind.Unknown) {
// introduce a new indentation scope for lists (including list start and end tokens)
while (formattingScanner.isOnToken()) {
let tokenInfo = formattingScanner.readTokenInfo(parent);
const tokenInfo = formattingScanner.readTokenInfo(parent);
if (tokenInfo.token.end > nodes.pos) {
// stop when formatting scanner moves past the beginning of node list
break;
@@ -651,7 +656,7 @@ namespace ts.formatting {
else if (tokenInfo.token.kind === listStartToken) {
// consume list start token
startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
let indentation =
const indentation =
computeIndentation(tokenInfo.token, startLine, Constants.Unknown, parent, parentDynamicIndentation, parentStartLine);
listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation.indentation, indentation.delta);
@@ -665,16 +670,17 @@ namespace ts.formatting {
}
let inheritedIndentation = Constants.Unknown;
for (let child of nodes) {
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true)
for (let i = 0; i < nodes.length; i++) {
const child = nodes[i];
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0);
}
if (listEndToken !== SyntaxKind.Unknown) {
if (formattingScanner.isOnToken()) {
let tokenInfo = formattingScanner.readTokenInfo(parent);
const tokenInfo = formattingScanner.readTokenInfo(parent);
// consume the list end token only if it is still belong to the parent
// there might be the case when current token matches end token but does not considered as one
// function (x: function) <--
// function (x: function) <--
// without this check close paren will be interpreted as list end token for function expression which is wrong
if (tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) {
// consume list end token
@@ -687,7 +693,7 @@ namespace ts.formatting {
function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container?: Node): void {
Debug.assert(rangeContainsRange(parent, currentTokenInfo.token));
let lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
let indentToken = false;
if (currentTokenInfo.leadingTrivia) {
@@ -695,13 +701,13 @@ namespace ts.formatting {
}
let lineAdded: boolean;
let isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token);
const isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token);
let tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
const tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
if (isTokenInRange) {
let rangeHasError = rangeContainsError(currentTokenInfo.token);
const rangeHasError = rangeContainsError(currentTokenInfo.token);
// save previousRange since processRange will overwrite this value with current one
let savePreviousRange = previousRange;
const savePreviousRange = previousRange;
lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation);
if (rangeHasError) {
// do not indent comments\token if token range overlaps with some error
@@ -724,29 +730,28 @@ namespace ts.formatting {
}
if (indentToken) {
let tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
const tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) :
Constants.Unknown;
let indentNextTokenOrTrivia = true;
if (currentTokenInfo.leadingTrivia) {
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
let indentNextTokenOrTrivia = true;
for (let triviaItem of currentTokenInfo.leadingTrivia) {
if (!rangeContainsRange(originalRange, triviaItem)) {
continue;
}
const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
for (const triviaItem of currentTokenInfo.leadingTrivia) {
const triviaInRange = rangeContainsRange(originalRange, triviaItem);
switch (triviaItem.kind) {
case SyntaxKind.MultiLineCommentTrivia:
indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
if (triviaInRange) {
indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
}
indentNextTokenOrTrivia = false;
break;
case SyntaxKind.SingleLineCommentTrivia:
if (indentNextTokenOrTrivia) {
if (indentNextTokenOrTrivia && triviaInRange) {
insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false);
indentNextTokenOrTrivia = false;
}
indentNextTokenOrTrivia = false;
break;
case SyntaxKind.NewLineTrivia:
indentNextTokenOrTrivia = true;
@@ -756,7 +761,7 @@ namespace ts.formatting {
}
// indent token only if is it is in target range and does not overlap with any error ranges
if (tokenIndentation !== Constants.Unknown) {
if (tokenIndentation !== Constants.Unknown && indentNextTokenOrTrivia) {
insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded);
lastIndentedLine = tokenStart.line;
@@ -771,9 +776,9 @@ namespace ts.formatting {
}
function processTrivia(trivia: TextRangeWithKind[], parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): void {
for (let triviaItem of trivia) {
for (const triviaItem of trivia) {
if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) {
let triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
const triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation);
}
}
@@ -785,17 +790,17 @@ namespace ts.formatting {
contextNode: Node,
dynamicIndentation: DynamicIndentation): boolean {
let rangeHasError = rangeContainsError(range);
const rangeHasError = rangeContainsError(range);
let lineAdded: boolean;
if (!rangeHasError && !previousRangeHasError) {
if (!previousRange) {
// trim whitespaces starting from the beginning of the span up to the current line
let originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
const originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
}
else {
lineAdded =
processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation)
processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
}
}
@@ -818,7 +823,7 @@ namespace ts.formatting {
formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode);
let rule = rulesProvider.getRulesMap().GetRule(formattingContext);
const rule = rulesProvider.getRulesMap().GetRule(formattingContext);
let trimTrailingWhitespaces: boolean;
let lineAdded: boolean;
@@ -827,19 +832,19 @@ namespace ts.formatting {
if (rule.Operation.Action & (RuleAction.Space | RuleAction.Delete) && currentStartLine !== previousStartLine) {
lineAdded = false;
// Handle the case where the next line is moved to be the end of this line.
// Handle the case where the next line is moved to be the end of this line.
// In this case we don't indent the next line in the next pass.
if (currentParent.getStart(sourceFile) === currentItem.pos) {
dynamicIndentation.recomputeIndentation(/*lineAdded*/ false);
dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false);
}
}
else if (rule.Operation.Action & RuleAction.NewLine && currentStartLine === previousStartLine) {
lineAdded = true;
// Handle the case where token2 is moved to the new line.
// Handle the case where token2 is moved to the new line.
// In this case we indent token2 in the next pass but we set
// sameLineIndent flag to notify the indenter that the indentation is within the line.
if (currentParent.getStart(sourceFile) === currentItem.pos) {
dynamicIndentation.recomputeIndentation(/*lineAdded*/ true);
dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true);
}
}
@@ -859,25 +864,29 @@ namespace ts.formatting {
}
function insertIndentation(pos: number, indentation: number, lineAdded: boolean): void {
let indentationString = getIndentationString(indentation, options);
const indentationString = getIndentationString(indentation, options);
if (lineAdded) {
// new line is added before the token by the formatting rules
// insert indentation string at the very beginning of the token
recordReplace(pos, 0, indentationString);
}
else {
let tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
if (indentation !== tokenStart.character) {
let startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile);
const tokenStart = sourceFile.getLineAndCharacterOfPosition(pos);
const startLinePosition = getStartPositionOfLine(tokenStart.line, sourceFile);
if (indentation !== tokenStart.character || indentationIsDifferent(indentationString, startLinePosition)) {
recordReplace(startLinePosition, tokenStart.character, indentationString);
}
}
}
function indentationIsDifferent(indentationString: string, startLinePosition: number): boolean {
return indentationString !== sourceFile.text.substr(startLinePosition , indentationString.length);
}
function indentMultilineComment(commentRange: TextRange, indentation: number, firstLineIsIndented: boolean) {
// split comment in lines
let startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line;
let endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
const endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line;
let parts: TextRange[];
if (startLine === endLine) {
if (!firstLineIsIndented) {
@@ -889,8 +898,8 @@ namespace ts.formatting {
else {
parts = [];
let startPos = commentRange.pos;
for (let line = startLine; line < endLine; ++line) {
let endOfLine = getEndLinePosition(line, sourceFile);
for (let line = startLine; line < endLine; line++) {
const endOfLine = getEndLinePosition(line, sourceFile);
parts.push({ pos: startPos, end: endOfLine });
startPos = getStartPositionOfLine(line + 1, sourceFile);
}
@@ -898,9 +907,9 @@ namespace ts.formatting {
parts.push({ pos: startPos, end: commentRange.end });
}
let startLinePos = getStartPositionOfLine(startLine, sourceFile);
const startLinePos = getStartPositionOfLine(startLine, sourceFile);
let nonWhitespaceColumnInFirstPart =
const nonWhitespaceColumnInFirstPart =
SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options);
if (indentation === nonWhitespaceColumnInFirstPart.column) {
@@ -914,17 +923,17 @@ namespace ts.formatting {
}
// shift all parts on the delta size
let delta = indentation - nonWhitespaceColumnInFirstPart.column;
for (let i = startIndex, len = parts.length; i < len; ++i, ++startLine) {
let startLinePos = getStartPositionOfLine(startLine, sourceFile);
let nonWhitespaceCharacterAndColumn =
const delta = indentation - nonWhitespaceColumnInFirstPart.column;
for (let i = startIndex, len = parts.length; i < len; i++, startLine++) {
const startLinePos = getStartPositionOfLine(startLine, sourceFile);
const nonWhitespaceCharacterAndColumn =
i === 0
? nonWhitespaceColumnInFirstPart
: SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options);
let newIndentation = nonWhitespaceCharacterAndColumn.column + delta;
const newIndentation = nonWhitespaceCharacterAndColumn.column + delta;
if (newIndentation > 0) {
let indentationString = getIndentationString(newIndentation, options);
const indentationString = getIndentationString(newIndentation, options);
recordReplace(startLinePos, nonWhitespaceCharacterAndColumn.character, indentationString);
}
else {
@@ -934,16 +943,16 @@ namespace ts.formatting {
}
function trimTrailingWhitespacesForLines(line1: number, line2: number, range?: TextRangeWithKind) {
for (let line = line1; line < line2; ++line) {
let lineStartPosition = getStartPositionOfLine(line, sourceFile);
let lineEndPosition = getEndLinePosition(line, sourceFile);
for (let line = line1; line < line2; line++) {
const lineStartPosition = getStartPositionOfLine(line, sourceFile);
const lineEndPosition = getEndLinePosition(line, sourceFile);
// do not trim whitespaces in comments or template expression
if (range && (isComment(range.kind) || isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) {
continue;
}
let whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
const whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition);
if (whitespaceStart !== -1) {
Debug.assert(whitespaceStart === lineStartPosition || !isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1)));
recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart);
@@ -970,16 +979,16 @@ namespace ts.formatting {
* Trimming will be done for lines after the previous range
*/
function trimTrailingWhitespacesForRemainingRange() {
let startPosition = previousRange ? previousRange.end : originalRange.pos;
const startPosition = previousRange ? previousRange.end : originalRange.pos;
let startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
let endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line;
const startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line;
const 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 }
return { span: createTextSpan(start, len), newText };
}
function recordDelete(start: number, len: number) {
@@ -1000,7 +1009,6 @@ namespace ts.formatting {
currentRange: TextRangeWithKind,
currentStartLine: number): void {
let between: TextRange;
switch (rule.Operation.Action) {
case RuleAction.Ignore:
// no action required
@@ -1020,7 +1028,7 @@ namespace ts.formatting {
}
// edit should not be applied only if we have one line feed between elements
let lineDelta = currentStartLine - previousStartLine;
const lineDelta = currentStartLine - previousStartLine;
if (lineDelta !== 1) {
recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter);
}
@@ -1031,7 +1039,7 @@ namespace ts.formatting {
return;
}
let posDelta = currentRange.pos - previousRange.end;
const posDelta = currentRange.pos - previousRange.end;
if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== CharacterCodes.space) {
recordReplace(previousRange.end, currentRange.pos - previousRange.end, " ");
}
@@ -1040,15 +1048,6 @@ namespace ts.formatting {
}
}
function isSomeBlock(kind: SyntaxKind): boolean {
switch (kind) {
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
return true;
}
return false;
}
function getOpenTokenForList(node: Node, list: Node[]) {
switch (node.kind) {
case SyntaxKind.Constructor:
@@ -1093,13 +1092,13 @@ namespace ts.formatting {
return SyntaxKind.Unknown;
}
var internedSizes: { tabSize: number; indentSize: number };
var internedTabsIndentation: string[];
var internedSpacesIndentation: string[];
let internedSizes: { tabSize: number; indentSize: number };
let internedTabsIndentation: string[];
let internedSpacesIndentation: string[];
export function getIndentationString(indentation: number, options: FormatCodeOptions): string {
// reset interned strings if FormatCodeOptions were changed
let resetInternedStrings =
const resetInternedStrings =
!internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize);
if (resetInternedStrings) {
@@ -1108,8 +1107,8 @@ namespace ts.formatting {
}
if (!options.ConvertTabsToSpaces) {
let tabs = Math.floor(indentation / options.TabSize);
let spaces = indentation - tabs * options.TabSize;
const tabs = Math.floor(indentation / options.TabSize);
const spaces = indentation - tabs * options.TabSize;
let tabString: string;
if (!internedTabsIndentation) {
@@ -1117,7 +1116,7 @@ namespace ts.formatting {
}
if (internedTabsIndentation[tabs] === undefined) {
internedTabsIndentation[tabs] = tabString = repeat('\t', tabs);
internedTabsIndentation[tabs] = tabString = repeat("\t", tabs);
}
else {
tabString = internedTabsIndentation[tabs];
@@ -1127,8 +1126,8 @@ namespace ts.formatting {
}
else {
let spacesString: string;
let quotient = Math.floor(indentation / options.IndentSize);
let remainder = indentation % options.IndentSize;
const quotient = Math.floor(indentation / options.IndentSize);
const remainder = indentation % options.IndentSize;
if (!internedSpacesIndentation) {
internedSpacesIndentation = [];
}
@@ -1146,11 +1145,11 @@ namespace ts.formatting {
function repeat(value: string, count: number): string {
let s = "";
for (let i = 0; i < count; ++i) {
for (let i = 0; i < count; i++) {
s += value;
}
return s;
}
}
}
}
+8 -8
View File
@@ -57,8 +57,8 @@ namespace ts.formatting {
public TokensAreOnSameLine(): boolean {
if (this.tokensAreOnSameLine === undefined) {
let startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
let endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
const startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
const endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
this.tokensAreOnSameLine = (startLine === endLine);
}
@@ -82,17 +82,17 @@ namespace ts.formatting {
}
private NodeIsOnOneLine(node: Node): boolean {
let startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
let endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
const startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
const endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
return startLine === endLine;
}
private BlockIsOnOneLine(node: Node): boolean {
let openBrace = findChildOfKind(node, SyntaxKind.OpenBraceToken, this.sourceFile);
let closeBrace = findChildOfKind(node, SyntaxKind.CloseBraceToken, this.sourceFile);
const openBrace = findChildOfKind(node, SyntaxKind.OpenBraceToken, this.sourceFile);
const closeBrace = findChildOfKind(node, SyntaxKind.CloseBraceToken, this.sourceFile);
if (openBrace && closeBrace) {
let startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
let endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
const startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line;
const endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line;
return startLine === endLine;
}
return false;
+17 -18
View File
@@ -35,7 +35,7 @@ namespace ts.formatting {
scanner.setText(sourceFile.text);
scanner.setTextPos(startPos);
let wasNewLine: boolean = true;
let wasNewLine = true;
let leadingTrivia: TextRangeWithKind[];
let trailingTrivia: TextRangeWithKind[];
@@ -56,13 +56,13 @@ namespace ts.formatting {
scanner.setText(undefined);
scanner = undefined;
}
}
};
function advance(): void {
Debug.assert(scanner !== undefined);
lastTokenInfo = undefined;
let isStarted = scanner.getStartPos() !== startPos;
const isStarted = scanner.getStartPos() !== startPos;
if (isStarted) {
if (trailingTrivia) {
@@ -81,23 +81,22 @@ namespace ts.formatting {
scanner.scan();
}
let t: SyntaxKind;
let pos = scanner.getStartPos();
// Read leading trivia and token
while (pos < endPos) {
let t = scanner.getToken();
const t = scanner.getToken();
if (!isTrivia(t)) {
break;
}
// consume leading trivia
scanner.scan();
let item = {
const item = {
pos: pos,
end: scanner.getStartPos(),
kind: t
}
};
pos = scanner.getStartPos();
@@ -166,16 +165,16 @@ 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 =
const expectedScanAction =
shouldRescanGreaterThanToken(n)
? ScanAction.RescanGreaterThanToken
: shouldRescanSlashToken(n)
? ScanAction.RescanSlashToken
: shouldRescanSlashToken(n)
? ScanAction.RescanSlashToken
: shouldRescanTemplateToken(n)
? ScanAction.RescanTemplateToken
: shouldRescanJsxIdentifier(n)
? ScanAction.RescanJsxIdentifier
: ScanAction.Scan
? ScanAction.RescanJsxIdentifier
: ScanAction.Scan;
if (lastTokenInfo && expectedScanAction === lastScanAction) {
// readTokenInfo was called before with the same expected scan action.
@@ -218,11 +217,11 @@ namespace ts.formatting {
lastScanAction = ScanAction.Scan;
}
let token: TextRangeWithKind = {
const token: TextRangeWithKind = {
pos: scanner.getStartPos(),
end: scanner.getTextPos(),
kind: currentToken
}
};
// consume trailing trivia
if (trailingTrivia) {
@@ -233,7 +232,7 @@ namespace ts.formatting {
if (!isTrivia(currentToken)) {
break;
}
let trivia = {
const trivia = {
pos: scanner.getStartPos(),
end: scanner.getTextPos(),
kind: currentToken
@@ -256,7 +255,7 @@ namespace ts.formatting {
leadingTrivia: leadingTrivia,
trailingTrivia: trailingTrivia,
token: token
}
};
return fixTokenKind(lastTokenInfo, n);
}
@@ -264,8 +263,8 @@ 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();
const current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken();
const startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos();
return startPos < endPos && current !== SyntaxKind.EndOfFileToken && !isTrivia(current);
}
+3 -12
View File
@@ -3,13 +3,7 @@
/* @internal */
namespace ts.formatting {
export class RuleOperation {
public Context: RuleOperationContext;
public Action: RuleAction;
constructor() {
this.Context = null;
this.Action = null;
}
constructor(public Context: RuleOperationContext, public Action: RuleAction) {}
public toString(): string {
return "[context=" + this.Context + "," +
@@ -17,14 +11,11 @@ namespace ts.formatting {
}
static create1(action: RuleAction) {
return RuleOperation.create2(RuleOperationContext.Any, action)
return RuleOperation.create2(RuleOperationContext.Any, action);
}
static create2(context: RuleOperationContext, action: RuleAction) {
let result = new RuleOperation();
result.Context = context;
result.Action = action;
return result;
return new RuleOperation(context, action);
}
}
}
@@ -5,7 +5,7 @@ namespace ts.formatting {
export class RuleOperationContext {
private customContextChecks: { (context: FormattingContext): boolean; }[];
constructor(...funcs: { (context: FormattingContext): boolean; }[]) {
this.customContextChecks = funcs;
}
@@ -22,7 +22,7 @@ namespace ts.formatting {
return true;
}
for (let check of this.customContextChecks) {
for (const check of this.customContextChecks) {
if (!check(context)) {
return false;
}
+11 -11
View File
@@ -4,8 +4,8 @@
namespace ts.formatting {
export class Rules {
public getRuleName(rule: Rule) {
let o: ts.Map<any> = <any>this;
for (let name in o) {
const o: ts.Map<any> = <any>this;
for (const name in o) {
if (o[name] === rule) {
return name;
}
@@ -166,7 +166,7 @@ namespace ts.formatting {
public NoSpaceAfterKeywordInControl: Rule;
// Open Brace braces after function
//TypeScript: Function can have return types, which can be made of tons of different token kinds
// TypeScript: Function can have return types, which can be made of tons of different token kinds
public FunctionOpenBraceLeftTokenRange: Shared.TokenRange;
public SpaceBeforeOpenBraceInFunction: Rule;
public NewLineBeforeOpenBraceInFunction: Rule;
@@ -458,7 +458,7 @@ namespace ts.formatting {
this.NoSpaceAfterKeywordInControl = new Rule(RuleDescriptor.create2(Shared.TokenRange.Keywords, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsControlDeclContext), RuleAction.Delete));
// Open Brace braces after function
//TypeScript: Function can have return types, which can be made of tons of different token kinds
// TypeScript: Function can have return types, which can be made of tons of different token kinds
this.NewLineBeforeOpenBraceInFunction = new Rule(RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, SyntaxKind.OpenBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), RuleAction.NewLine), RuleFlags.CanDeleteNewLines);
// Open Brace braces after TypeScript module/class/interface
@@ -616,17 +616,17 @@ namespace ts.formatting {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
//case SyntaxKind.MemberFunctionDeclaration:
// case SyntaxKind.MemberFunctionDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
///case SyntaxKind.MethodSignature:
// case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.FunctionExpression:
case SyntaxKind.Constructor:
case SyntaxKind.ArrowFunction:
//case SyntaxKind.ConstructorDeclaration:
//case SyntaxKind.SimpleArrowFunctionExpression:
//case SyntaxKind.ParenthesizedArrowFunctionExpression:
// case SyntaxKind.ConstructorDeclaration:
// case SyntaxKind.SimpleArrowFunctionExpression:
// case SyntaxKind.ParenthesizedArrowFunctionExpression:
case SyntaxKind.InterfaceDeclaration: // This one is not truly a function, but for formatting purposes, it acts just like one
return true;
}
@@ -724,7 +724,7 @@ namespace ts.formatting {
}
static IsNotBeforeBlockInFunctionDeclarationContext(context: FormattingContext): boolean {
return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context)
return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context);
}
static IsEndOfDecoratorContextOnSameLine(context: FormattingContext): boolean {
@@ -755,7 +755,7 @@ namespace ts.formatting {
}
static IsObjectTypeContext(context: FormattingContext): boolean {
return context.contextNode.kind === SyntaxKind.TypeLiteral;// && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
return context.contextNode.kind === SyntaxKind.TypeLiteral; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
}
static IsTypeArgumentOrParameterOrAssertion(token: TextRangeWithKind, parent: Node): boolean {
+17 -17
View File
@@ -12,17 +12,17 @@ namespace ts.formatting {
}
static create(rules: Rule[]): RulesMap {
let result = new RulesMap();
const result = new RulesMap();
result.Initialize(rules);
return result;
}
public Initialize(rules: Rule[]) {
this.mapRowLength = SyntaxKind.LastToken + 1;
this.map = <any> new Array(this.mapRowLength * this.mapRowLength);//new Array<RulesBucket>(this.mapRowLength * this.mapRowLength);
this.map = <any> new Array(this.mapRowLength * this.mapRowLength); // new Array<RulesBucket>(this.mapRowLength * this.mapRowLength);
// This array is used only during construction of the rulesbucket in the map
let rulesBucketConstructionStateList: RulesBucketConstructionState[] = <any> new Array(this.map.length);//new Array<RulesBucketConstructionState>(this.map.length);
const rulesBucketConstructionStateList: RulesBucketConstructionState[] = <any>new Array(this.map.length); // new Array<RulesBucketConstructionState>(this.map.length);
this.FillRules(rules, rulesBucketConstructionStateList);
return this.map;
@@ -35,18 +35,18 @@ namespace ts.formatting {
}
private GetRuleBucketIndex(row: number, column: number): number {
let rulesBucketIndex = (row * this.mapRowLength) + column;
//Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array.");
const rulesBucketIndex = (row * this.mapRowLength) + column;
// Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array.");
return rulesBucketIndex;
}
private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void {
let specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any &&
const specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any &&
rule.Descriptor.RightTokenRange !== Shared.TokenRange.Any;
rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => {
rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => {
let rulesBucketIndex = this.GetRuleBucketIndex(left, right);
const rulesBucketIndex = this.GetRuleBucketIndex(left, right);
let rulesBucket = this.map[rulesBucketIndex];
if (rulesBucket === undefined) {
@@ -54,26 +54,26 @@ namespace ts.formatting {
}
rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex);
})
})
});
});
}
public GetRule(context: FormattingContext): Rule {
let bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind);
let bucket = this.map[bucketIndex];
if (bucket != null) {
for (let rule of bucket.Rules()) {
const bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind);
const bucket = this.map[bucketIndex];
if (bucket) {
for (const rule of bucket.Rules()) {
if (rule.Operation.Context.InContext(context)) {
return rule;
}
}
}
return null;
return undefined;
}
}
let MaskBitSize = 5;
let Mask = 0x1f;
const MaskBitSize = 5;
const Mask = 0x1f;
export enum RulesPosition {
IgnoreRulesSpecific = 0,
@@ -167,7 +167,7 @@ namespace ts.formatting {
if (state === undefined) {
state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState();
}
let index = state.GetInsertionIndex(position);
const index = state.GetInsertionIndex(position);
this.rules.splice(index, 0, rule);
state.IncreaseInsertionIndex(position);
}
+3 -4
View File
@@ -25,10 +25,9 @@ namespace ts.formatting {
}
public ensureUpToDate(options: ts.FormatCodeOptions) {
// TODO: Should this be '==='?
if (this.options == null || !ts.compareDataObjects(this.options, options)) {
let activeRules = this.createActiveRules(options);
let rulesMap = RulesMap.create(activeRules);
if (!this.options || !ts.compareDataObjects(this.options, options)) {
const activeRules = this.createActiveRules(options);
const rulesMap = RulesMap.create(activeRules);
this.activeRules = activeRules;
this.rulesMap = rulesMap;
+35 -35
View File
@@ -2,7 +2,7 @@
/* @internal */
namespace ts.formatting {
export module SmartIndenter {
export namespace SmartIndenter {
const enum Value {
Unknown = -1
@@ -19,18 +19,18 @@ namespace ts.formatting {
return 0;
}
let precedingToken = findPrecedingToken(position, sourceFile);
const precedingToken = findPrecedingToken(position, sourceFile);
if (!precedingToken) {
return 0;
}
// no indentation in string \regex\template literals
let precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
const precedingTokenIsLiteral = isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind);
if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) {
return 0;
}
let lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
const lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
// indentation is first non-whitespace character in a previous line
// for block indentation, we should look for a line which contains something that's not
@@ -40,21 +40,21 @@ namespace ts.formatting {
// move backwards until we find a line with a non-whitespace character,
// then find the first non-whitespace character for that line.
let current = position;
while (current > 0){
let char = sourceFile.text.charCodeAt(current);
while (current > 0) {
const char = sourceFile.text.charCodeAt(current);
if (!isWhiteSpace(char) && !isLineBreak(char)) {
break;
}
current--;
}
let lineStart = ts.getLineStartPositionForPosition(current, sourceFile);
const lineStart = ts.getLineStartPositionForPosition(current, sourceFile);
return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options);
}
if (precedingToken.kind === SyntaxKind.CommaToken && precedingToken.parent.kind !== SyntaxKind.BinaryExpression) {
// previous token is comma that separates items in list - find the previous item and try to derive indentation from it
let actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
const actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options);
if (actualIndentation !== Value.Unknown) {
return actualIndentation;
}
@@ -104,7 +104,7 @@ namespace ts.formatting {
}
export function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number {
let start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
const start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile));
return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options);
}
@@ -124,19 +124,19 @@ namespace ts.formatting {
while (parent) {
let useActualIndentation = true;
if (ignoreActualIndentationRange) {
let start = current.getStart(sourceFile);
const start = current.getStart(sourceFile);
useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end;
}
if (useActualIndentation) {
// check if current node is a list item - if yes, take indentation from it
let actualIndentation = getActualIndentationForListItem(current, sourceFile, options);
const actualIndentation = getActualIndentationForListItem(current, sourceFile, options);
if (actualIndentation !== Value.Unknown) {
return actualIndentation + indentationDelta;
}
}
parentStart = getParentStart(parent, current, sourceFile);
let parentAndChildShareLine =
const parentAndChildShareLine =
parentStart.line === currentStart.line ||
childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile);
@@ -167,7 +167,7 @@ namespace ts.formatting {
function getParentStart(parent: Node, child: Node, sourceFile: SourceFile): LineAndCharacter {
let containingList = getContainingList(child, sourceFile);
const containingList = getContainingList(child, sourceFile);
if (containingList) {
return sourceFile.getLineAndCharacterOfPosition(containingList.pos);
}
@@ -180,7 +180,7 @@ namespace ts.formatting {
*/
function getActualIndentationForListItemBeforeComma(commaToken: Node, sourceFile: SourceFile, options: EditorOptions): number {
// previous token is comma that separates items in list - find the previous item and try to derive indentation from it
let commaItemInfo = findListItemInfo(commaToken);
const commaItemInfo = findListItemInfo(commaToken);
if (commaItemInfo && commaItemInfo.listItemIndex > 0) {
return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options);
}
@@ -203,7 +203,7 @@ namespace ts.formatting {
// actual indentation is used for statements\declarations if one of cases below is true:
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
let useActualIndentation =
const useActualIndentation =
(isDeclaration(current) || isStatementButNotDeclaration(current)) &&
(parent.kind === SyntaxKind.SourceFile || !parentAndChildShareLine);
@@ -215,7 +215,7 @@ namespace ts.formatting {
}
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken: Node, current: Node, lineAtPosition: number, sourceFile: SourceFile): boolean {
let nextToken = findNextToken(precedingToken, current);
const nextToken = findNextToken(precedingToken, current);
if (!nextToken) {
return false;
}
@@ -234,7 +234,7 @@ namespace ts.formatting {
// class A {
// $}
let nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
const nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line;
return lineAtPosition === nextTokenStartLine;
}
@@ -247,10 +247,10 @@ namespace ts.formatting {
export function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean {
if (parent.kind === SyntaxKind.IfStatement && (<IfStatement>parent).elseStatement === child) {
let elseKeyword = findChildOfKind(parent, SyntaxKind.ElseKeyword, sourceFile);
const elseKeyword = findChildOfKind(parent, SyntaxKind.ElseKeyword, sourceFile);
Debug.assert(elseKeyword !== undefined);
let elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
const elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line;
return elseKeywordStartLine === childStartLine;
}
@@ -277,7 +277,7 @@ namespace ts.formatting {
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature: {
let start = node.getStart(sourceFile);
const start = node.getStart(sourceFile);
if ((<SignatureDeclaration>node.parent).typeParameters &&
rangeContainsStartEnd((<SignatureDeclaration>node.parent).typeParameters, start, node.getEnd())) {
return (<SignatureDeclaration>node.parent).typeParameters;
@@ -289,7 +289,7 @@ namespace ts.formatting {
}
case SyntaxKind.NewExpression:
case SyntaxKind.CallExpression: {
let start = node.getStart(sourceFile);
const start = node.getStart(sourceFile);
if ((<CallExpression>node.parent).typeArguments &&
rangeContainsStartEnd((<CallExpression>node.parent).typeArguments, start, node.getEnd())) {
return (<CallExpression>node.parent).typeArguments;
@@ -306,11 +306,11 @@ namespace ts.formatting {
}
function getActualIndentationForListItem(node: Node, sourceFile: SourceFile, options: EditorOptions): number {
let containingList = getContainingList(node, sourceFile);
const containingList = getContainingList(node, sourceFile);
return containingList ? getActualIndentationFromList(containingList) : Value.Unknown;
function getActualIndentationFromList(list: Node[]): number {
let index = indexOf(list, node);
const index = indexOf(list, node);
return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : Value.Unknown;
}
}
@@ -327,15 +327,15 @@ namespace ts.formatting {
node.parent.kind === SyntaxKind.NewExpression) &&
(<CallExpression>node.parent).expression !== node) {
let fullCallOrNewExpression = (<CallExpression | NewExpression>node.parent).expression;
let startingExpression = getStartingExpression(<PropertyAccessExpression | CallExpression | ElementAccessExpression>fullCallOrNewExpression);
const fullCallOrNewExpression = (<CallExpression | NewExpression>node.parent).expression;
const startingExpression = getStartingExpression(<PropertyAccessExpression | CallExpression | ElementAccessExpression>fullCallOrNewExpression);
if (fullCallOrNewExpression === startingExpression) {
return Value.Unknown;
}
let fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end);
let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end);
const fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end);
const startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end);
if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) {
return Value.Unknown;
@@ -365,17 +365,17 @@ namespace ts.formatting {
function deriveActualIndentationFromList(list: Node[], index: number, sourceFile: SourceFile, options: EditorOptions): number {
Debug.assert(index >= 0 && index < list.length);
let node = list[index];
const node = list[index];
// walk toward the start of the list starting from current node and check if the line is the same for all items.
// if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i]
let lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile);
for (let i = index - 1; i >= 0; --i) {
for (let i = index - 1; i >= 0; i--) {
if (list[i].kind === SyntaxKind.CommaToken) {
continue;
}
// skip list items that ends on the same line with the current list element
let prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
const prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line;
if (prevEndLine !== lineAndCharacter.line) {
return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options);
}
@@ -386,7 +386,7 @@ namespace ts.formatting {
}
function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter: LineAndCharacter, sourceFile: SourceFile, options: EditorOptions): number {
let lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
const lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0);
return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options);
}
@@ -400,8 +400,8 @@ namespace ts.formatting {
export function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions) {
let character = 0;
let column = 0;
for (let pos = startPos; pos < endPos; ++pos) {
let ch = sourceFile.text.charCodeAt(pos);
for (let pos = startPos; pos < endPos; pos++) {
const ch = sourceFile.text.charCodeAt(pos);
if (!isWhiteSpace(ch)) {
break;
}
@@ -470,7 +470,7 @@ namespace ts.formatting {
/* @internal */
export function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean) {
let childKind = child ? child.kind : SyntaxKind.Unknown;
const childKind = child ? child.kind : SyntaxKind.Unknown;
switch (parent.kind) {
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
@@ -497,7 +497,7 @@ namespace ts.formatting {
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);
return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false);
}
}
}
+2 -2
View File
@@ -2,7 +2,7 @@
/* @internal */
namespace ts.formatting {
export module Shared {
export namespace Shared {
export interface ITokenAccess {
GetTokens(): SyntaxKind[];
Contains(token: SyntaxKind): boolean;
@@ -60,7 +60,7 @@ namespace ts.formatting {
export class TokenAllAccess implements ITokenAccess {
public GetTokens(): SyntaxKind[] {
let result: SyntaxKind[] = [];
const result: SyntaxKind[] = [];
for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) {
result.push(token);
}
+14 -1
View File
@@ -2,7 +2,7 @@
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[] {
export function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[] {
const patternMatcher = createPatternMatcher(searchValue);
let rawItems: RawNavigateToItem[] = [];
@@ -49,6 +49,19 @@ namespace ts.NavigateTo {
}
});
// Remove imports when the imported declaration is already in the list and has the same name.
rawItems = filter(rawItems, item => {
const decl = item.declaration;
if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) {
const importer = checker.getSymbolAtLocation(decl.name);
const imported = checker.getAliasedSymbol(importer);
return importer.name !== imported.name;
}
else {
return true;
}
});
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
rawItems = rawItems.slice(0, maxResultCount);
+55 -39
View File
@@ -46,7 +46,7 @@ namespace ts.NavigationBar {
}
function getChildNodes(nodes: Node[]): Node[] {
let childNodes: Node[] = [];
const childNodes: Node[] = [];
function visit(node: Node) {
switch (node.kind) {
@@ -109,7 +109,7 @@ namespace ts.NavigationBar {
}
}
//for (let i = 0, n = nodes.length; i < n; i++) {
// for (let i = 0, n = nodes.length; i < n; i++) {
// let node = nodes[i];
// if (node.kind === SyntaxKind.ClassDeclaration ||
@@ -123,13 +123,13 @@ namespace ts.NavigationBar {
// else if (node.kind === SyntaxKind.VariableStatement) {
// childNodes.push.apply(childNodes, (<VariableStatement>node).declarations);
// }
//}
// }
forEach(nodes, visit);
return sortNodes(childNodes);
}
function getTopLevelNodes(node: SourceFile): Node[] {
let topLevelNodes: Node[] = [];
const topLevelNodes: Node[] = [];
topLevelNodes.push(node);
addTopLevelNodes(node.statements, topLevelNodes);
@@ -157,7 +157,7 @@ namespace ts.NavigationBar {
function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void {
nodes = sortNodes(nodes);
for (let node of nodes) {
for (const node of nodes) {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
topLevelNodes.push(node);
@@ -176,6 +176,7 @@ namespace ts.NavigationBar {
break;
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
topLevelNodes.push(node);
break;
@@ -197,7 +198,7 @@ namespace ts.NavigationBar {
}
function hasNamedFunctionDeclarations(nodes: NodeArray<Statement>): boolean {
for (let s of nodes) {
for (const s of nodes) {
if (s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text)) {
return true;
}
@@ -237,17 +238,17 @@ namespace ts.NavigationBar {
}
function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] {
let items: ts.NavigationBarItem[] = [];
const items: ts.NavigationBarItem[] = [];
let keyToItem: Map<NavigationBarItem> = {};
const keyToItem: Map<NavigationBarItem> = {};
for (let child of nodes) {
let item = createItem(child);
for (const child of nodes) {
const item = createItem(child);
if (item !== undefined) {
if (item.text.length > 0) {
let key = item.text + "-" + item.kind + "-" + item.indent;
const key = item.text + "-" + item.kind + "-" + item.indent;
let itemWithSameName = keyToItem[key];
const itemWithSameName = keyToItem[key];
if (itemWithSameName) {
// We had an item with the same name. Merge these items together.
merge(itemWithSameName, item);
@@ -274,8 +275,8 @@ namespace ts.NavigationBar {
// Next, recursively merge or add any children in the source as appropriate.
outer:
for (let sourceChild of source.childItems) {
for (let targetChild of target.childItems) {
for (const sourceChild of source.childItems) {
for (const targetChild of target.childItems) {
if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) {
// Found a match. merge them.
merge(targetChild, sourceChild);
@@ -313,9 +314,15 @@ namespace ts.NavigationBar {
case SyntaxKind.IndexSignature:
return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement);
case SyntaxKind.EnumDeclaration:
return createItem(node, getTextOfNode((<EnumDeclaration>node).name), ts.ScriptElementKind.enumElement);
case SyntaxKind.EnumMember:
return createItem(node, getTextOfNode((<EnumMember>node).name), ts.ScriptElementKind.memberVariableElement);
case SyntaxKind.InterfaceDeclaration:
return createItem(node, getTextOfNode((<InterfaceDeclaration>node).name), ts.ScriptElementKind.interfaceElement);
case SyntaxKind.CallSignature:
return createItem(node, "()", ts.ScriptElementKind.callSignatureElement);
@@ -382,7 +389,7 @@ namespace ts.NavigationBar {
return !text || text.trim() === "";
}
function getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TextSpan[], childItems: NavigationBarItem[] = [], indent: number = 0): NavigationBarItem {
function getNavigationBarItem(text: string, kind: string, kindModifiers: string, spans: TextSpan[], childItems: NavigationBarItem[] = [], indent = 0): NavigationBarItem {
if (isEmpty(text)) {
return undefined;
}
@@ -422,6 +429,9 @@ namespace ts.NavigationBar {
case SyntaxKind.FunctionDeclaration:
return createFunctionItem(<FunctionDeclaration>node);
case SyntaxKind.TypeAliasDeclaration:
return createTypeAliasItem(<TypeAliasDeclaration>node);
}
return undefined;
@@ -433,7 +443,7 @@ namespace ts.NavigationBar {
}
// Otherwise, we need to aggregate each identifier to build up the qualified name.
let result: string[] = [];
const result: string[] = [];
result.push(moduleDeclaration.name.text);
@@ -447,9 +457,9 @@ namespace ts.NavigationBar {
}
function createModuleItem(node: ModuleDeclaration): NavigationBarItem {
let moduleName = getModuleName(node);
const moduleName = getModuleName(node);
let childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
const childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
return getNavigationBarItem(moduleName,
ts.ScriptElementKind.moduleElement,
@@ -461,9 +471,9 @@ namespace ts.NavigationBar {
function createFunctionItem(node: FunctionDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
const 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)],
@@ -474,9 +484,18 @@ namespace ts.NavigationBar {
return undefined;
}
function createTypeAliasItem(node: TypeAliasDeclaration): ts.NavigationBarItem {
return getNavigationBarItem(node.name.text,
ts.ScriptElementKind.typeElement,
getNodeModifiers(node),
[getNodeSpan(node)],
[],
getIndent(node));
}
function createMemberFunctionLikeItem(node: MethodDeclaration | ConstructorDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
const childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
let scriptElementKind: string;
let memberFunctionName: string;
if (node.kind === SyntaxKind.MethodDeclaration) {
@@ -500,16 +519,16 @@ namespace ts.NavigationBar {
}
function createSourceFileItem(node: SourceFile): ts.NavigationBarItem {
let childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
const childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
if (childItems === undefined || childItems.length === 0) {
return undefined;
}
hasGlobalNode = true;
let rootName = isExternalModule(node)
const rootName = isExternalModule(node)
? "\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(node.fileName)))) + "\""
: "<global>"
: "<global>";
return getNavigationBarItem(rootName,
ts.ScriptElementKind.moduleElement,
@@ -522,14 +541,14 @@ namespace ts.NavigationBar {
let childItems: NavigationBarItem[];
if (node.members) {
let constructor = <ConstructorDeclaration>forEach(node.members, member => {
const constructor = <ConstructorDeclaration>forEach(node.members, member => {
return member.kind === SyntaxKind.Constructor && member;
});
// Add the constructor parameters in as children of the class (for property parameters).
// Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that
// are not properties will be filtered out later by createChildItem.
let nodes: Node[] = removeDynamicallyNamedProperties(node);
const nodes: Node[] = removeDynamicallyNamedProperties(node);
if (constructor) {
addRange(nodes, filter(constructor.parameters, p => !isBindingPattern(p.name)));
}
@@ -537,7 +556,7 @@ namespace ts.NavigationBar {
childItems = getItemsWorker(sortNodes(nodes), createChildItem);
}
var nodeName = !node.name ? "default" : node.name.text;
const nodeName = !node.name ? "default" : node.name.text;
return getNavigationBarItem(
nodeName,
@@ -549,7 +568,7 @@ namespace ts.NavigationBar {
}
function createEnumItem(node: EnumDeclaration): ts.NavigationBarItem {
let childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
const childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem);
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.enumElement,
@@ -560,7 +579,7 @@ namespace ts.NavigationBar {
}
function createInterfaceItem(node: InterfaceDeclaration): ts.NavigationBarItem {
let childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
const childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem);
return getNavigationBarItem(
node.name.text,
ts.ScriptElementKind.interfaceElement,
@@ -578,7 +597,7 @@ namespace ts.NavigationBar {
/**
* Like removeComputedProperties, but retains the properties with well known symbol names
*/
function removeDynamicallyNamedProperties(node: ClassDeclaration | InterfaceDeclaration): Declaration[]{
function removeDynamicallyNamedProperties(node: ClassDeclaration | InterfaceDeclaration): Declaration[] {
return filter<Declaration>(node.members, member => !hasDynamicName(member));
}
@@ -606,11 +625,11 @@ namespace ts.NavigationBar {
const anonClassText = "<class>";
let indent = 0;
let rootName = isExternalModule(sourceFile) ?
const rootName = isExternalModule(sourceFile) ?
"\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName)))) + "\""
: "<global>";
let sourceFileItem = getNavBarItem(rootName, ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]);
const 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,
@@ -643,12 +662,12 @@ namespace ts.NavigationBar {
}
}
function createNavBarItem(node: Node) : NavigationBarItem {
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*/
if (node.parent/*VariableDeclarationList*/.parent/*VariableStatement*/
.parent/*SourceFile*/.kind !== SyntaxKind.SourceFile) {
return undefined;
}
@@ -711,7 +730,7 @@ namespace ts.NavigationBar {
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 {
@@ -724,7 +743,7 @@ namespace ts.NavigationBar {
return undefined;
}
const callExpr = node.parent as CallExpression;
if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== 'define') {
if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== "define") {
return undefined;
}
@@ -758,9 +777,6 @@ namespace ts.NavigationBar {
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 &&
+355 -170
View File
@@ -13,7 +13,7 @@
namespace ts {
/** The version of the language service API */
export const servicesVersion = "0.4";
export const servicesVersion = "0.5";
export interface Node {
getSourceFile(): SourceFile;
@@ -50,6 +50,7 @@ namespace ts {
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
getNonNullableType(): Type;
}
export interface Signature {
@@ -741,6 +742,9 @@ namespace ts {
? this.checker.getBaseTypes(<InterfaceType><Type>this)
: undefined;
}
getNonNullableType(): Type {
return this.checker.getNonNullableType(this);
}
}
class SignatureObject implements Signature {
@@ -910,6 +914,7 @@ namespace ts {
function visit(node: Node): void {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
const functionDeclaration = <FunctionLikeDeclaration>node;
@@ -936,6 +941,7 @@ namespace ts {
break;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.EnumDeclaration:
@@ -950,34 +956,25 @@ namespace ts {
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeLiteral:
addDeclaration(<Declaration>node);
// fall through
case SyntaxKind.Constructor:
case SyntaxKind.VariableStatement:
case SyntaxKind.VariableDeclarationList:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ModuleBlock:
forEachChild(node, visit);
break;
case SyntaxKind.Block:
if (isFunctionBlock(node)) {
forEachChild(node, visit);
}
break;
case SyntaxKind.Parameter:
// Only consider properties defined as constructor parameters
if (!(getModifierFlags(node) & ModifierFlags.AccessibilityModifier)) {
// Only consider parameter properties
if (!hasModifier(node, ModifierFlags.ParameterPropertyModifier)) {
break;
}
// fall through
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
if (isBindingPattern((<VariableDeclaration>node).name)) {
forEachChild((<VariableDeclaration>node).name, visit);
case SyntaxKind.BindingElement: {
const decl = <VariableDeclaration> node;
if (isBindingPattern(decl.name)) {
forEachChild(decl.name, visit);
break;
}
if (decl.initializer)
visit(decl.initializer);
}
case SyntaxKind.EnumMember:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
@@ -1014,6 +1011,9 @@ namespace ts {
}
}
break;
default:
forEachChild(node, visit);
}
}
}
@@ -1033,7 +1033,7 @@ namespace ts {
getScriptFileNames(): string[];
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -1487,6 +1487,15 @@ namespace ts {
version: string,
scriptKind?: ScriptKind): SourceFile;
acquireDocumentWithKey(
fileName: string,
path: Path,
compilationSettings: CompilerOptions,
key: DocumentRegistryBucketKey,
scriptSnapshot: IScriptSnapshot,
version: string,
scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
@@ -1506,6 +1515,16 @@ namespace ts {
version: string,
scriptKind?: ScriptKind): SourceFile;
updateDocumentWithKey(
fileName: string,
path: Path,
compilationSettings: CompilerOptions,
key: DocumentRegistryBucketKey,
scriptSnapshot: IScriptSnapshot,
version: string,
scriptKind?: ScriptKind): SourceFile;
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
@@ -1517,76 +1536,86 @@ namespace ts {
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
reportStats(): string;
}
export type DocumentRegistryBucketKey = string & { __bucketKey: any };
// TODO: move these to enums
export namespace ScriptElementKind {
export const unknown = "";
export const warning = "warning";
// predefined type (void) or keyword (class)
/** predefined type (void) or keyword (class) */
export const keyword = "keyword";
// top level script node
/** top level script node */
export const scriptElement = "script";
// module foo {}
/** module foo {} */
export const moduleElement = "module";
// class X {}
/** class X {} */
export const classElement = "class";
// var x = class X {}
/** var x = class X {} */
export const localClassElement = "local class";
// interface Y {}
/** interface Y {} */
export const interfaceElement = "interface";
// type T = ...
/** type T = ... */
export const typeElement = "type";
// enum E
/** enum E */
export const enumElement = "enum";
// Inside module and script only
// const v = ..
/**
* Inside module and script only
* const v = ..
*/
export const variableElement = "var";
// Inside function
/** Inside function */
export const localVariableElement = "local var";
// Inside module and script only
// function f() { }
/**
* Inside module and script only
* function f() { }
*/
export const functionElement = "function";
// Inside function
/** Inside function */
export const localFunctionElement = "local function";
// class X { [public|private]* foo() {} }
/** class X { [public|private]* foo() {} } */
export const memberFunctionElement = "method";
// class X { [public|private]* [get|set] foo:number; }
/** class X { [public|private]* [get|set] foo:number; } */
export const memberGetAccessorElement = "getter";
export const memberSetAccessorElement = "setter";
// class X { [public|private]* foo:number; }
// interface Y { foo:number; }
/**
* class X { [public|private]* foo:number; }
* interface Y { foo:number; }
*/
export const memberVariableElement = "property";
// class X { constructor() { } }
/** class X { constructor() { } } */
export const constructorImplementationElement = "constructor";
// interface Y { ():number; }
/** interface Y { ():number; } */
export const callSignatureElement = "call";
// interface Y { []:number; }
/** interface Y { []:number; } */
export const indexSignatureElement = "index";
// interface Y { new():Y; }
/** interface Y { new():Y; } */
export const constructSignatureElement = "construct";
// function foo(*Y*: string)
/** function foo(*Y*: string) */
export const parameterElement = "parameter";
export const typeParameterElement = "type parameter";
@@ -1789,11 +1818,13 @@ namespace ts {
public getOrCreateEntry(fileName: string): HostFileInformation {
const path = toPath(fileName, this.currentDirectory, this.getCanonicalFileName);
if (this.contains(path)) {
return this.getEntry(path);
}
return this.getOrCreateEntryByPath(fileName, path);
}
return this.createEntry(fileName, path);
public getOrCreateEntryByPath(fileName: string, path: Path): HostFileInformation {
return this.contains(path)
? this.getEntry(path)
: this.createEntry(fileName, path);
}
public getRootFileNames(): string[] {
@@ -1927,7 +1958,7 @@ namespace ts {
// Create a compilerHost object to allow the compiler to read and write files
const compilerHost: CompilerHost = {
getSourceFile: (fileName, target) => fileName === normalizeSlashes(inputFileName) ? sourceFile : undefined,
getSourceFile: (fileName, target) => fileName === normalizePath(inputFileName) ? sourceFile : undefined,
writeFile: (name, text, writeByteOrderMark) => {
if (fileExtensionIs(name, ".map")) {
Debug.assert(sourceMapText === undefined, `Unexpected multiple source map outputs for the file '${name}'`);
@@ -2047,12 +2078,11 @@ namespace ts {
const buckets: Map<FileMap<DocumentRegistryEntry>> = {};
const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames);
function getKeyFromCompilationSettings(settings: CompilerOptions): string {
return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs;
function getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey {
return <DocumentRegistryBucketKey>`_${settings.target}|${settings.module}|${settings.noResolve}|${settings.jsx}|${settings.allowJs}|${settings.baseUrl}|${settings.typesRoot}|${settings.typesSearchPaths}|${JSON.stringify(settings.rootDirs)}|${JSON.stringify(settings.paths)}`;
}
function getBucketForCompilationSettings(settings: CompilerOptions, createIfMissing: boolean): FileMap<DocumentRegistryEntry> {
const key = getKeyFromCompilationSettings(settings);
function getBucketForCompilationSettings(key: DocumentRegistryBucketKey, createIfMissing: boolean): FileMap<DocumentRegistryEntry> {
let bucket = lookUp(buckets, key);
if (!bucket && createIfMissing) {
buckets[key] = bucket = createFileMap<DocumentRegistryEntry>();
@@ -2081,23 +2111,36 @@ namespace ts {
}
function acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile {
return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ true, scriptKind);
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const key = getKeyForCompilationSettings(compilationSettings);
return acquireDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
}
function acquireDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile {
return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ true, scriptKind);
}
function updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile {
return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ false, scriptKind);
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const key = getKeyForCompilationSettings(compilationSettings);
return updateDocumentWithKey(fileName, path, compilationSettings, key, scriptSnapshot, version, scriptKind);
}
function updateDocumentWithKey(fileName: string, path: Path, compilationSettings: CompilerOptions, key: DocumentRegistryBucketKey, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile {
return acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, /*acquiring*/ false, scriptKind);
}
function acquireOrUpdateDocument(
fileName: string,
path: Path,
compilationSettings: CompilerOptions,
key: DocumentRegistryBucketKey,
scriptSnapshot: IScriptSnapshot,
version: string,
acquiring: boolean,
scriptKind?: ScriptKind): SourceFile {
const bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true);
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
let entry = bucket.get(path);
if (!entry) {
Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?");
@@ -2135,10 +2178,14 @@ namespace ts {
}
function releaseDocument(fileName: string, compilationSettings: CompilerOptions): void {
const bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/false);
Debug.assert(bucket !== undefined);
const path = toPath(fileName, currentDirectory, getCanonicalFileName);
const key = getKeyForCompilationSettings(compilationSettings);
return releaseDocumentWithKey(path, key);
}
function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void {
const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/false);
Debug.assert(bucket !== undefined);
const entry = bucket.get(path);
entry.languageServiceRefCount--;
@@ -2151,9 +2198,13 @@ namespace ts {
return {
acquireDocument,
acquireDocumentWithKey,
updateDocument,
updateDocumentWithKey,
releaseDocument,
reportStats
releaseDocumentWithKey,
reportStats,
getKeyForCompilationSettings
};
}
@@ -2587,10 +2638,33 @@ namespace ts {
isFunctionLike(node.parent) && (<FunctionLikeDeclaration>node.parent).name === node;
}
/** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */
function isNameOfPropertyAssignment(node: Node): boolean {
return (node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) &&
(node.parent.kind === SyntaxKind.PropertyAssignment || node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) && (<PropertyDeclaration>node.parent).name === node;
function isObjectLiteralPropertyDeclaration(node: Node): node is ObjectLiteralElement {
switch (node.kind) {
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return true;
}
return false;
}
/**
* Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }
*/
function getContainingObjectLiteralElement(node: Node): ObjectLiteralElement {
switch (node.kind) {
case SyntaxKind.StringLiteral:
case SyntaxKind.NumericLiteral:
if (node.parent.kind === SyntaxKind.ComputedPropertyName) {
return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined;
}
// intential fall through
case SyntaxKind.Identifier:
return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined;
}
return undefined;
}
function isLiteralNameOfPropertyDeclarationOrIndexAccess(node: Node): boolean {
@@ -2608,6 +2682,8 @@ namespace ts {
return (<Declaration>node.parent).name === node;
case SyntaxKind.ElementAccessExpression:
return (<ElementAccessExpression>node.parent).argumentExpression === node;
case SyntaxKind.ComputedPropertyName:
return true;
}
}
@@ -2706,7 +2782,9 @@ namespace ts {
/* @internal */ export function getNodeKind(node: Node): string {
switch (node.kind) {
case SyntaxKind.ModuleDeclaration: return ScriptElementKind.moduleElement;
case SyntaxKind.ClassDeclaration: return ScriptElementKind.classElement;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
return ScriptElementKind.classElement;
case SyntaxKind.InterfaceDeclaration: return ScriptElementKind.interfaceElement;
case SyntaxKind.TypeAliasDeclaration: return ScriptElementKind.typeElement;
case SyntaxKind.EnumDeclaration: return ScriptElementKind.enumElement;
@@ -2716,7 +2794,9 @@ namespace ts {
: isLet(node)
? ScriptElementKind.letElement
: ScriptElementKind.variableElement;
case SyntaxKind.FunctionDeclaration: return ScriptElementKind.functionElement;
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
return ScriptElementKind.functionElement;
case SyntaxKind.GetAccessor: return ScriptElementKind.memberGetAccessorElement;
case SyntaxKind.SetAccessor: return ScriptElementKind.memberSetAccessorElement;
case SyntaxKind.MethodDeclaration:
@@ -2731,7 +2811,7 @@ namespace ts {
case SyntaxKind.Constructor: return ScriptElementKind.constructorImplementationElement;
case SyntaxKind.TypeParameter: return ScriptElementKind.typeParameterElement;
case SyntaxKind.EnumMember: return ScriptElementKind.variableElement;
case SyntaxKind.Parameter: return (getModifierFlags(node) & ModifierFlags.AccessibilityModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement;
case SyntaxKind.Parameter: return hasModifier(node, ModifierFlags.ParameterPropertyModifier) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement;
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ImportClause:
@@ -2839,6 +2919,7 @@ namespace ts {
// Now create a new compiler
const compilerHost: CompilerHost = {
getSourceFile: getOrCreateSourceFile,
getSourceFileByPath: getOrCreateSourceFileByPath,
getCancellationToken: () => cancellationToken,
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitivefileNames,
@@ -2874,15 +2955,17 @@ namespace ts {
};
}
const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
const newProgram = createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program);
// Release any files we have acquired in the old program but are
// not part of the new program.
if (program) {
const oldSourceFiles = program.getSourceFiles();
const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldSettings);
for (const oldSourceFile of oldSourceFiles) {
if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) {
documentRegistry.releaseDocument(oldSourceFile.fileName, oldSettings);
documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey);
}
}
}
@@ -2899,11 +2982,15 @@ namespace ts {
return;
function getOrCreateSourceFile(fileName: string): SourceFile {
return getOrCreateSourceFileByPath(fileName, toPath(fileName, currentDirectory, getCanonicalFileName));
}
function getOrCreateSourceFileByPath(fileName: string, path: Path): SourceFile {
Debug.assert(hostCache !== undefined);
// The program is asking for this file, check first if the host can locate it.
// If the host can not locate the file, then it does not exist. return undefined
// to the program to allow reporting of errors for missing files.
const hostFileInformation = hostCache.getOrCreateEntry(fileName);
const hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path);
if (!hostFileInformation) {
return undefined;
}
@@ -2913,7 +3000,7 @@ namespace ts {
// can not be reused. we have to dump all syntax trees and create new ones.
if (!changesInCompilationSettingsAffectSyntax) {
// Check if the old program had this file already
const oldSourceFile = program && program.getSourceFile(fileName);
const oldSourceFile = program && program.getSourceFileByPath(path);
if (oldSourceFile) {
// We already had a source file for this file name. Go to the registry to
// ensure that we get the right up to date version of it. We need this to
@@ -2940,16 +3027,16 @@ namespace ts {
// We do not support the scenario where a host can modify a registered
// file's script kind, i.e. in one project some file is treated as ".ts"
// and in another as ".js"
Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + fileName);
Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path);
return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
}
// We didn't already have the file. Fall through and acquire it from the registry.
}
// Could not find this file in the old program, create a new SourceFile for it.
return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind);
}
function sourceFileUpToDate(sourceFile: SourceFile): boolean {
@@ -4278,7 +4365,7 @@ namespace ts {
displayParts.push(keywordPart(SyntaxKind.NewKeyword));
displayParts.push(spacePart());
}
if (!(type.flags & TypeFlags.Anonymous)) {
if (!(type.flags & TypeFlags.Anonymous) && type.symbol) {
addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
}
addSignatureDisplayParts(signature, allSignatures, TypeFormatFlags.WriteArrowStyleSignature);
@@ -4295,7 +4382,7 @@ namespace ts {
(location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration
// get the signature from the declaration and write it
const functionDeclaration = <FunctionLikeDeclaration>location.parent;
const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getConstructSignatures() : type.getCallSignatures();
const allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures();
if (!typeChecker.isImplementationOfOverload(functionDeclaration)) {
signature = typeChecker.getSignatureFromDeclaration(functionDeclaration);
}
@@ -4493,7 +4580,7 @@ namespace ts {
symbolFlags & SymbolFlags.Signature ||
symbolFlags & SymbolFlags.Accessor ||
symbolKind === ScriptElementKind.memberFunctionElement) {
const allSignatures = type.getCallSignatures();
const allSignatures = type.getNonNullableType().getCallSignatures();
addSignatureDisplayParts(allSignatures[0], allSignatures);
}
}
@@ -4574,7 +4661,7 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
if (node === sourceFile) {
return undefined;
}
@@ -4731,18 +4818,6 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
return undefined;
}
// Labels
if (isJumpStatementTarget(node)) {
const labelName = (<Identifier>node).text;
const label = getTargetLabel((<BreakOrContinueStatement>node.parent), (<Identifier>node).text);
return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined;
}
/// Triple slash reference comments
const comment = findReferenceInPosition(sourceFile.referencedFiles, position);
if (comment) {
@@ -4752,6 +4827,7 @@ namespace ts {
}
return undefined;
}
// Type reference directives
const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
@@ -4762,6 +4838,18 @@ namespace ts {
return undefined;
}
const node = getTouchingPropertyName(sourceFile, position);
if (node === sourceFile) {
return undefined;
}
// Labels
if (isJumpStatementTarget(node)) {
const labelName = (<Identifier>node).text;
const label = getTargetLabel((<BreakOrContinueStatement>node.parent), (<Identifier>node).text);
return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined;
}
const typeChecker = program.getTypeChecker();
let symbol = typeChecker.getSymbolAtLocation(node);
@@ -4820,7 +4908,7 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
if (node === sourceFile) {
return undefined;
}
@@ -4870,8 +4958,7 @@ namespace ts {
function getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
synchronizeHostData();
filesToSearch = map(filesToSearch, normalizeSlashes);
const sourceFilesToSearch = filter(program.getSourceFiles(), f => contains(filesToSearch, f.fileName));
const sourceFilesToSearch = map(filesToSearch, f => program.getSourceFile(f));
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingWord(sourceFile, position);
@@ -4897,8 +4984,8 @@ namespace ts {
node.kind === SyntaxKind.ThisKeyword ||
node.kind === SyntaxKind.ThisType ||
node.kind === SyntaxKind.SuperKeyword ||
isLiteralNameOfPropertyDeclarationOrIndexAccess(node) ||
isNameOfExternalModuleImportOrDeclaration(node)) {
node.kind === SyntaxKind.StringLiteral ||
isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) {
const referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false);
return convertReferencedSymbols(referencedSymbols);
@@ -5557,7 +5644,7 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
if (!node) {
if (node === sourceFile) {
return undefined;
}
@@ -5565,8 +5652,8 @@ namespace ts {
// TODO (drosen): This should be enabled in a later release - currently breaks rename.
// node.kind !== SyntaxKind.ThisKeyword &&
// node.kind !== SyntaxKind.SuperKeyword &&
!isLiteralNameOfPropertyDeclarationOrIndexAccess(node) &&
!isNameOfExternalModuleImportOrDeclaration(node)) {
node.kind !== SyntaxKind.StringLiteral &&
!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) {
return undefined;
}
@@ -5601,6 +5688,10 @@ namespace ts {
const symbol = typeChecker.getSymbolAtLocation(node);
if (!symbol && node.kind === SyntaxKind.StringLiteral) {
return getReferencesForStringLiteral(<StringLiteral>node, sourceFiles);
}
// Could not find a symbol e.g. unknown identifier
if (!symbol) {
// Can't have references to something that we have no symbol for.
@@ -6157,6 +6248,52 @@ namespace ts {
}
}
function getReferencesForStringLiteral(node: StringLiteral, sourceFiles: SourceFile[]): ReferencedSymbol[] {
const typeChecker = program.getTypeChecker();
const type = getStringLiteralTypeForNode(node, typeChecker);
if (!type) {
// nothing to do here. moving on
return undefined;
}
const references: ReferenceEntry[] = [];
for (const sourceFile of sourceFiles) {
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, type.text, sourceFile.getStart(), sourceFile.getEnd());
getReferencesForStringLiteralInFile(sourceFile, type, possiblePositions, references);
}
return [{
definition: {
containerKind: "",
containerName: "",
fileName: node.getSourceFile().fileName,
kind: ScriptElementKind.variableElement,
name: type.text,
textSpan: createTextSpanFromBounds(node.getStart(), node.getEnd())
},
references: references
}];
function getReferencesForStringLiteralInFile(sourceFile: SourceFile, searchType: Type, possiblePositions: number[], references: ReferenceEntry[]): void {
for (const position of possiblePositions) {
cancellationToken.throwIfCancellationRequested();
const node = getTouchingWord(sourceFile, position);
if (!node || node.kind !== SyntaxKind.StringLiteral) {
return;
}
const type = getStringLiteralTypeForNode(<StringLiteral>node, typeChecker);
if (type === searchType) {
references.push(getReferenceEntryFromNode(node));
}
}
}
}
function populateSearchSymbolSet(symbol: Symbol, location: Node): Symbol[] {
// The search set contains at least the current symbol
let result = [symbol];
@@ -6164,7 +6301,8 @@ namespace ts {
// If the location is name of property symbol from object literal destructuring pattern
// Search the property symbol
// for ( { property: p2 } of elems) { }
if (isNameOfPropertyAssignment(location) && location.parent.kind !== SyntaxKind.ShorthandPropertyAssignment) {
const containingObjectLiteralElement = getContainingObjectLiteralElement(location);
if (containingObjectLiteralElement && containingObjectLiteralElement.kind !== SyntaxKind.ShorthandPropertyAssignment) {
const propertySymbol = getPropertySymbolOfDestructuringAssignment(location);
if (propertySymbol) {
result.push(propertySymbol);
@@ -6190,8 +6328,8 @@ namespace ts {
// If the location is in a context sensitive location (i.e. in an object literal) try
// to get a contextual type for it, and add the property symbol from the contextual
// type to the search set
if (isNameOfPropertyAssignment(location)) {
forEach(getPropertySymbolsFromContextualType(location), contextualSymbol => {
if (containingObjectLiteralElement) {
forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), contextualSymbol => {
addRange(result, typeChecker.getRootSymbols(contextualSymbol));
});
@@ -6292,7 +6430,7 @@ namespace ts {
if (type) {
const propertySymbol = typeChecker.getPropertyOfType(type, propertyName);
if (propertySymbol) {
result.push(propertySymbol);
result.push(...typeChecker.getRootSymbols(propertySymbol));
}
// Visit the typeReference as well to see if it directly or indirectly use that property
@@ -6318,8 +6456,9 @@ namespace ts {
// If the reference location is in an object literal, try to get the contextual type for the
// object literal, lookup the property symbol in the contextual type, and use this symbol to
// compare to our searchSymbol
if (isNameOfPropertyAssignment(referenceLocation)) {
const contextualSymbol = forEach(getPropertySymbolsFromContextualType(referenceLocation), contextualSymbol => {
const containingObjectLiteralElement = getContainingObjectLiteralElement(referenceLocation);
if (containingObjectLiteralElement) {
const contextualSymbol = forEach(getPropertySymbolsFromContextualType(containingObjectLiteralElement), contextualSymbol => {
return forEach(typeChecker.getRootSymbols(contextualSymbol), s => searchSymbols.indexOf(s) >= 0 ? s : undefined);
});
@@ -6365,37 +6504,38 @@ namespace ts {
});
}
function getPropertySymbolsFromContextualType(node: Node): Symbol[] {
if (isNameOfPropertyAssignment(node)) {
const objectLiteral = <ObjectLiteralExpression>node.parent.parent;
const contextualType = typeChecker.getContextualType(objectLiteral);
const name = (<Identifier>node).text;
if (contextualType) {
if (contextualType.flags & TypeFlags.Union) {
// This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types)
// if not, search the constituent types for the property
const unionProperty = contextualType.getProperty(name);
if (unionProperty) {
return [unionProperty];
}
else {
const result: Symbol[] = [];
forEach((<UnionType>contextualType).types, t => {
const symbol = t.getProperty(name);
if (symbol) {
result.push(symbol);
}
});
return result;
}
}
else {
const symbol = contextualType.getProperty(name);
if (symbol) {
return [symbol];
}
}
function getNameFromObjectLiteralElement(node: ObjectLiteralElement) {
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;
}
return undefined;
}
return (<Identifier | LiteralExpression>node.name).text;
}
function getPropertySymbolsFromContextualType(node: ObjectLiteralElement): Symbol[] {
const objectLiteral = <ObjectLiteralExpression>node.parent;
const contextualType = typeChecker.getContextualType(objectLiteral);
const name = getNameFromObjectLiteralElement(node);
if (name && contextualType) {
const result: Symbol[] = [];
const symbol = contextualType.getProperty(name);
if (symbol) {
result.push(symbol);
}
if (contextualType.flags & TypeFlags.Union) {
forEach((<UnionType>contextualType).types, t => {
const symbol = t.getProperty(name);
if (symbol) {
result.push(symbol);
}
});
}
return result;
}
return undefined;
}
@@ -6472,8 +6612,8 @@ namespace ts {
/// NavigateTo
function getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[] {
synchronizeHostData();
return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount);
const checker = getProgram().getTypeChecker();
return ts.NavigateTo.getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount);
}
function getEmitOutput(fileName: string): EmitOutput {
@@ -6671,7 +6811,7 @@ namespace ts {
// Get node at the location
const node = getTouchingPropertyName(sourceFile, startPos);
if (!node) {
if (node === sourceFile) {
return;
}
@@ -7677,6 +7817,14 @@ namespace ts {
}
}
function getStringLiteralTypeForNode(node: StringLiteral | StringLiteralTypeNode, typeChecker: TypeChecker): StringLiteralType {
const searchNode = node.parent.kind === SyntaxKind.StringLiteralType ? <StringLiteralTypeNode>node.parent : node;
const type = typeChecker.getTypeAtLocation(searchNode);
if (type && type.flags & TypeFlags.StringLiteral) {
return <StringLiteralType>type;
}
return undefined;
}
function getRenameInfo(fileName: string, position: number): RenameInfo {
synchronizeHostData();
@@ -7684,46 +7832,60 @@ namespace ts {
const sourceFile = getValidSourceFile(fileName);
const typeChecker = program.getTypeChecker();
const defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings());
const canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName));
const node = getTouchingWord(sourceFile, position);
// Can only rename an identifier.
if (node && node.kind === SyntaxKind.Identifier) {
const symbol = typeChecker.getSymbolAtLocation(node);
if (node) {
if (node.kind === SyntaxKind.Identifier ||
node.kind === SyntaxKind.StringLiteral ||
isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) {
const symbol = typeChecker.getSymbolAtLocation(node);
// Only allow a symbol to be renamed if it actually has at least one declaration.
if (symbol) {
const declarations = symbol.getDeclarations();
if (declarations && declarations.length > 0) {
// Disallow rename for elements that are defined in the standard TypeScript library.
const defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings());
const canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName));
if (defaultLibFileName) {
for (const current of declarations) {
const sourceFile = current.getSourceFile();
// TODO (drosen): When is there no source file?
if (!sourceFile) {
continue;
}
// Only allow a symbol to be renamed if it actually has at least one declaration.
if (symbol) {
const declarations = symbol.getDeclarations();
if (declarations && declarations.length > 0) {
// Disallow rename for elements that are defined in the standard TypeScript library.
if (forEach(declarations, isDefinedInLibraryFile)) {
return getRenameInfoError(getLocaleSpecificMessage(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library));
}
const canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName));
if (canonicalName === canonicalDefaultLibName) {
return getRenameInfoError(getLocaleSpecificMessage(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library));
}
const displayName = stripQuotes(getDeclaredName(typeChecker, symbol, node));
const kind = getSymbolKind(symbol, node);
if (kind) {
return {
canRename: true,
kind,
displayName,
localizedErrorMessage: undefined,
fullDisplayName: typeChecker.getFullyQualifiedName(symbol),
kindModifiers: getSymbolModifiers(symbol),
triggerSpan: createTriggerSpanForNode(node, sourceFile)
};
}
}
const displayName = stripQuotes(getDeclaredName(typeChecker, symbol, node));
const kind = getSymbolKind(symbol, node);
if (kind) {
return {
canRename: true,
kind,
displayName,
localizedErrorMessage: undefined,
fullDisplayName: typeChecker.getFullyQualifiedName(symbol),
kindModifiers: getSymbolModifiers(symbol),
triggerSpan: createTextSpan(node.getStart(), node.getWidth())
};
}
else if (node.kind === SyntaxKind.StringLiteral) {
const type = getStringLiteralTypeForNode(<StringLiteral>node, typeChecker);
if (type) {
if (isDefinedInLibraryFile(node)) {
return getRenameInfoError(getLocaleSpecificMessage(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library));
}
else {
const displayName = stripQuotes(type.text);
return {
canRename: true,
kind: ScriptElementKind.variableElement,
displayName,
localizedErrorMessage: undefined,
fullDisplayName: displayName,
kindModifiers: ScriptElementKindModifier.none,
triggerSpan: createTriggerSpanForNode(node, sourceFile)
};
}
}
}
}
@@ -7742,6 +7904,28 @@ namespace ts {
triggerSpan: undefined
};
}
function isDefinedInLibraryFile(declaration: Node) {
if (defaultLibFileName) {
const sourceFile = declaration.getSourceFile();
const canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName));
if (canonicalName === canonicalDefaultLibName) {
return true;
}
}
return false;
}
function createTriggerSpanForNode(node: Node, sourceFile: SourceFile) {
let start = node.getStart(sourceFile);
let width = node.getWidth(sourceFile);
if (node.kind === SyntaxKind.StringLiteral) {
// Exclude the quotes
start += 1;
width -= 2;
}
return createTextSpan(start, width);
}
}
return {
@@ -7813,7 +7997,8 @@ namespace ts {
// "a['propname']" then we want to store "propname" in the name table.
if (isDeclarationName(node) ||
node.parent.kind === SyntaxKind.ExternalModuleReference ||
isArgumentOfElementAccessExpression(node)) {
isArgumentOfElementAccessExpression(node) ||
isLiteralComputedPropertyDeclarationName(node)) {
nameTable[(<LiteralExpression>node).text] = nameTable[(<LiteralExpression>node).text] === undefined ? node.pos : -1;
}
+11
View File
@@ -61,6 +61,7 @@ namespace ts {
getLocalizedDiagnosticMessages(): string;
getCancellationToken(): HostCancellationToken;
getCurrentDirectory(): string;
getDirectories(path: string): string[];
getDefaultLibFileName(options: string): string;
getNewLine?(): string;
getProjectVersion?(): string;
@@ -400,6 +401,10 @@ namespace ts {
return this.shimHost.getCurrentDirectory();
}
public getDirectories(path: string): string[] {
return this.shimHost.getDirectories(path);
}
public getDefaultLibFileName(options: CompilerOptions): string {
return this.shimHost.getDefaultLibFileName(JSON.stringify(options));
}
@@ -431,11 +436,15 @@ namespace ts {
export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost {
public directoryExists: (directoryName: string) => boolean;
public realpath: (path: string) => string;
constructor(private shimHost: CoreServicesShimHost) {
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
if ("realpath" in this.shimHost) {
this.realpath = path => this.shimHost.realpath(path);
}
}
public readDirectory(rootDir: string, extension: string, exclude: string[], depth?: number): string[] {
@@ -997,6 +1006,7 @@ namespace ts {
options: {},
typingOptions: {},
files: [],
raw: {},
errors: [realizeDiagnostic(result.error, "\r\n")]
};
}
@@ -1008,6 +1018,7 @@ namespace ts {
options: configFile.options,
typingOptions: configFile.typingOptions,
files: configFile.fileNames,
raw: configFile.raw,
errors: realizeDiagnostics(configFile.errors, "\r\n")
};
});
+74 -74
View File
@@ -7,7 +7,7 @@ namespace ts.SignatureHelp {
// To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it
// will return the generic identifier that started the expression (e.g. "foo" in "foo<any, |"). It is then up to the caller to ensure that this is a valid generic expression through
// looking up the type. The method will also keep track of the parameter index inside the expression.
//public static isInPartiallyWrittenTypeArgumentList(syntaxTree: TypeScript.SyntaxTree, position: number): any {
// public static isInPartiallyWrittenTypeArgumentList(syntaxTree: TypeScript.SyntaxTree, position: number): any {
// let token = Syntax.findTokenOnLeft(syntaxTree.sourceUnit(), position, /*includeSkippedTokens*/ true);
// if (token && TypeScript.Syntax.hasAncestorOfKind(token, TypeScript.SyntaxKind.TypeParameterList)) {
@@ -125,9 +125,9 @@ namespace ts.SignatureHelp {
// }
// return null;
//}
// }
//private static moveBackUpTillMatchingTokenKind(token: TypeScript.ISyntaxToken, tokenKind: TypeScript.SyntaxKind, matchingTokenKind: TypeScript.SyntaxKind): TypeScript.ISyntaxToken {
// private static moveBackUpTillMatchingTokenKind(token: TypeScript.ISyntaxToken, tokenKind: TypeScript.SyntaxKind, matchingTokenKind: TypeScript.SyntaxKind): TypeScript.ISyntaxToken {
// if (!token || token.kind() !== tokenKind) {
// throw TypeScript.Errors.invalidOperation();
// }
@@ -161,8 +161,8 @@ namespace ts.SignatureHelp {
// // Did not find matching token
// return null;
//}
let emptyArray: any[] = [];
// }
const emptyArray: any[] = [];
const enum ArgumentListKind {
TypeArguments,
@@ -179,16 +179,16 @@ namespace ts.SignatureHelp {
}
export function getSignatureHelpItems(program: Program, sourceFile: SourceFile, position: number, cancellationToken: CancellationToken): SignatureHelpItems {
let typeChecker = program.getTypeChecker();
const typeChecker = program.getTypeChecker();
// Decide whether to show signature help
let startingToken = findTokenOnLeftOfPosition(sourceFile, position);
const startingToken = findTokenOnLeftOfPosition(sourceFile, position);
if (!startingToken) {
// We are at the beginning of the file
return undefined;
}
let argumentInfo = getContainingArgumentInfo(startingToken);
const argumentInfo = getContainingArgumentInfo(startingToken);
cancellationToken.throwIfCancellationRequested();
// Semantic filtering of signature help
@@ -196,9 +196,9 @@ namespace ts.SignatureHelp {
return undefined;
}
let call = argumentInfo.invocation;
let candidates = <Signature[]>[];
let resolvedSignature = typeChecker.getResolvedSignature(call, candidates);
const call = argumentInfo.invocation;
const candidates = <Signature[]>[];
const resolvedSignature = typeChecker.getResolvedSignature(call, candidates);
cancellationToken.throwIfCancellationRequested();
if (!candidates.length) {
@@ -219,9 +219,9 @@ namespace ts.SignatureHelp {
}
// See if we can find some symbol with the call expression name that has call signatures.
let callExpression = <CallExpression>argumentInfo.invocation;
let expression = callExpression.expression;
let name = expression.kind === SyntaxKind.Identifier
const callExpression = <CallExpression>argumentInfo.invocation;
const expression = callExpression.expression;
const name = expression.kind === SyntaxKind.Identifier
? <Identifier> expression
: expression.kind === SyntaxKind.PropertyAccessExpression
? (<PropertyAccessExpression>expression).name
@@ -231,18 +231,18 @@ namespace ts.SignatureHelp {
return undefined;
}
let typeChecker = program.getTypeChecker();
for (let sourceFile of program.getSourceFiles()) {
let nameToDeclarations = sourceFile.getNamedDeclarations();
let declarations = getProperty(nameToDeclarations, name.text);
const typeChecker = program.getTypeChecker();
for (const sourceFile of program.getSourceFiles()) {
const nameToDeclarations = sourceFile.getNamedDeclarations();
const declarations = getProperty(nameToDeclarations, name.text);
if (declarations) {
for (let declaration of declarations) {
let symbol = declaration.symbol;
for (const declaration of declarations) {
const symbol = declaration.symbol;
if (symbol) {
let type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
const type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
if (type) {
let callSignatures = type.getCallSignatures();
const callSignatures = type.getCallSignatures();
if (callSignatures && callSignatures.length) {
return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo);
}
@@ -259,7 +259,7 @@ namespace ts.SignatureHelp {
*/
function getImmediatelyContainingArgumentInfo(node: Node): ArgumentListInfo {
if (node.parent.kind === SyntaxKind.CallExpression || node.parent.kind === SyntaxKind.NewExpression) {
let callExpression = <CallExpression>node.parent;
const callExpression = <CallExpression>node.parent;
// There are 3 cases to handle:
// 1. The token introduces a list, and should begin a sig help session
// 2. The token is either not associated with a list, or ends a list, so the session should end
@@ -278,8 +278,8 @@ namespace ts.SignatureHelp {
node.kind === SyntaxKind.OpenParenToken) {
// Find the list that starts right *after* the < or ( token.
// If the user has just opened a list, consider this item 0.
let list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile);
let isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;
const list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile);
const isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;
Debug.assert(list !== undefined);
return {
kind: isTypeArgList ? ArgumentListKind.TypeArguments : ArgumentListKind.CallArguments,
@@ -296,16 +296,16 @@ namespace ts.SignatureHelp {
// - Between the type arguments and the arguments (greater than token)
// - On the target of the call (parent.func)
// - On the 'new' keyword in a 'new' expression
let listItemInfo = findListItemInfo(node);
const listItemInfo = findListItemInfo(node);
if (listItemInfo) {
let list = listItemInfo.list;
let isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;
const list = listItemInfo.list;
const isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos;
let argumentIndex = getArgumentIndex(list, node);
let argumentCount = getArgumentCount(list);
const argumentIndex = getArgumentIndex(list, node);
const argumentCount = getArgumentCount(list);
Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount,
`argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`);
`argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`);
return {
kind: isTypeArgList ? ArgumentListKind.TypeArguments : ArgumentListKind.CallArguments,
@@ -324,18 +324,18 @@ namespace ts.SignatureHelp {
}
}
else if (node.kind === SyntaxKind.TemplateHead && node.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) {
let templateExpression = <TemplateExpression>node.parent;
let tagExpression = <TaggedTemplateExpression>templateExpression.parent;
const templateExpression = <TemplateExpression>node.parent;
const tagExpression = <TaggedTemplateExpression>templateExpression.parent;
Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression);
let argumentIndex = isInsideTemplateLiteral(<LiteralExpression>node, position) ? 0 : 1;
const argumentIndex = isInsideTemplateLiteral(<LiteralExpression>node, position) ? 0 : 1;
return getArgumentListInfoForTemplate(tagExpression, argumentIndex);
}
else if (node.parent.kind === SyntaxKind.TemplateSpan && node.parent.parent.parent.kind === SyntaxKind.TaggedTemplateExpression) {
let templateSpan = <TemplateSpan>node.parent;
let templateExpression = <TemplateExpression>templateSpan.parent;
let tagExpression = <TaggedTemplateExpression>templateExpression.parent;
const templateSpan = <TemplateSpan>node.parent;
const templateExpression = <TemplateExpression>templateSpan.parent;
const tagExpression = <TaggedTemplateExpression>templateExpression.parent;
Debug.assert(templateExpression.kind === SyntaxKind.TemplateExpression);
// If we're just after a template tail, don't show signature help.
@@ -343,12 +343,12 @@ namespace ts.SignatureHelp {
return undefined;
}
let spanIndex = templateExpression.templateSpans.indexOf(templateSpan);
let argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node);
const spanIndex = templateExpression.templateSpans.indexOf(templateSpan);
const argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node);
return getArgumentListInfoForTemplate(tagExpression, argumentIndex);
}
return undefined;
}
@@ -365,8 +365,8 @@ namespace ts.SignatureHelp {
// that trailing comma in the list, and we'll have generated the appropriate
// arg index.
let argumentIndex = 0;
let listChildren = argumentsList.getChildren();
for (let child of listChildren) {
const listChildren = argumentsList.getChildren();
for (const child of listChildren) {
if (child === node) {
break;
}
@@ -390,7 +390,7 @@ namespace ts.SignatureHelp {
// we'll have: 'a' '<comma>' '<missing>'
// That will give us 2 non-commas. We then add one for the last comma, givin us an
// arg count of 3.
let listChildren = argumentsList.getChildren();
const listChildren = argumentsList.getChildren();
let argumentCount = countWhere(listChildren, arg => arg.kind !== SyntaxKind.CommaToken);
if (listChildren.length > 0 && lastOrUndefined(listChildren).kind === SyntaxKind.CommaToken) {
@@ -426,11 +426,11 @@ namespace ts.SignatureHelp {
function getArgumentListInfoForTemplate(tagExpression: TaggedTemplateExpression, argumentIndex: number): ArgumentListInfo {
// argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument.
let argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral
const argumentCount = tagExpression.template.kind === SyntaxKind.NoSubstitutionTemplateLiteral
? 1
: (<TemplateExpression>tagExpression.template).templateSpans.length + 1;
Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`);
Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`);
return {
kind: ArgumentListKind.TaggedTemplateArguments,
@@ -450,14 +450,14 @@ namespace ts.SignatureHelp {
//
// The applicable span is from the first bar to the second bar (inclusive,
// but not including parentheses)
let applicableSpanStart = argumentsList.getFullStart();
let applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
const applicableSpanStart = argumentsList.getFullStart();
const applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getApplicableSpanForTaggedTemplate(taggedTemplate: TaggedTemplateExpression): TextSpan {
let template = taggedTemplate.template;
let applicableSpanStart = template.getStart();
const template = taggedTemplate.template;
const applicableSpanStart = template.getStart();
let applicableSpanEnd = template.getEnd();
// We need to adjust the end position for the case where the template does not have a tail.
@@ -470,7 +470,7 @@ namespace ts.SignatureHelp {
// This is because a Missing node has no width. However, what we actually want is to include trivia
// leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail.
if (template.kind === SyntaxKind.TemplateExpression) {
let lastSpan = lastOrUndefined((<TemplateExpression>template).templateSpans);
const lastSpan = lastOrUndefined((<TemplateExpression>template).templateSpans);
if (lastSpan.literal.getFullWidth() === 0) {
applicableSpanEnd = skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false);
}
@@ -491,7 +491,7 @@ namespace ts.SignatureHelp {
Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind);
}
let argumentInfo = getImmediatelyContainingArgumentInfo(n);
const argumentInfo = getImmediatelyContainingArgumentInfo(n);
if (argumentInfo) {
return argumentInfo;
}
@@ -503,8 +503,8 @@ namespace ts.SignatureHelp {
}
function getChildListThatStartsWithOpenerToken(parent: Node, openerToken: Node, sourceFile: SourceFile): Node {
let children = parent.getChildren(sourceFile);
let indexOfOpenerToken = children.indexOf(openerToken);
const children = parent.getChildren(sourceFile);
const indexOfOpenerToken = children.indexOf(openerToken);
Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1);
return children[indexOfOpenerToken + 1];
}
@@ -521,7 +521,7 @@ namespace ts.SignatureHelp {
let maxParamsSignatureIndex = -1;
let maxParams = -1;
for (let i = 0; i < candidates.length; i++) {
let candidate = candidates[i];
const candidate = candidates[i];
if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) {
return i;
@@ -537,17 +537,17 @@ namespace ts.SignatureHelp {
}
function createSignatureHelpItems(candidates: Signature[], bestSignature: Signature, argumentListInfo: ArgumentListInfo): SignatureHelpItems {
let applicableSpan = argumentListInfo.argumentsSpan;
let isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments;
const applicableSpan = argumentListInfo.argumentsSpan;
const isTypeParameterList = argumentListInfo.kind === ArgumentListKind.TypeArguments;
let invocation = argumentListInfo.invocation;
let callTarget = getInvokedExpression(invocation)
let callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget);
let callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined);
let items: SignatureHelpItem[] = map(candidates, candidateSignature => {
const invocation = argumentListInfo.invocation;
const callTarget = getInvokedExpression(invocation);
const callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget);
const callTargetDisplayParts = callTargetSymbol && symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined);
const items: SignatureHelpItem[] = map(candidates, candidateSignature => {
let signatureHelpParameters: SignatureHelpParameter[];
let prefixDisplayParts: SymbolDisplayPart[] = [];
let suffixDisplayParts: SymbolDisplayPart[] = [];
const prefixDisplayParts: SymbolDisplayPart[] = [];
const suffixDisplayParts: SymbolDisplayPart[] = [];
if (callTargetDisplayParts) {
addRange(prefixDisplayParts, callTargetDisplayParts);
@@ -555,28 +555,28 @@ namespace ts.SignatureHelp {
if (isTypeParameterList) {
prefixDisplayParts.push(punctuationPart(SyntaxKind.LessThanToken));
let typeParameters = candidateSignature.typeParameters;
const typeParameters = candidateSignature.typeParameters;
signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray;
suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
let parameterParts = mapToDisplayParts(writer =>
const parameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisType, candidateSignature.parameters, writer, invocation));
addRange(suffixDisplayParts, parameterParts);
}
else {
let typeParameterParts = mapToDisplayParts(writer =>
const typeParameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation));
addRange(prefixDisplayParts, typeParameterParts);
prefixDisplayParts.push(punctuationPart(SyntaxKind.OpenParenToken));
let parameters = candidateSignature.parameters;
const parameters = candidateSignature.parameters;
signatureHelpParameters = parameters.length > 0 ? map(parameters, createSignatureHelpParameterForParameter) : emptyArray;
suffixDisplayParts.push(punctuationPart(SyntaxKind.CloseParenToken));
}
let returnTypeParts = mapToDisplayParts(writer =>
const returnTypeParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation));
addRange(suffixDisplayParts, returnTypeParts);
return {
isVariadic: candidateSignature.hasRestParameter,
prefixDisplayParts,
@@ -587,17 +587,17 @@ namespace ts.SignatureHelp {
};
});
let argumentIndex = argumentListInfo.argumentIndex;
const argumentIndex = argumentListInfo.argumentIndex;
// argumentCount is the *apparent* number of arguments.
let argumentCount = argumentListInfo.argumentCount;
const argumentCount = argumentListInfo.argumentCount;
let selectedItemIndex = candidates.indexOf(bestSignature);
if (selectedItemIndex < 0) {
selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount);
}
Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`);
Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, `argumentCount < argumentIndex, ${argumentCount} < ${argumentIndex}`);
return {
items,
@@ -608,7 +608,7 @@ namespace ts.SignatureHelp {
};
function createSignatureHelpParameterForParameter(parameter: Symbol): SignatureHelpParameter {
let displayParts = mapToDisplayParts(writer =>
const displayParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation));
return {
@@ -620,7 +620,7 @@ namespace ts.SignatureHelp {
}
function createSignatureHelpParameterForTypeParameter(typeParameter: TypeParameter): SignatureHelpParameter {
let displayParts = mapToDisplayParts(writer =>
const displayParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation));
return {
+63 -56
View File
@@ -7,8 +7,8 @@ namespace ts {
}
export function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number {
let lineStarts = sourceFile.getLineStarts();
let line = sourceFile.getLineAndCharacterOfPosition(position).line;
const lineStarts = sourceFile.getLineStarts();
const line = sourceFile.getLineAndCharacterOfPosition(position).line;
return lineStarts[line];
}
@@ -29,8 +29,8 @@ namespace ts {
}
export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number) {
let start = Math.max(start1, start2);
let end = Math.min(end1, end2);
const start = Math.max(start1, start2);
const end = Math.min(end1, end2);
return start < end;
}
@@ -131,7 +131,7 @@ namespace ts {
return isCompletedNode((<IterationStatement>n).statement, sourceFile);
case SyntaxKind.DoStatement:
// rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')';
let hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile);
const hasWhileKeyword = findChildOfKind(n, SyntaxKind.WhileKeyword, sourceFile);
if (hasWhileKeyword) {
return nodeEndsWith(n, SyntaxKind.CloseParenToken, sourceFile);
}
@@ -145,13 +145,13 @@ namespace ts {
case SyntaxKind.VoidExpression:
case SyntaxKind.YieldExpression:
case SyntaxKind.SpreadElementExpression:
let unaryWordExpression = (<TypeOfExpression | DeleteExpression | VoidExpression | YieldExpression | SpreadElementExpression>n);
const unaryWordExpression = (<TypeOfExpression | DeleteExpression | VoidExpression | YieldExpression | SpreadElementExpression>n);
return isCompletedNode(unaryWordExpression.expression, sourceFile);
case SyntaxKind.TaggedTemplateExpression:
return isCompletedNode((<TaggedTemplateExpression>n).template, sourceFile);
case SyntaxKind.TemplateExpression:
let lastSpan = lastOrUndefined((<TemplateExpression>n).templateSpans);
const lastSpan = lastOrUndefined((<TemplateExpression>n).templateSpans);
return isCompletedNode(lastSpan, sourceFile);
case SyntaxKind.TemplateSpan:
return nodeIsPresent((<TemplateSpan>n).literal);
@@ -173,9 +173,9 @@ namespace ts {
* If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'.
*/
function nodeEndsWith(n: Node, expectedLastToken: SyntaxKind, sourceFile: SourceFile): boolean {
let children = n.getChildren(sourceFile);
const children = n.getChildren(sourceFile);
if (children.length) {
let last = lastOrUndefined(children);
const last = lastOrUndefined(children);
if (last.kind === expectedLastToken) {
return true;
}
@@ -187,7 +187,7 @@ namespace ts {
}
export function findListItemInfo(node: Node): ListItemInfo {
let list = findContainingList(node);
const list = findContainingList(node);
// It is possible at this point for syntaxList to be undefined, either if
// node.parent had no list child, or if none of its list children contained
@@ -197,8 +197,8 @@ namespace ts {
return undefined;
}
let children = list.getChildren();
let listItemIndex = indexOf(children, node);
const children = list.getChildren();
const listItemIndex = indexOf(children, node);
return {
listItemIndex,
@@ -219,7 +219,7 @@ namespace ts {
// be parented by the container of the SyntaxList, not the SyntaxList itself.
// In order to find the list item index, we first need to locate SyntaxList itself and then search
// for the position of the relevant node (or comma).
let syntaxList = forEach(node.parent.getChildren(), c => {
const syntaxList = forEach(node.parent.getChildren(), c => {
// find syntax list that covers the span of the node
if (c.kind === SyntaxKind.SyntaxList && c.pos <= node.pos && c.end >= node.end) {
return c;
@@ -266,16 +266,16 @@ namespace ts {
// find the child that contains 'position'
for (let i = 0, n = current.getChildCount(sourceFile); i < n; i++) {
let child = current.getChildAt(i);
let start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile);
const child = current.getChildAt(i);
const start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile);
if (start <= position) {
let end = child.getEnd();
const end = child.getEnd();
if (position < end || (position === end && child.kind === SyntaxKind.EndOfFileToken)) {
current = child;
continue outer;
}
else if (includeItemAtEndPosition && end === position) {
let previousToken = findPrecedingToken(position, sourceFile, child);
const previousToken = findPrecedingToken(position, sourceFile, child);
if (previousToken && includeItemAtEndPosition(previousToken)) {
return previousToken;
}
@@ -297,7 +297,7 @@ namespace ts {
export function findTokenOnLeftOfPosition(file: SourceFile, position: number): Node {
// Ideally, getTokenAtPosition should return a token. However, it is currently
// broken, so we do a check to make sure the result was indeed a token.
let tokenAtPosition = getTokenAtPosition(file, position);
const tokenAtPosition = getTokenAtPosition(file, position);
if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) {
return tokenAtPosition;
}
@@ -314,9 +314,9 @@ namespace ts {
return n;
}
let children = n.getChildren();
for (let child of children) {
let shouldDiveInChildNode =
const children = n.getChildren();
for (const child of children) {
const shouldDiveInChildNode =
// previous token is enclosed somewhere in the child
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
@@ -339,8 +339,8 @@ namespace ts {
return n;
}
let children = n.getChildren();
let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
const children = n.getChildren();
const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
return candidate && findRightmostToken(candidate);
}
@@ -352,7 +352,7 @@ namespace ts {
const children = n.getChildren();
for (let i = 0, len = children.length; i < len; i++) {
let child = children[i];
const child = children[i];
// condition 'position < child.end' checks if child node end after the position
// in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc'
// aaaa___bbbb___$__ccc
@@ -369,8 +369,8 @@ namespace ts {
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
return candidate && findRightmostToken(candidate)
const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
return candidate && findRightmostToken(candidate);
}
else {
// candidate should be in this node
@@ -386,14 +386,14 @@ namespace ts {
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
if (children.length) {
let candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
const candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
return candidate && findRightmostToken(candidate);
}
}
/// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition'
function findRightmostChildNodeWithTokens(children: Node[], exclusiveStartPosition: number): Node {
for (let i = exclusiveStartPosition - 1; i >= 0; --i) {
for (let i = exclusiveStartPosition - 1; i >= 0; i--) {
if (nodeHasTokens(children[i])) {
return children[i];
}
@@ -402,7 +402,7 @@ namespace ts {
}
export function isInString(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position);
return token && (token.kind === SyntaxKind.StringLiteral || token.kind === SyntaxKind.StringLiteralType) && position > token.getStart(sourceFile);
}
@@ -414,7 +414,7 @@ namespace ts {
* returns true if the position is in between the open and close elements of an JSX expression.
*/
export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position);
if (!token) {
return false;
@@ -446,7 +446,7 @@ namespace ts {
}
export function isInTemplateString(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position);
return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}
@@ -455,10 +455,10 @@ namespace ts {
* satisfies predicate, and false otherwise.
*/
export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean {
let token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position);
if (token && position <= token.getStart(sourceFile)) {
let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
// The end marker of a single-line comment does not include the newline character.
// In the following case, we are inside a comment (^ denotes the cursor position):
@@ -482,16 +482,16 @@ namespace ts {
}
export function hasDocComment(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position);
// First, we have to see if this position actually landed in a comment.
let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
return forEach(commentRanges, jsDocPrefix);
function jsDocPrefix(c: CommentRange): boolean {
var text = sourceFile.text;
return text.length >= c.pos + 3 && text[c.pos] === '/' && text[c.pos + 1] === '*' && text[c.pos + 2] === '*';
const text = sourceFile.text;
return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*";
}
}
@@ -515,9 +515,9 @@ namespace ts {
}
if (node) {
let jsDocComment = node.jsDocComment;
const jsDocComment = node.jsDocComment;
if (jsDocComment) {
for (let tag of jsDocComment.tags) {
for (const tag of jsDocComment.tags) {
if (tag.pos <= position && position <= tag.end) {
return tag;
}
@@ -535,8 +535,8 @@ namespace ts {
}
export function getNodeModifiers(node: Node): string {
let flags = getCombinedModifierFlags(node);
let result: string[] = [];
const flags = getCombinedModifierFlags(node);
const result: string[] = [];
if (flags & ModifierFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier);
if (flags & ModifierFlags.Protected) result.push(ScriptElementKindModifier.protectedMemberModifier);
@@ -546,7 +546,7 @@ namespace ts {
if (flags & ModifierFlags.Export) result.push(ScriptElementKindModifier.exportedModifier);
if (isInAmbientContext(node)) result.push(ScriptElementKindModifier.ambientModifier);
return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none;
return result.length > 0 ? result.join(",") : ScriptElementKindModifier.none;
}
export function getTypeArgumentOrTypeParameterList(node: Node): NodeArray<Node> {
@@ -608,7 +608,7 @@ namespace ts {
}
export function compareDataObjects(dst: any, src: any): boolean {
for (let e in dst) {
for (const e in dst) {
if (typeof dst[e] === "object") {
if (!compareDataObjects(dst[e], src[e])) {
return false;
@@ -661,7 +661,7 @@ namespace ts {
return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === SyntaxKind.Parameter;
}
let displayPartWriter = getDisplayPartWriter();
const displayPartWriter = getDisplayPartWriter();
function getDisplayPartWriter(): DisplayPartsSymbolWriter {
let displayParts: SymbolDisplayPart[];
let lineStart: boolean;
@@ -687,7 +687,7 @@ namespace ts {
function writeIndent() {
if (lineStart) {
let indentString = getIndentString(indent);
const indentString = getIndentString(indent);
if (indentString) {
displayParts.push(displayPart(indentString, SymbolDisplayPartKind.space));
}
@@ -711,7 +711,7 @@ namespace ts {
}
function resetWriter() {
displayParts = []
displayParts = [];
lineStart = true;
indent = 0;
}
@@ -721,7 +721,7 @@ namespace ts {
return displayPart(text, displayPartKind(symbol), symbol);
function displayPartKind(symbol: Symbol): SymbolDisplayPartKind {
let flags = symbol.flags;
const flags = symbol.flags;
if (flags & SymbolFlags.Variable) {
return isFirstDeclarationOfSymbolParameter(symbol) ? SymbolDisplayPartKind.parameterName : SymbolDisplayPartKind.localName;
@@ -768,7 +768,7 @@ namespace ts {
}
export function textOrKeywordPart(text: string) {
var kind = stringToToken(text);
const kind = stringToToken(text);
return kind === undefined
? textPart(text)
: keywordPart(kind);
@@ -792,7 +792,7 @@ namespace ts {
export function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] {
writeDisplayParts(displayPartWriter);
let result = displayPartWriter.displayParts();
const result = displayPartWriter.displayParts();
displayPartWriter.clear();
return result;
}
@@ -821,12 +821,16 @@ namespace ts {
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
else if (isStringOrNumericLiteral(location.kind) &&
location.parent.kind === SyntaxKind.ComputedPropertyName) {
return (<LiteralExpression>location).text;
}
// Try to get the local symbol if we're dealing with an 'export default'
// since that symbol has the "true" name.
let localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol);
const localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol);
let name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
const name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
return name;
}
@@ -843,7 +847,7 @@ namespace ts {
* @return non-quoted string
*/
export function stripQuotes(name: string) {
let length = name.length;
const length = name.length;
if (length >= 2 &&
name.charCodeAt(0) === name.charCodeAt(length - 1) &&
(name.charCodeAt(0) === CharacterCodes.doubleQuote || name.charCodeAt(0) === CharacterCodes.singleQuote)) {
@@ -858,12 +862,15 @@ namespace ts {
}
export function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind {
// First check to see if the script kind can be determined from the file name
var scriptKind = getScriptKindFromFileName(fileName);
if (scriptKind === ScriptKind.Unknown && host && host.getScriptKind) {
// Next check to see if the host can resolve the script kind
// First check to see if the script kind was specified by the host. Chances are the host
// may override the default script kind for the file extension.
let scriptKind: ScriptKind;
if (host && host.getScriptKind) {
scriptKind = host.getScriptKind(fileName);
}
if (!scriptKind || scriptKind === ScriptKind.Unknown) {
scriptKind = getScriptKindFromFileName(fileName);
}
return ensureScriptKind(fileName, scriptKind);
}
}
@@ -55,7 +55,7 @@ export function delint(sourceFile: ts.SourceFile) {
}
}
const fileNames = process.argv.slice(2);
const fileNames: string[] = process.argv.slice(2);
fileNames.forEach(fileName => {
// Parse a file
let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
@@ -19,7 +19,7 @@ function printError(error: ts.Diagnostic): void {
console.log(`${error.file && error.file.fileName}: ${error.messageText}`);
}
export function createProgram(rootFiles: string[], compilerOptionsJson: string): ts.Program {
export function createProgram(rootFiles: string[], compilerOptionsJson: string): ts.Program | undefined {
const { config, error } = ts.parseConfigFileTextToJson("tsconfig.json", compilerOptionsJson)
if (error) {
printError(error);
@@ -8,7 +8,13 @@
declare var process: any;
declare var console: any;
declare var fs: any;
declare var fs: {
existsSync(path: string): boolean;
readdirSync(path: string): string[];
readFileSync(filename: string, encoding?: string): string;
writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;
watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: { mtime: Date }, prev: { mtime: Date }) => void): void;
};
declare var path: any;
import * as ts from "typescript";
@@ -12,3 +12,4 @@ var C = (function () {
return C;
}());
exports.C = C;
module.exports = B;
@@ -12,3 +12,4 @@ var C = (function () {
return C;
}());
exports.C = C;
module.exports = B;
@@ -55,7 +55,7 @@ function f2(x: Color | string | string[]) {
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>x : Color | string | string[]
>x : string[] | Color | string
>"number" : string
var z = x;
@@ -68,16 +68,16 @@ function f2(x: Color | string | string[]) {
}
else {
var w = x;
>w : string | string[]
>x : string | string[]
>w : string[] | string
>x : string[] | string
var w: string | string[];
>w : string | string[]
>w : string[] | string
}
if (typeof x === "string") {
>typeof x === "string" : boolean
>typeof x : string
>x : Color | string | string[]
>x : Color | string[] | string
>"string" : string
var a = x;
@@ -1,20 +1,14 @@
tests/cases/compiler/accessorParameterAccessibilityModifier.ts(3,9): error TS2369: A parameter property is only allowed in a constructor implementation.
tests/cases/compiler/accessorParameterAccessibilityModifier.ts(3,11): error TS2369: A parameter property is only allowed in a constructor implementation.
tests/cases/compiler/accessorParameterAccessibilityModifier.ts(4,16): error TS2369: A parameter property is only allowed in a constructor implementation.
tests/cases/compiler/accessorParameterAccessibilityModifier.ts(4,18): error TS2369: A parameter property is only allowed in a constructor implementation.
==== tests/cases/compiler/accessorParameterAccessibilityModifier.ts (4 errors) ====
==== tests/cases/compiler/accessorParameterAccessibilityModifier.ts (2 errors) ====
class C {
set X(public v) { }
~
!!! error TS2369: A parameter property is only allowed in a constructor implementation.
~~~~~~~~
!!! error TS2369: A parameter property is only allowed in a constructor implementation.
static set X(public v2) { }
~
!!! error TS2369: A parameter property is only allowed in a constructor implementation.
~~~~~~~~~
!!! error TS2369: A parameter property is only allowed in a constructor implementation.
}
+3
View File
@@ -55,9 +55,12 @@ var foo;
var provide = foo;
var booz = foo.bar.baz;
var beez = foo.bar;
var m = no;
var m2 = no.mod;
5;
"s";
null;
var r = undefined;
var p = new provide.Provide();
function use() {
beez.baz.boo;
@@ -0,0 +1,8 @@
//// [ambientNameRestrictions.ts]
export declare namespace Foo {
export var static: any;
}
//// [ambientNameRestrictions.js]
"use strict";
@@ -0,0 +1,8 @@
=== tests/cases/compiler/ambientNameRestrictions.ts ===
export declare namespace Foo {
>Foo : Symbol(Foo, Decl(ambientNameRestrictions.ts, 0, 0))
export var static: any;
>static : Symbol(static, Decl(ambientNameRestrictions.ts, 1, 12))
}
@@ -0,0 +1,8 @@
=== tests/cases/compiler/ambientNameRestrictions.ts ===
export declare namespace Foo {
>Foo : typeof Foo
export var static: any;
>static : any
}
@@ -9,9 +9,9 @@ function doubleAndReturnAsArray(x: number, y: number, z: number): [number, numbe
let blah = arguments[Symbol.iterator];
>blah : Symbol(blah, Decl(argumentsObjectIterator02_ES6.ts, 2, 7))
>arguments : Symbol(arguments)
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.iterable.d.ts, --, --))
>Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.iterable.d.ts, --, --))
let result = [];
>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7))
+16
View File
@@ -0,0 +1,16 @@
//// [arrayFilter.ts]
var foo = [
{ name: 'bar' },
{ name: null },
{ name: 'baz' }
]
foo.filter(x => x.name); //should accepted all possible types not only boolean!
//// [arrayFilter.js]
var foo = [
{ name: 'bar' },
{ name: null },
{ name: 'baz' }
];
foo.filter(function (x) { return x.name; }); //should accepted all possible types not only boolean!
@@ -0,0 +1,24 @@
=== tests/cases/compiler/arrayFilter.ts ===
var foo = [
>foo : Symbol(foo, Decl(arrayFilter.ts, 0, 3))
{ name: 'bar' },
>name : Symbol(name, Decl(arrayFilter.ts, 1, 5))
{ name: null },
>name : Symbol(name, Decl(arrayFilter.ts, 2, 5))
{ name: 'baz' }
>name : Symbol(name, Decl(arrayFilter.ts, 3, 5))
]
foo.filter(x => x.name); //should accepted all possible types not only boolean!
>foo.filter : Symbol(Array.filter, Decl(lib.d.ts, --, --))
>foo : Symbol(foo, Decl(arrayFilter.ts, 0, 3))
>filter : Symbol(Array.filter, Decl(lib.d.ts, --, --))
>x : Symbol(x, Decl(arrayFilter.ts, 6, 11))
>x.name : Symbol(name, Decl(arrayFilter.ts, 1, 5))
>x : Symbol(x, Decl(arrayFilter.ts, 6, 11))
>name : Symbol(name, Decl(arrayFilter.ts, 1, 5))
@@ -0,0 +1,33 @@
=== tests/cases/compiler/arrayFilter.ts ===
var foo = [
>foo : { name: string; }[]
>[ { name: 'bar' }, { name: null }, { name: 'baz' }] : { name: string; }[]
{ name: 'bar' },
>{ name: 'bar' } : { name: string; }
>name : string
>'bar' : string
{ name: null },
>{ name: null } : { name: null; }
>name : null
>null : null
{ name: 'baz' }
>{ name: 'baz' } : { name: string; }
>name : string
>'baz' : string
]
foo.filter(x => x.name); //should accepted all possible types not only boolean!
>foo.filter(x => x.name) : { name: string; }[]
>foo.filter : (callbackfn: (value: { name: string; }, index: number, array: { name: string; }[]) => any, thisArg?: any) => { name: string; }[]
>foo : { name: string; }[]
>filter : (callbackfn: (value: { name: string; }, index: number, array: { name: string; }[]) => any, thisArg?: any) => { name: string; }[]
>x => x.name : (x: { name: string; }) => string
>x : { name: string; }
>x.name : string
>x : { name: string; }
>name : string
@@ -79,7 +79,7 @@ interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43))
>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --))
>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --))
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES6.ts, 44, 3))
@@ -0,0 +1,6 @@
//// [arrowFunctionWithParameterNameAsync.ts]
const x = async => async;
//// [arrowFunctionWithParameterNameAsync.js]
var x = function (async) { return async; };
@@ -0,0 +1,7 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/arrowFunctionWithParameterNameAsync.ts ===
const x = async => async;
>x : Symbol(x, Decl(arrowFunctionWithParameterNameAsync.ts, 1, 5))
>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync.ts, 1, 9))
>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync.ts, 1, 9))
@@ -0,0 +1,8 @@
=== tests/cases/conformance/async/es6/asyncArrowFunction/arrowFunctionWithParameterNameAsync.ts ===
const x = async => async;
>x : (async: any) => any
>async => async : (async: any) => any
>async : any
>async : any
@@ -5,7 +5,7 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(8,5): error TS2322: Type '
Property 'apply' is missing in type '{}'.
tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type 'typeof bad' is not assignable to type 'Function'.
Types of property 'apply' are incompatible.
Type 'number' is not assignable to type '{ <T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U; (this: Function, thisArg: any, argArray?: any): any; }'.
Type 'number' is not assignable to type '(this: Function, thisArg: any, argArray?: any) => any'.
==== tests/cases/compiler/assignmentToObjectAndFunction.ts (3 errors) ====
@@ -48,4 +48,4 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type
~~~~~~~~~~
!!! error TS2322: Type 'typeof bad' is not assignable to type 'Function'.
!!! error TS2322: Types of property 'apply' are incompatible.
!!! error TS2322: Type 'number' is not assignable to type '{ <T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U; (this: Function, thisArg: any, argArray?: any): any; }'.
!!! error TS2322: Type 'number' is not assignable to type '(this: Function, thisArg: any, argArray?: any) => any'.
@@ -0,0 +1,53 @@
//// [assignmentTypeNarrowing.ts]
let x: string | number | boolean | RegExp;
x = "";
x; // string
[x] = [true];
x; // boolean
[x = ""] = [1];
x; // string | number
({x} = {x: true});
x; // boolean
({y: x} = {y: 1});
x; // number
({x = ""} = {x: true});
x; // string | boolean
({y: x = /a/} = {y: 1});
x; // number | RegExp
let a: string[];
for (x of a) {
x; // string
}
//// [assignmentTypeNarrowing.js]
var x;
x = "";
x; // string
x = [true][0];
x; // boolean
_a = [1][0], x = _a === void 0 ? "" : _a;
x; // string | number
(_b = { x: true }, x = _b.x, _b);
x; // boolean
(_c = { y: 1 }, x = _c.y, _c);
x; // number
(_d = { x: true }, _e = _d.x, x = _e === void 0 ? "" : _e, _d);
x; // string | boolean
(_f = { y: 1 }, _g = _f.y, x = _g === void 0 ? /a/ : _g, _f);
x; // number | RegExp
var a;
for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
x = a_1[_i];
x; // string
}
var _a, _b, _c, _d, _e, _f, _g;
Loaded 100 of 968 files, more files were not shown because too many files have changed in this diff. Show more