Merged branch 'master' into noParentNodesInEmitter

This commit is contained in:
Ron Buckton
2015-08-31 12:35:22 -07:00
1269 changed files with 71851 additions and 49975 deletions
+17 -14
View File
@@ -17,7 +17,7 @@ var docDirectory = "doc/";
var builtDirectory = "built/";
var builtLocalDirectory = "built/local/";
var LKGDirectory = "bin/";
var LKGDirectory = "lib/";
var copyright = "CopyrightNotice.txt";
var thirdParty = "ThirdPartyNoticeText.txt";
@@ -141,7 +141,10 @@ var harnessSources = harnessCoreSources.concat([
"session.ts",
"versionCache.ts",
"convertToBase64.ts",
"transpile.ts"
"transpile.ts",
"reuseProgramStructure.ts",
"cachingInServerLSHost.ts",
"moduleResolution.ts"
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
@@ -155,10 +158,10 @@ var harnessSources = harnessCoreSources.concat([
var librarySourceMap = [
{ target: "lib.core.d.ts", sources: ["core.d.ts"] },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "extensions.d.ts", "intl.d.ts", "dom.generated.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "extensions.d.ts", "intl.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], },
{ target: "lib.d.ts", sources: ["core.d.ts", "extensions.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.d.ts", sources: ["core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.core.es6.d.ts", sources: ["core.d.ts", "es6.d.ts"]},
{ target: "lib.es6.d.ts", sources: ["core.d.ts", "es6.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
];
@@ -218,7 +221,7 @@ var compilerFilename = "tsc.js";
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) {
file(outFile, prereqs, function() {
var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory;
var options = "--module commonjs -noImplicitAny";
var options = "--module commonjs --noImplicitAny --noEmitOnError";
// Keep comments when specifically requested
// or when in debug mode.
@@ -339,10 +342,10 @@ file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson],
complete();
});
ex.run();
}, {async: true});
}, {async: true});
desc("Generates a diagnostic file in TypeScript based on an input JSON file");
task("generate-diagnostics", [diagnosticInfoMapTs]);
task("generate-diagnostics", [diagnosticInfoMapTs]);
// Publish nightly
@@ -479,11 +482,11 @@ file(specMd, [word2mdJs, specWord], function () {
child_process.exec(cmd, function () {
complete();
});
}, {async: true});
}, {async: true});
desc("Generates a Markdown version of the Language Specification");
task("generate-spec", [specMd]);
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
@@ -615,7 +618,7 @@ task("runtests", ["tests", builtLocalDirectory], function() {
exec(cmd, deleteTemporaryProjectOutput);
}, {async: true});
desc("Generates code coverage data via instanbul");
desc("Generates code coverage data via instanbul");
task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run;
console.log(cmd);
@@ -658,7 +661,7 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function(
function getDiffTool() {
var program = process.env['DIFF']
if (!program) {
fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
fail("Add the 'DIFF' environment variable to the path of the program you want to use.");
}
return program;
}
@@ -667,14 +670,14 @@ function getDiffTool() {
desc("Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff', function () {
var cmd = '"' + getDiffTool() + '" ' + refBaseline + ' ' + localBaseline;
console.log(cmd);
console.log(cmd);
exec(cmd);
}, {async: true});
desc("Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable");
task('diff-rwc', function () {
var cmd = '"' + getDiffTool() + '" ' + refRwcBaseline + ' ' + localRwcBaseline;
console.log(cmd);
console.log(cmd);
exec(cmd);
}, {async: true});
+14 -1
View File
@@ -6,8 +6,21 @@
[![Join the chat at https://gitter.im/Microsoft/TypeScript](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [twitter account](https://twitter.com/typescriptlang).
[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [Twitter account](https://twitter.com/typescriptlang).
## Installing
For the latest stable version:
```
npm install -g typescript
```
For our nightly builds:
```
npm install -g typescript@next
```
## Contribute
-1199
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,2 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')
require('../lib/tsc.js')
Regular → Executable
+1 -1
View File
@@ -1,2 +1,2 @@
#!/usr/bin/env node
require('./tsserver.js')
require('../lib/tsserver.js')
Binary file not shown.
Binary file not shown.
+1720 -1192
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+426 -66
View File
@@ -331,31 +331,31 @@ interface String {
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A String object or string literal that represents the regular expression
* @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj.
* @param searchValue A string that represents the regular expression.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: string, replaceValue: string): string;
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A String object or string literal that represents the regular expression
* @param replaceValue A function that returns the replacement text.
* @param searchValue A string that represents the regular expression.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string;
replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags
* @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj.
* @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: RegExp, replaceValue: string): string;
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags
* @param replaceValue A function that returns the replacement text.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string;
replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
@@ -986,14 +986,14 @@ interface JSON {
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: (key: string, value: any) => any, space: any): string;
stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer Array that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: any[], space: any): string;
stringify(value: any, replacer: any[], space: string | number): string;
}
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
@@ -1196,11 +1196,13 @@ interface PromiseLike<T> {
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
}
interface ArrayLike<T> {
length: number;
[n: number]: T;
}
/////////////////////////////
/// IE10 ECMAScript Extensions
/////////////////////////////
/**
* Represents a raw buffer of binary data, which is used to store data for the
@@ -1253,14 +1255,14 @@ interface DataView {
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat32(byteOffset: number, littleEndian: boolean): number;
getFloat32(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Float64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat64(byteOffset: number, littleEndian: boolean): number;
getFloat64(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Int8 value at the specified byte offset from the start of the view. There is
@@ -1274,13 +1276,13 @@ interface DataView {
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt16(byteOffset: number, littleEndian: boolean): number;
getInt16(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Int32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt32(byteOffset: number, littleEndian: boolean): number;
getInt32(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Uint8 value at the specified byte offset from the start of the view. There is
@@ -1294,14 +1296,14 @@ interface DataView {
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint16(byteOffset: number, littleEndian: boolean): number;
getUint16(byteOffset: number, littleEndian?: boolean): number;
/**
* Gets the Uint32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint32(byteOffset: number, littleEndian: boolean): number;
getUint32(byteOffset: number, littleEndian?: boolean): number;
/**
* Stores an Float32 value at the specified byte offset from the start of the view.
@@ -1310,7 +1312,7 @@ interface DataView {
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat32(byteOffset: number, value: number, littleEndian: boolean): void;
setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Float64 value at the specified byte offset from the start of the view.
@@ -1319,7 +1321,7 @@ interface DataView {
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat64(byteOffset: number, value: number, littleEndian: boolean): void;
setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Int8 value at the specified byte offset from the start of the view.
@@ -1335,7 +1337,7 @@ interface DataView {
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt16(byteOffset: number, value: number, littleEndian: boolean): void;
setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Int32 value at the specified byte offset from the start of the view.
@@ -1344,7 +1346,7 @@ interface DataView {
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt32(byteOffset: number, value: number, littleEndian: boolean): void;
setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Uint8 value at the specified byte offset from the start of the view.
@@ -1360,7 +1362,7 @@ interface DataView {
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint16(byteOffset: number, value: number, littleEndian: boolean): void;
setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;
/**
* Stores an Uint32 value at the specified byte offset from the start of the view.
@@ -1369,7 +1371,7 @@ interface DataView {
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint32(byteOffset: number, value: number, littleEndian: boolean): void;
setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;
}
interface DataViewConstructor {
@@ -1576,7 +1578,7 @@ interface Int8Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int8Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -1625,8 +1627,7 @@ interface Int8Array {
interface Int8ArrayConstructor {
prototype: Int8Array;
new (length: number): Int8Array;
new (array: Int8Array): Int8Array;
new (array: number[]): Int8Array;
new (array: ArrayLike<number>): Int8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array;
/**
@@ -1639,6 +1640,15 @@ interface Int8ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
declare var Int8Array: Int8ArrayConstructor;
@@ -1841,7 +1851,7 @@ interface Uint8Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint8Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -1891,8 +1901,7 @@ interface Uint8Array {
interface Uint8ArrayConstructor {
prototype: Uint8Array;
new (length: number): Uint8Array;
new (array: Uint8Array): Uint8Array;
new (array: number[]): Uint8Array;
new (array: ArrayLike<number>): Uint8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array;
/**
@@ -1905,9 +1914,291 @@ interface Uint8ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
declare var Uint8Array: Uint8ArrayConstructor;
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* The size in bytes of each element in the array.
*/
BYTES_PER_ELEMENT: number;
/**
* The ArrayBuffer instance referenced by the array.
*/
buffer: ArrayBuffer;
/**
* The length in bytes of the array.
*/
byteLength: number;
/**
* The offset in bytes of the array.
*/
byteOffset: number;
/**
* 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
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): Uint8ClampedArray;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in array1 until the callbackfn returns false,
* or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;
/**
* 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
* length+end.
*/
fill(value: number, start?: number, end?: number): Uint8ClampedArray;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): Uint8ClampedArray;
/**
* 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
* 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
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
/**
* 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
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: number, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: number, fromIndex?: number): number;
/**
* The length of the array.
*/
length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue?: number): number;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;
/**
* Reverses the elements in an Array.
*/
reverse(): Uint8ClampedArray;
/**
* Sets a value or an array of values.
* @param index The index of the location to set.
* @param value The value to set.
*/
set(index: number, value: number): void;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint8ClampedArray, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array.
*/
slice(start?: number, end?: number): Uint8ClampedArray;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls the
* callbackfn function for each element in array1 until the callbackfn returns true, or until
* the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;
/**
* Sorts an array.
* @param compareFn The name of the function used to determine the order of the elements. If
* omitted, the elements are sorted in ascending, ASCII character order.
*/
sort(compareFn?: (a: number, b: number) => number): Uint8ClampedArray;
/**
* Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin: number, end?: number): Uint8ClampedArray;
/**
* Converts a number to a string by using the current locale.
*/
toLocaleString(): string;
/**
* Returns a string representation of an array.
*/
toString(): string;
[index: number]: number;
}
interface Uint8ClampedArrayConstructor {
prototype: Uint8ClampedArray;
new (length: number): Uint8ClampedArray;
new (array: ArrayLike<number>): Uint8ClampedArray;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray;
/**
* The size in bytes of each element in the array.
*/
BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
declare var Uint8ClampedArray: Uint8ClampedArrayConstructor;
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
@@ -2107,7 +2398,7 @@ interface Int16Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int16Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -2157,8 +2448,7 @@ interface Int16Array {
interface Int16ArrayConstructor {
prototype: Int16Array;
new (length: number): Int16Array;
new (array: Int16Array): Int16Array;
new (array: number[]): Int16Array;
new (array: ArrayLike<number>): Int16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array;
/**
@@ -2171,6 +2461,15 @@ interface Int16ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
declare var Int16Array: Int16ArrayConstructor;
@@ -2373,7 +2672,7 @@ interface Uint16Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint16Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -2423,8 +2722,7 @@ interface Uint16Array {
interface Uint16ArrayConstructor {
prototype: Uint16Array;
new (length: number): Uint16Array;
new (array: Uint16Array): Uint16Array;
new (array: number[]): Uint16Array;
new (array: ArrayLike<number>): Uint16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array;
/**
@@ -2437,6 +2735,15 @@ interface Uint16ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
declare var Uint16Array: Uint16ArrayConstructor;
/**
@@ -2638,7 +2945,7 @@ interface Int32Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int32Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -2688,8 +2995,7 @@ interface Int32Array {
interface Int32ArrayConstructor {
prototype: Int32Array;
new (length: number): Int32Array;
new (array: Int32Array): Int32Array;
new (array: number[]): Int32Array;
new (array: ArrayLike<number>): Int32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array;
/**
@@ -2702,6 +3008,14 @@ interface Int32ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
declare var Int32Array: Int32ArrayConstructor;
@@ -2904,7 +3218,7 @@ interface Uint32Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint32Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -2954,8 +3268,7 @@ interface Uint32Array {
interface Uint32ArrayConstructor {
prototype: Uint32Array;
new (length: number): Uint32Array;
new (array: Uint32Array): Uint32Array;
new (array: number[]): Uint32Array;
new (array: ArrayLike<number>): Uint32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array;
/**
@@ -2968,6 +3281,14 @@ interface Uint32ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
declare var Uint32Array: Uint32ArrayConstructor;
@@ -3170,7 +3491,7 @@ interface Float32Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float32Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -3220,8 +3541,7 @@ interface Float32Array {
interface Float32ArrayConstructor {
prototype: Float32Array;
new (length: number): Float32Array;
new (array: Float32Array): Float32Array;
new (array: number[]): Float32Array;
new (array: ArrayLike<number>): Float32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array;
/**
@@ -3234,6 +3554,15 @@ interface Float32ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
declare var Float32Array: Float32ArrayConstructor;
@@ -3436,7 +3765,7 @@ interface Float64Array {
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float64Array, offset?: number): void;
set(array: ArrayLike<number>, offset?: number): void;
/**
* Returns a section of an array.
@@ -3486,8 +3815,7 @@ interface Float64Array {
interface Float64ArrayConstructor {
prototype: Float64Array;
new (length: number): Float64Array;
new (array: Float64Array): Float64Array;
new (array: number[]): Float64Array;
new (array: ArrayLike<number>): Float64Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array;
/**
@@ -3500,8 +3828,17 @@ interface Float64ArrayConstructor {
* @param items A set of elements to include in the new array object.
*/
of(...items: number[]): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
declare var Float64Array: Float64ArrayConstructor;/////////////////////////////
declare var Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
@@ -6135,7 +6472,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported.
* @param replace Specifies whether the existing entry for the document is replaced in the history list.
*/
open(url?: string, name?: string, features?: string, replace?: boolean): Document | Window;
open(url?: string, name?: string, features?: string, replace?: boolean): Document;
/**
* Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.
* @param commandId Specifies a command identifier.
@@ -6592,6 +6929,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
webkitMatchesSelector(selectors: string): boolean;
webkitRequestFullScreen(): void;
webkitRequestFullscreen(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -6706,7 +7044,7 @@ interface File extends Blob {
declare var File: {
prototype: File;
new(): File;
new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;
}
interface FileList {
@@ -7579,7 +7917,6 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@@ -10541,7 +10878,7 @@ interface IDBDatabase extends EventTarget {
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -10662,7 +10999,7 @@ interface IDBTransaction extends EventTarget {
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -10692,11 +11029,14 @@ interface ImageData {
width: number;
}
declare var ImageData: {
interface ImageDataConstructor {
prototype: ImageData;
new(): ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
}
declare var ImageData: ImageDataConstructor;
interface KeyboardEvent extends UIEvent {
altKey: boolean;
char: string;
@@ -11379,7 +11719,7 @@ interface MessageEvent extends Event {
declare var MessageEvent: {
prototype: MessageEvent;
new(): MessageEvent;
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
interface MessagePort extends EventTarget {
@@ -12121,7 +12461,7 @@ interface ProgressEvent extends Event {
declare var ProgressEvent: {
prototype: ProgressEvent;
new(): ProgressEvent;
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
interface Range {
@@ -15638,7 +15978,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
onvolumechange: (ev: Event) => any;
onwaiting: (ev: Event) => any;
opener: Window;
orientation: string;
orientation: string | number;
outerHeight: number;
outerWidth: number;
pageXOffset: number;
@@ -15845,7 +16185,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
LOADING: number;
OPENED: number;
UNSENT: number;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -16115,7 +16455,7 @@ interface MSBaseReader {
DONE: number;
EMPTY: number;
LOADING: number;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -16271,7 +16611,7 @@ interface XMLHttpRequestEventTarget {
onloadstart: (ev: Event) => any;
onprogress: (ev: ProgressEvent) => any;
ontimeout: (ev: ProgressEvent) => any;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -16293,12 +16633,32 @@ interface BlobPropertyBag {
endings?: string;
}
interface FilePropertyBag {
type?: string;
lastModified?: number;
}
interface EventListenerObject {
handleEvent(evt: Event): void;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface MessageEventInit extends EventInit {
data?: any;
origin?: string;
lastEventId?: string;
channel?: string;
source?: any;
ports?: MessagePort[];
}
interface ProgressEventInit extends EventInit {
lengthComputable?: boolean;
loaded?: number;
total?: number;
}
interface ErrorEventHandler {
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
@@ -16453,7 +16813,7 @@ declare var onunload: (ev: Event) => any;
declare var onvolumechange: (ev: Event) => any;
declare var onwaiting: (ev: Event) => any;
declare var opener: Window;
declare var orientation: string;
declare var orientation: string | number;
declare var outerHeight: number;
declare var outerWidth: number;
declare var pageXOffset: number;
+37 -2318
View File
File diff suppressed because it is too large Load Diff
+2839 -2562
View File
File diff suppressed because it is too large Load Diff
+1174
View File
File diff suppressed because it is too large Load Diff
+5257 -4097
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+352 -300
View File
@@ -23,6 +23,7 @@ declare module "typescript" {
contains(fileName: string): boolean;
remove(fileName: string): void;
forEachValue(f: (v: T) => void): void;
clear(): void;
}
interface TextRange {
pos: number;
@@ -35,293 +36,294 @@ declare module "typescript" {
MultiLineCommentTrivia = 3,
NewLineTrivia = 4,
WhitespaceTrivia = 5,
ConflictMarkerTrivia = 6,
NumericLiteral = 7,
StringLiteral = 8,
RegularExpressionLiteral = 9,
NoSubstitutionTemplateLiteral = 10,
TemplateHead = 11,
TemplateMiddle = 12,
TemplateTail = 13,
OpenBraceToken = 14,
CloseBraceToken = 15,
OpenParenToken = 16,
CloseParenToken = 17,
OpenBracketToken = 18,
CloseBracketToken = 19,
DotToken = 20,
DotDotDotToken = 21,
SemicolonToken = 22,
CommaToken = 23,
LessThanToken = 24,
LessThanSlashToken = 25,
GreaterThanToken = 26,
LessThanEqualsToken = 27,
GreaterThanEqualsToken = 28,
EqualsEqualsToken = 29,
ExclamationEqualsToken = 30,
EqualsEqualsEqualsToken = 31,
ExclamationEqualsEqualsToken = 32,
EqualsGreaterThanToken = 33,
PlusToken = 34,
MinusToken = 35,
AsteriskToken = 36,
SlashToken = 37,
PercentToken = 38,
PlusPlusToken = 39,
MinusMinusToken = 40,
LessThanLessThanToken = 41,
GreaterThanGreaterThanToken = 42,
GreaterThanGreaterThanGreaterThanToken = 43,
AmpersandToken = 44,
BarToken = 45,
CaretToken = 46,
ExclamationToken = 47,
TildeToken = 48,
AmpersandAmpersandToken = 49,
BarBarToken = 50,
QuestionToken = 51,
ColonToken = 52,
AtToken = 53,
EqualsToken = 54,
PlusEqualsToken = 55,
MinusEqualsToken = 56,
AsteriskEqualsToken = 57,
SlashEqualsToken = 58,
PercentEqualsToken = 59,
LessThanLessThanEqualsToken = 60,
GreaterThanGreaterThanEqualsToken = 61,
GreaterThanGreaterThanGreaterThanEqualsToken = 62,
AmpersandEqualsToken = 63,
BarEqualsToken = 64,
CaretEqualsToken = 65,
Identifier = 66,
BreakKeyword = 67,
CaseKeyword = 68,
CatchKeyword = 69,
ClassKeyword = 70,
ConstKeyword = 71,
ContinueKeyword = 72,
DebuggerKeyword = 73,
DefaultKeyword = 74,
DeleteKeyword = 75,
DoKeyword = 76,
ElseKeyword = 77,
EnumKeyword = 78,
ExportKeyword = 79,
ExtendsKeyword = 80,
FalseKeyword = 81,
FinallyKeyword = 82,
ForKeyword = 83,
FunctionKeyword = 84,
IfKeyword = 85,
ImportKeyword = 86,
InKeyword = 87,
InstanceOfKeyword = 88,
NewKeyword = 89,
NullKeyword = 90,
ReturnKeyword = 91,
SuperKeyword = 92,
SwitchKeyword = 93,
ThisKeyword = 94,
ThrowKeyword = 95,
TrueKeyword = 96,
TryKeyword = 97,
TypeOfKeyword = 98,
VarKeyword = 99,
VoidKeyword = 100,
WhileKeyword = 101,
WithKeyword = 102,
ImplementsKeyword = 103,
InterfaceKeyword = 104,
LetKeyword = 105,
PackageKeyword = 106,
PrivateKeyword = 107,
ProtectedKeyword = 108,
PublicKeyword = 109,
StaticKeyword = 110,
YieldKeyword = 111,
AbstractKeyword = 112,
AsKeyword = 113,
AnyKeyword = 114,
AsyncKeyword = 115,
AwaitKeyword = 116,
BooleanKeyword = 117,
ConstructorKeyword = 118,
DeclareKeyword = 119,
GetKeyword = 120,
IsKeyword = 121,
ModuleKeyword = 122,
NamespaceKeyword = 123,
RequireKeyword = 124,
NumberKeyword = 125,
SetKeyword = 126,
StringKeyword = 127,
SymbolKeyword = 128,
TypeKeyword = 129,
FromKeyword = 130,
OfKeyword = 131,
QualifiedName = 132,
ComputedPropertyName = 133,
TypeParameter = 134,
Parameter = 135,
Decorator = 136,
PropertySignature = 137,
PropertyDeclaration = 138,
MethodSignature = 139,
MethodDeclaration = 140,
Constructor = 141,
GetAccessor = 142,
SetAccessor = 143,
CallSignature = 144,
ConstructSignature = 145,
IndexSignature = 146,
TypePredicate = 147,
TypeReference = 148,
FunctionType = 149,
ConstructorType = 150,
TypeQuery = 151,
TypeLiteral = 152,
ArrayType = 153,
TupleType = 154,
UnionType = 155,
IntersectionType = 156,
ParenthesizedType = 157,
ObjectBindingPattern = 158,
ArrayBindingPattern = 159,
BindingElement = 160,
ArrayLiteralExpression = 161,
ObjectLiteralExpression = 162,
PropertyAccessExpression = 163,
ElementAccessExpression = 164,
CallExpression = 165,
NewExpression = 166,
TaggedTemplateExpression = 167,
TypeAssertionExpression = 168,
ParenthesizedExpression = 169,
FunctionExpression = 170,
ArrowFunction = 171,
DeleteExpression = 172,
TypeOfExpression = 173,
VoidExpression = 174,
AwaitExpression = 175,
PrefixUnaryExpression = 176,
PostfixUnaryExpression = 177,
BinaryExpression = 178,
ConditionalExpression = 179,
TemplateExpression = 180,
YieldExpression = 181,
SpreadElementExpression = 182,
ClassExpression = 183,
OmittedExpression = 184,
ExpressionWithTypeArguments = 185,
AsExpression = 186,
TemplateSpan = 187,
SemicolonClassElement = 188,
Block = 189,
VariableStatement = 190,
EmptyStatement = 191,
ExpressionStatement = 192,
IfStatement = 193,
DoStatement = 194,
WhileStatement = 195,
ForStatement = 196,
ForInStatement = 197,
ForOfStatement = 198,
ContinueStatement = 199,
BreakStatement = 200,
ReturnStatement = 201,
WithStatement = 202,
SwitchStatement = 203,
LabeledStatement = 204,
ThrowStatement = 205,
TryStatement = 206,
DebuggerStatement = 207,
VariableDeclaration = 208,
VariableDeclarationList = 209,
FunctionDeclaration = 210,
ClassDeclaration = 211,
InterfaceDeclaration = 212,
TypeAliasDeclaration = 213,
EnumDeclaration = 214,
ModuleDeclaration = 215,
ModuleBlock = 216,
CaseBlock = 217,
ImportEqualsDeclaration = 218,
ImportDeclaration = 219,
ImportClause = 220,
NamespaceImport = 221,
NamedImports = 222,
ImportSpecifier = 223,
ExportAssignment = 224,
ExportDeclaration = 225,
NamedExports = 226,
ExportSpecifier = 227,
MissingDeclaration = 228,
ExternalModuleReference = 229,
JsxElement = 230,
JsxSelfClosingElement = 231,
JsxOpeningElement = 232,
JsxText = 233,
JsxClosingElement = 234,
JsxAttribute = 235,
JsxSpreadAttribute = 236,
JsxExpression = 237,
CaseClause = 238,
DefaultClause = 239,
HeritageClause = 240,
CatchClause = 241,
PropertyAssignment = 242,
ShorthandPropertyAssignment = 243,
EnumMember = 244,
SourceFile = 245,
JSDocTypeExpression = 246,
JSDocAllType = 247,
JSDocUnknownType = 248,
JSDocArrayType = 249,
JSDocUnionType = 250,
JSDocTupleType = 251,
JSDocNullableType = 252,
JSDocNonNullableType = 253,
JSDocRecordType = 254,
JSDocRecordMember = 255,
JSDocTypeReference = 256,
JSDocOptionalType = 257,
JSDocFunctionType = 258,
JSDocVariadicType = 259,
JSDocConstructorType = 260,
JSDocThisType = 261,
JSDocComment = 262,
JSDocTag = 263,
JSDocParameterTag = 264,
JSDocReturnTag = 265,
JSDocTypeTag = 266,
JSDocTemplateTag = 267,
SyntaxList = 268,
Count = 269,
FirstAssignment = 54,
LastAssignment = 65,
FirstReservedWord = 67,
LastReservedWord = 102,
FirstKeyword = 67,
LastKeyword = 131,
FirstFutureReservedWord = 103,
LastFutureReservedWord = 111,
FirstTypeNode = 148,
LastTypeNode = 157,
FirstPunctuation = 14,
LastPunctuation = 65,
ShebangTrivia = 6,
ConflictMarkerTrivia = 7,
NumericLiteral = 8,
StringLiteral = 9,
RegularExpressionLiteral = 10,
NoSubstitutionTemplateLiteral = 11,
TemplateHead = 12,
TemplateMiddle = 13,
TemplateTail = 14,
OpenBraceToken = 15,
CloseBraceToken = 16,
OpenParenToken = 17,
CloseParenToken = 18,
OpenBracketToken = 19,
CloseBracketToken = 20,
DotToken = 21,
DotDotDotToken = 22,
SemicolonToken = 23,
CommaToken = 24,
LessThanToken = 25,
LessThanSlashToken = 26,
GreaterThanToken = 27,
LessThanEqualsToken = 28,
GreaterThanEqualsToken = 29,
EqualsEqualsToken = 30,
ExclamationEqualsToken = 31,
EqualsEqualsEqualsToken = 32,
ExclamationEqualsEqualsToken = 33,
EqualsGreaterThanToken = 34,
PlusToken = 35,
MinusToken = 36,
AsteriskToken = 37,
SlashToken = 38,
PercentToken = 39,
PlusPlusToken = 40,
MinusMinusToken = 41,
LessThanLessThanToken = 42,
GreaterThanGreaterThanToken = 43,
GreaterThanGreaterThanGreaterThanToken = 44,
AmpersandToken = 45,
BarToken = 46,
CaretToken = 47,
ExclamationToken = 48,
TildeToken = 49,
AmpersandAmpersandToken = 50,
BarBarToken = 51,
QuestionToken = 52,
ColonToken = 53,
AtToken = 54,
EqualsToken = 55,
PlusEqualsToken = 56,
MinusEqualsToken = 57,
AsteriskEqualsToken = 58,
SlashEqualsToken = 59,
PercentEqualsToken = 60,
LessThanLessThanEqualsToken = 61,
GreaterThanGreaterThanEqualsToken = 62,
GreaterThanGreaterThanGreaterThanEqualsToken = 63,
AmpersandEqualsToken = 64,
BarEqualsToken = 65,
CaretEqualsToken = 66,
Identifier = 67,
BreakKeyword = 68,
CaseKeyword = 69,
CatchKeyword = 70,
ClassKeyword = 71,
ConstKeyword = 72,
ContinueKeyword = 73,
DebuggerKeyword = 74,
DefaultKeyword = 75,
DeleteKeyword = 76,
DoKeyword = 77,
ElseKeyword = 78,
EnumKeyword = 79,
ExportKeyword = 80,
ExtendsKeyword = 81,
FalseKeyword = 82,
FinallyKeyword = 83,
ForKeyword = 84,
FunctionKeyword = 85,
IfKeyword = 86,
ImportKeyword = 87,
InKeyword = 88,
InstanceOfKeyword = 89,
NewKeyword = 90,
NullKeyword = 91,
ReturnKeyword = 92,
SuperKeyword = 93,
SwitchKeyword = 94,
ThisKeyword = 95,
ThrowKeyword = 96,
TrueKeyword = 97,
TryKeyword = 98,
TypeOfKeyword = 99,
VarKeyword = 100,
VoidKeyword = 101,
WhileKeyword = 102,
WithKeyword = 103,
ImplementsKeyword = 104,
InterfaceKeyword = 105,
LetKeyword = 106,
PackageKeyword = 107,
PrivateKeyword = 108,
ProtectedKeyword = 109,
PublicKeyword = 110,
StaticKeyword = 111,
YieldKeyword = 112,
AbstractKeyword = 113,
AsKeyword = 114,
AnyKeyword = 115,
AsyncKeyword = 116,
AwaitKeyword = 117,
BooleanKeyword = 118,
ConstructorKeyword = 119,
DeclareKeyword = 120,
GetKeyword = 121,
IsKeyword = 122,
ModuleKeyword = 123,
NamespaceKeyword = 124,
RequireKeyword = 125,
NumberKeyword = 126,
SetKeyword = 127,
StringKeyword = 128,
SymbolKeyword = 129,
TypeKeyword = 130,
FromKeyword = 131,
OfKeyword = 132,
QualifiedName = 133,
ComputedPropertyName = 134,
TypeParameter = 135,
Parameter = 136,
Decorator = 137,
PropertySignature = 138,
PropertyDeclaration = 139,
MethodSignature = 140,
MethodDeclaration = 141,
Constructor = 142,
GetAccessor = 143,
SetAccessor = 144,
CallSignature = 145,
ConstructSignature = 146,
IndexSignature = 147,
TypePredicate = 148,
TypeReference = 149,
FunctionType = 150,
ConstructorType = 151,
TypeQuery = 152,
TypeLiteral = 153,
ArrayType = 154,
TupleType = 155,
UnionType = 156,
IntersectionType = 157,
ParenthesizedType = 158,
ObjectBindingPattern = 159,
ArrayBindingPattern = 160,
BindingElement = 161,
ArrayLiteralExpression = 162,
ObjectLiteralExpression = 163,
PropertyAccessExpression = 164,
ElementAccessExpression = 165,
CallExpression = 166,
NewExpression = 167,
TaggedTemplateExpression = 168,
TypeAssertionExpression = 169,
ParenthesizedExpression = 170,
FunctionExpression = 171,
ArrowFunction = 172,
DeleteExpression = 173,
TypeOfExpression = 174,
VoidExpression = 175,
AwaitExpression = 176,
PrefixUnaryExpression = 177,
PostfixUnaryExpression = 178,
BinaryExpression = 179,
ConditionalExpression = 180,
TemplateExpression = 181,
YieldExpression = 182,
SpreadElementExpression = 183,
ClassExpression = 184,
OmittedExpression = 185,
ExpressionWithTypeArguments = 186,
AsExpression = 187,
TemplateSpan = 188,
SemicolonClassElement = 189,
Block = 190,
VariableStatement = 191,
EmptyStatement = 192,
ExpressionStatement = 193,
IfStatement = 194,
DoStatement = 195,
WhileStatement = 196,
ForStatement = 197,
ForInStatement = 198,
ForOfStatement = 199,
ContinueStatement = 200,
BreakStatement = 201,
ReturnStatement = 202,
WithStatement = 203,
SwitchStatement = 204,
LabeledStatement = 205,
ThrowStatement = 206,
TryStatement = 207,
DebuggerStatement = 208,
VariableDeclaration = 209,
VariableDeclarationList = 210,
FunctionDeclaration = 211,
ClassDeclaration = 212,
InterfaceDeclaration = 213,
TypeAliasDeclaration = 214,
EnumDeclaration = 215,
ModuleDeclaration = 216,
ModuleBlock = 217,
CaseBlock = 218,
ImportEqualsDeclaration = 219,
ImportDeclaration = 220,
ImportClause = 221,
NamespaceImport = 222,
NamedImports = 223,
ImportSpecifier = 224,
ExportAssignment = 225,
ExportDeclaration = 226,
NamedExports = 227,
ExportSpecifier = 228,
MissingDeclaration = 229,
ExternalModuleReference = 230,
JsxElement = 231,
JsxSelfClosingElement = 232,
JsxOpeningElement = 233,
JsxText = 234,
JsxClosingElement = 235,
JsxAttribute = 236,
JsxSpreadAttribute = 237,
JsxExpression = 238,
CaseClause = 239,
DefaultClause = 240,
HeritageClause = 241,
CatchClause = 242,
PropertyAssignment = 243,
ShorthandPropertyAssignment = 244,
EnumMember = 245,
SourceFile = 246,
JSDocTypeExpression = 247,
JSDocAllType = 248,
JSDocUnknownType = 249,
JSDocArrayType = 250,
JSDocUnionType = 251,
JSDocTupleType = 252,
JSDocNullableType = 253,
JSDocNonNullableType = 254,
JSDocRecordType = 255,
JSDocRecordMember = 256,
JSDocTypeReference = 257,
JSDocOptionalType = 258,
JSDocFunctionType = 259,
JSDocVariadicType = 260,
JSDocConstructorType = 261,
JSDocThisType = 262,
JSDocComment = 263,
JSDocTag = 264,
JSDocParameterTag = 265,
JSDocReturnTag = 266,
JSDocTypeTag = 267,
JSDocTemplateTag = 268,
SyntaxList = 269,
Count = 270,
FirstAssignment = 55,
LastAssignment = 66,
FirstReservedWord = 68,
LastReservedWord = 103,
FirstKeyword = 68,
LastKeyword = 132,
FirstFutureReservedWord = 104,
LastFutureReservedWord = 112,
FirstTypeNode = 149,
LastTypeNode = 158,
FirstPunctuation = 15,
LastPunctuation = 66,
FirstToken = 0,
LastToken = 131,
LastToken = 132,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
LastLiteralToken = 10,
FirstTemplateToken = 10,
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 65,
FirstNode = 132,
LastTriviaToken = 7,
FirstLiteralToken = 8,
LastLiteralToken = 11,
FirstTemplateToken = 11,
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 66,
FirstNode = 133,
}
const enum NodeFlags {
Export = 1,
@@ -452,9 +454,9 @@ declare module "typescript" {
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
* Examples:
* FunctionDeclaration
* MethodDeclaration
* AccessorDeclaration
* - FunctionDeclaration
* - MethodDeclaration
* - AccessorDeclaration
*/
interface FunctionLikeDeclaration extends SignatureDeclaration {
_functionLikeDeclarationBrand: any;
@@ -944,7 +946,7 @@ declare module "typescript" {
getSourceFile(fileName: string): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
interface ParseConfigHost extends ModuleResolutionHost {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
@@ -958,6 +960,10 @@ declare module "typescript" {
throwIfCancellationRequested(): void;
}
interface Program extends ScriptReferenceHost {
/**
* Get a list of root file names that were passed to a 'createProgram'
*/
getRootFileNames(): string[];
/**
* Get a list of files in the program
*/
@@ -1019,11 +1025,6 @@ declare module "typescript" {
emitSkipped: boolean;
diagnostics: Diagnostic[];
}
interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
getSourceFiles(): SourceFile[];
getSourceFile(fileName: string): SourceFile;
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
@@ -1031,6 +1032,7 @@ declare module "typescript" {
getPropertyOfType(type: Type, propertyName: string): Symbol;
getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
@@ -1054,6 +1056,7 @@ declare module "typescript" {
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -1198,7 +1201,7 @@ declare module "typescript" {
Anonymous = 65536,
Instantiated = 131072,
ObjectLiteral = 524288,
ESSymbol = 4194304,
ESSymbol = 16777216,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
@@ -1218,8 +1221,6 @@ declare module "typescript" {
typeParameters: TypeParameter[];
outerTypeParameters: TypeParameter[];
localTypeParameters: TypeParameter[];
resolvedBaseConstructorType?: Type;
resolvedBaseTypes: ObjectType[];
}
interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
declaredProperties: Symbol[];
@@ -1292,6 +1293,10 @@ declare module "typescript" {
Error = 1,
Message = 2,
}
const enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2,
}
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
@@ -1299,6 +1304,7 @@ declare module "typescript" {
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
@@ -1315,6 +1321,7 @@ declare module "typescript" {
noLib?: boolean;
noResolve?: boolean;
out?: string;
outFile?: string;
outDir?: string;
preserveConstEnums?: boolean;
project?: string;
@@ -1330,6 +1337,7 @@ declare module "typescript" {
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
moduleResolution?: ModuleResolutionKind;
[option: string]: string | number | boolean;
}
const enum ModuleKind {
@@ -1367,14 +1375,25 @@ declare module "typescript" {
fileNames: string[];
errors: Diagnostic[];
}
interface CompilerHost {
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string;
}
interface ResolvedModule {
resolvedFileName: string;
failedLookupLocations: string[];
}
type ModuleNameResolver = (moduleName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => ResolvedModule;
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
}
interface TextSpan {
start: number;
@@ -1448,8 +1467,11 @@ declare module "typescript" {
function couldStartTrivia(text: string, pos: number): boolean;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[];
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
/** Optionally, get the shebang */
function getShebang(text: string): string;
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
declare module "typescript" {
function getDefaultLibFileName(options: CompilerOptions): string;
@@ -1489,13 +1511,17 @@ declare module "typescript" {
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare module "typescript" {
/** The version of the TypeScript compiler release */
const version: string;
function findConfigFile(searchPath: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule;
function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModule;
function baseUrlModuleNameResolver(moduleName: string, containingFile: string, baseUrl: string, host: ModuleResolutionHost): ResolvedModule;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare module "typescript" {
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
@@ -1559,6 +1585,7 @@ declare module "typescript" {
getConstructSignatures(): Signature[];
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
}
interface Signature {
getDeclaration(): SignatureDeclaration;
@@ -1600,6 +1627,7 @@ declare module "typescript" {
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
}
interface HostCancellationToken {
@@ -1620,6 +1648,7 @@ declare module "typescript" {
trace?(s: string): void;
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -1660,6 +1689,7 @@ declare module "typescript" {
getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[];
getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
@@ -1696,6 +1726,11 @@ declare module "typescript" {
span: TextSpan;
newText: string;
}
interface TextInsertion {
newText: string;
/** The position in newText the caret should point to after the insertion. */
caretOffset: number;
}
interface RenameLocation {
textSpan: TextSpan;
fileName: string;
@@ -1716,6 +1751,7 @@ declare module "typescript" {
const writtenReference: string;
}
interface HighlightSpan {
fileName?: string;
textSpan: TextSpan;
kind: string;
}
@@ -1743,6 +1779,7 @@ declare module "typescript" {
InsertSpaceAfterKeywordsInControlFlowStatements: boolean;
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
PlaceOpenBraceOnNewLineForFunctions: boolean;
PlaceOpenBraceOnNewLineForControlBlocks: boolean;
[s: string]: boolean | number | string;
@@ -1985,6 +2022,7 @@ declare module "typescript" {
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
reportStats(): string;
}
module ScriptElementKind {
const unknown: string;
@@ -2071,10 +2109,24 @@ declare module "typescript" {
}
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
interface TranspileOptions {
compilerOptions?: CompilerOptions;
fileName?: string;
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: Map<string>;
}
interface TranspileOutput {
outputText: string;
diagnostics?: Diagnostic[];
sourceMapText?: string;
}
function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput;
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry;
function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
File diff suppressed because it is too large Load Diff
+352 -300
View File
@@ -23,6 +23,7 @@ declare namespace ts {
contains(fileName: string): boolean;
remove(fileName: string): void;
forEachValue(f: (v: T) => void): void;
clear(): void;
}
interface TextRange {
pos: number;
@@ -35,293 +36,294 @@ declare namespace ts {
MultiLineCommentTrivia = 3,
NewLineTrivia = 4,
WhitespaceTrivia = 5,
ConflictMarkerTrivia = 6,
NumericLiteral = 7,
StringLiteral = 8,
RegularExpressionLiteral = 9,
NoSubstitutionTemplateLiteral = 10,
TemplateHead = 11,
TemplateMiddle = 12,
TemplateTail = 13,
OpenBraceToken = 14,
CloseBraceToken = 15,
OpenParenToken = 16,
CloseParenToken = 17,
OpenBracketToken = 18,
CloseBracketToken = 19,
DotToken = 20,
DotDotDotToken = 21,
SemicolonToken = 22,
CommaToken = 23,
LessThanToken = 24,
LessThanSlashToken = 25,
GreaterThanToken = 26,
LessThanEqualsToken = 27,
GreaterThanEqualsToken = 28,
EqualsEqualsToken = 29,
ExclamationEqualsToken = 30,
EqualsEqualsEqualsToken = 31,
ExclamationEqualsEqualsToken = 32,
EqualsGreaterThanToken = 33,
PlusToken = 34,
MinusToken = 35,
AsteriskToken = 36,
SlashToken = 37,
PercentToken = 38,
PlusPlusToken = 39,
MinusMinusToken = 40,
LessThanLessThanToken = 41,
GreaterThanGreaterThanToken = 42,
GreaterThanGreaterThanGreaterThanToken = 43,
AmpersandToken = 44,
BarToken = 45,
CaretToken = 46,
ExclamationToken = 47,
TildeToken = 48,
AmpersandAmpersandToken = 49,
BarBarToken = 50,
QuestionToken = 51,
ColonToken = 52,
AtToken = 53,
EqualsToken = 54,
PlusEqualsToken = 55,
MinusEqualsToken = 56,
AsteriskEqualsToken = 57,
SlashEqualsToken = 58,
PercentEqualsToken = 59,
LessThanLessThanEqualsToken = 60,
GreaterThanGreaterThanEqualsToken = 61,
GreaterThanGreaterThanGreaterThanEqualsToken = 62,
AmpersandEqualsToken = 63,
BarEqualsToken = 64,
CaretEqualsToken = 65,
Identifier = 66,
BreakKeyword = 67,
CaseKeyword = 68,
CatchKeyword = 69,
ClassKeyword = 70,
ConstKeyword = 71,
ContinueKeyword = 72,
DebuggerKeyword = 73,
DefaultKeyword = 74,
DeleteKeyword = 75,
DoKeyword = 76,
ElseKeyword = 77,
EnumKeyword = 78,
ExportKeyword = 79,
ExtendsKeyword = 80,
FalseKeyword = 81,
FinallyKeyword = 82,
ForKeyword = 83,
FunctionKeyword = 84,
IfKeyword = 85,
ImportKeyword = 86,
InKeyword = 87,
InstanceOfKeyword = 88,
NewKeyword = 89,
NullKeyword = 90,
ReturnKeyword = 91,
SuperKeyword = 92,
SwitchKeyword = 93,
ThisKeyword = 94,
ThrowKeyword = 95,
TrueKeyword = 96,
TryKeyword = 97,
TypeOfKeyword = 98,
VarKeyword = 99,
VoidKeyword = 100,
WhileKeyword = 101,
WithKeyword = 102,
ImplementsKeyword = 103,
InterfaceKeyword = 104,
LetKeyword = 105,
PackageKeyword = 106,
PrivateKeyword = 107,
ProtectedKeyword = 108,
PublicKeyword = 109,
StaticKeyword = 110,
YieldKeyword = 111,
AbstractKeyword = 112,
AsKeyword = 113,
AnyKeyword = 114,
AsyncKeyword = 115,
AwaitKeyword = 116,
BooleanKeyword = 117,
ConstructorKeyword = 118,
DeclareKeyword = 119,
GetKeyword = 120,
IsKeyword = 121,
ModuleKeyword = 122,
NamespaceKeyword = 123,
RequireKeyword = 124,
NumberKeyword = 125,
SetKeyword = 126,
StringKeyword = 127,
SymbolKeyword = 128,
TypeKeyword = 129,
FromKeyword = 130,
OfKeyword = 131,
QualifiedName = 132,
ComputedPropertyName = 133,
TypeParameter = 134,
Parameter = 135,
Decorator = 136,
PropertySignature = 137,
PropertyDeclaration = 138,
MethodSignature = 139,
MethodDeclaration = 140,
Constructor = 141,
GetAccessor = 142,
SetAccessor = 143,
CallSignature = 144,
ConstructSignature = 145,
IndexSignature = 146,
TypePredicate = 147,
TypeReference = 148,
FunctionType = 149,
ConstructorType = 150,
TypeQuery = 151,
TypeLiteral = 152,
ArrayType = 153,
TupleType = 154,
UnionType = 155,
IntersectionType = 156,
ParenthesizedType = 157,
ObjectBindingPattern = 158,
ArrayBindingPattern = 159,
BindingElement = 160,
ArrayLiteralExpression = 161,
ObjectLiteralExpression = 162,
PropertyAccessExpression = 163,
ElementAccessExpression = 164,
CallExpression = 165,
NewExpression = 166,
TaggedTemplateExpression = 167,
TypeAssertionExpression = 168,
ParenthesizedExpression = 169,
FunctionExpression = 170,
ArrowFunction = 171,
DeleteExpression = 172,
TypeOfExpression = 173,
VoidExpression = 174,
AwaitExpression = 175,
PrefixUnaryExpression = 176,
PostfixUnaryExpression = 177,
BinaryExpression = 178,
ConditionalExpression = 179,
TemplateExpression = 180,
YieldExpression = 181,
SpreadElementExpression = 182,
ClassExpression = 183,
OmittedExpression = 184,
ExpressionWithTypeArguments = 185,
AsExpression = 186,
TemplateSpan = 187,
SemicolonClassElement = 188,
Block = 189,
VariableStatement = 190,
EmptyStatement = 191,
ExpressionStatement = 192,
IfStatement = 193,
DoStatement = 194,
WhileStatement = 195,
ForStatement = 196,
ForInStatement = 197,
ForOfStatement = 198,
ContinueStatement = 199,
BreakStatement = 200,
ReturnStatement = 201,
WithStatement = 202,
SwitchStatement = 203,
LabeledStatement = 204,
ThrowStatement = 205,
TryStatement = 206,
DebuggerStatement = 207,
VariableDeclaration = 208,
VariableDeclarationList = 209,
FunctionDeclaration = 210,
ClassDeclaration = 211,
InterfaceDeclaration = 212,
TypeAliasDeclaration = 213,
EnumDeclaration = 214,
ModuleDeclaration = 215,
ModuleBlock = 216,
CaseBlock = 217,
ImportEqualsDeclaration = 218,
ImportDeclaration = 219,
ImportClause = 220,
NamespaceImport = 221,
NamedImports = 222,
ImportSpecifier = 223,
ExportAssignment = 224,
ExportDeclaration = 225,
NamedExports = 226,
ExportSpecifier = 227,
MissingDeclaration = 228,
ExternalModuleReference = 229,
JsxElement = 230,
JsxSelfClosingElement = 231,
JsxOpeningElement = 232,
JsxText = 233,
JsxClosingElement = 234,
JsxAttribute = 235,
JsxSpreadAttribute = 236,
JsxExpression = 237,
CaseClause = 238,
DefaultClause = 239,
HeritageClause = 240,
CatchClause = 241,
PropertyAssignment = 242,
ShorthandPropertyAssignment = 243,
EnumMember = 244,
SourceFile = 245,
JSDocTypeExpression = 246,
JSDocAllType = 247,
JSDocUnknownType = 248,
JSDocArrayType = 249,
JSDocUnionType = 250,
JSDocTupleType = 251,
JSDocNullableType = 252,
JSDocNonNullableType = 253,
JSDocRecordType = 254,
JSDocRecordMember = 255,
JSDocTypeReference = 256,
JSDocOptionalType = 257,
JSDocFunctionType = 258,
JSDocVariadicType = 259,
JSDocConstructorType = 260,
JSDocThisType = 261,
JSDocComment = 262,
JSDocTag = 263,
JSDocParameterTag = 264,
JSDocReturnTag = 265,
JSDocTypeTag = 266,
JSDocTemplateTag = 267,
SyntaxList = 268,
Count = 269,
FirstAssignment = 54,
LastAssignment = 65,
FirstReservedWord = 67,
LastReservedWord = 102,
FirstKeyword = 67,
LastKeyword = 131,
FirstFutureReservedWord = 103,
LastFutureReservedWord = 111,
FirstTypeNode = 148,
LastTypeNode = 157,
FirstPunctuation = 14,
LastPunctuation = 65,
ShebangTrivia = 6,
ConflictMarkerTrivia = 7,
NumericLiteral = 8,
StringLiteral = 9,
RegularExpressionLiteral = 10,
NoSubstitutionTemplateLiteral = 11,
TemplateHead = 12,
TemplateMiddle = 13,
TemplateTail = 14,
OpenBraceToken = 15,
CloseBraceToken = 16,
OpenParenToken = 17,
CloseParenToken = 18,
OpenBracketToken = 19,
CloseBracketToken = 20,
DotToken = 21,
DotDotDotToken = 22,
SemicolonToken = 23,
CommaToken = 24,
LessThanToken = 25,
LessThanSlashToken = 26,
GreaterThanToken = 27,
LessThanEqualsToken = 28,
GreaterThanEqualsToken = 29,
EqualsEqualsToken = 30,
ExclamationEqualsToken = 31,
EqualsEqualsEqualsToken = 32,
ExclamationEqualsEqualsToken = 33,
EqualsGreaterThanToken = 34,
PlusToken = 35,
MinusToken = 36,
AsteriskToken = 37,
SlashToken = 38,
PercentToken = 39,
PlusPlusToken = 40,
MinusMinusToken = 41,
LessThanLessThanToken = 42,
GreaterThanGreaterThanToken = 43,
GreaterThanGreaterThanGreaterThanToken = 44,
AmpersandToken = 45,
BarToken = 46,
CaretToken = 47,
ExclamationToken = 48,
TildeToken = 49,
AmpersandAmpersandToken = 50,
BarBarToken = 51,
QuestionToken = 52,
ColonToken = 53,
AtToken = 54,
EqualsToken = 55,
PlusEqualsToken = 56,
MinusEqualsToken = 57,
AsteriskEqualsToken = 58,
SlashEqualsToken = 59,
PercentEqualsToken = 60,
LessThanLessThanEqualsToken = 61,
GreaterThanGreaterThanEqualsToken = 62,
GreaterThanGreaterThanGreaterThanEqualsToken = 63,
AmpersandEqualsToken = 64,
BarEqualsToken = 65,
CaretEqualsToken = 66,
Identifier = 67,
BreakKeyword = 68,
CaseKeyword = 69,
CatchKeyword = 70,
ClassKeyword = 71,
ConstKeyword = 72,
ContinueKeyword = 73,
DebuggerKeyword = 74,
DefaultKeyword = 75,
DeleteKeyword = 76,
DoKeyword = 77,
ElseKeyword = 78,
EnumKeyword = 79,
ExportKeyword = 80,
ExtendsKeyword = 81,
FalseKeyword = 82,
FinallyKeyword = 83,
ForKeyword = 84,
FunctionKeyword = 85,
IfKeyword = 86,
ImportKeyword = 87,
InKeyword = 88,
InstanceOfKeyword = 89,
NewKeyword = 90,
NullKeyword = 91,
ReturnKeyword = 92,
SuperKeyword = 93,
SwitchKeyword = 94,
ThisKeyword = 95,
ThrowKeyword = 96,
TrueKeyword = 97,
TryKeyword = 98,
TypeOfKeyword = 99,
VarKeyword = 100,
VoidKeyword = 101,
WhileKeyword = 102,
WithKeyword = 103,
ImplementsKeyword = 104,
InterfaceKeyword = 105,
LetKeyword = 106,
PackageKeyword = 107,
PrivateKeyword = 108,
ProtectedKeyword = 109,
PublicKeyword = 110,
StaticKeyword = 111,
YieldKeyword = 112,
AbstractKeyword = 113,
AsKeyword = 114,
AnyKeyword = 115,
AsyncKeyword = 116,
AwaitKeyword = 117,
BooleanKeyword = 118,
ConstructorKeyword = 119,
DeclareKeyword = 120,
GetKeyword = 121,
IsKeyword = 122,
ModuleKeyword = 123,
NamespaceKeyword = 124,
RequireKeyword = 125,
NumberKeyword = 126,
SetKeyword = 127,
StringKeyword = 128,
SymbolKeyword = 129,
TypeKeyword = 130,
FromKeyword = 131,
OfKeyword = 132,
QualifiedName = 133,
ComputedPropertyName = 134,
TypeParameter = 135,
Parameter = 136,
Decorator = 137,
PropertySignature = 138,
PropertyDeclaration = 139,
MethodSignature = 140,
MethodDeclaration = 141,
Constructor = 142,
GetAccessor = 143,
SetAccessor = 144,
CallSignature = 145,
ConstructSignature = 146,
IndexSignature = 147,
TypePredicate = 148,
TypeReference = 149,
FunctionType = 150,
ConstructorType = 151,
TypeQuery = 152,
TypeLiteral = 153,
ArrayType = 154,
TupleType = 155,
UnionType = 156,
IntersectionType = 157,
ParenthesizedType = 158,
ObjectBindingPattern = 159,
ArrayBindingPattern = 160,
BindingElement = 161,
ArrayLiteralExpression = 162,
ObjectLiteralExpression = 163,
PropertyAccessExpression = 164,
ElementAccessExpression = 165,
CallExpression = 166,
NewExpression = 167,
TaggedTemplateExpression = 168,
TypeAssertionExpression = 169,
ParenthesizedExpression = 170,
FunctionExpression = 171,
ArrowFunction = 172,
DeleteExpression = 173,
TypeOfExpression = 174,
VoidExpression = 175,
AwaitExpression = 176,
PrefixUnaryExpression = 177,
PostfixUnaryExpression = 178,
BinaryExpression = 179,
ConditionalExpression = 180,
TemplateExpression = 181,
YieldExpression = 182,
SpreadElementExpression = 183,
ClassExpression = 184,
OmittedExpression = 185,
ExpressionWithTypeArguments = 186,
AsExpression = 187,
TemplateSpan = 188,
SemicolonClassElement = 189,
Block = 190,
VariableStatement = 191,
EmptyStatement = 192,
ExpressionStatement = 193,
IfStatement = 194,
DoStatement = 195,
WhileStatement = 196,
ForStatement = 197,
ForInStatement = 198,
ForOfStatement = 199,
ContinueStatement = 200,
BreakStatement = 201,
ReturnStatement = 202,
WithStatement = 203,
SwitchStatement = 204,
LabeledStatement = 205,
ThrowStatement = 206,
TryStatement = 207,
DebuggerStatement = 208,
VariableDeclaration = 209,
VariableDeclarationList = 210,
FunctionDeclaration = 211,
ClassDeclaration = 212,
InterfaceDeclaration = 213,
TypeAliasDeclaration = 214,
EnumDeclaration = 215,
ModuleDeclaration = 216,
ModuleBlock = 217,
CaseBlock = 218,
ImportEqualsDeclaration = 219,
ImportDeclaration = 220,
ImportClause = 221,
NamespaceImport = 222,
NamedImports = 223,
ImportSpecifier = 224,
ExportAssignment = 225,
ExportDeclaration = 226,
NamedExports = 227,
ExportSpecifier = 228,
MissingDeclaration = 229,
ExternalModuleReference = 230,
JsxElement = 231,
JsxSelfClosingElement = 232,
JsxOpeningElement = 233,
JsxText = 234,
JsxClosingElement = 235,
JsxAttribute = 236,
JsxSpreadAttribute = 237,
JsxExpression = 238,
CaseClause = 239,
DefaultClause = 240,
HeritageClause = 241,
CatchClause = 242,
PropertyAssignment = 243,
ShorthandPropertyAssignment = 244,
EnumMember = 245,
SourceFile = 246,
JSDocTypeExpression = 247,
JSDocAllType = 248,
JSDocUnknownType = 249,
JSDocArrayType = 250,
JSDocUnionType = 251,
JSDocTupleType = 252,
JSDocNullableType = 253,
JSDocNonNullableType = 254,
JSDocRecordType = 255,
JSDocRecordMember = 256,
JSDocTypeReference = 257,
JSDocOptionalType = 258,
JSDocFunctionType = 259,
JSDocVariadicType = 260,
JSDocConstructorType = 261,
JSDocThisType = 262,
JSDocComment = 263,
JSDocTag = 264,
JSDocParameterTag = 265,
JSDocReturnTag = 266,
JSDocTypeTag = 267,
JSDocTemplateTag = 268,
SyntaxList = 269,
Count = 270,
FirstAssignment = 55,
LastAssignment = 66,
FirstReservedWord = 68,
LastReservedWord = 103,
FirstKeyword = 68,
LastKeyword = 132,
FirstFutureReservedWord = 104,
LastFutureReservedWord = 112,
FirstTypeNode = 149,
LastTypeNode = 158,
FirstPunctuation = 15,
LastPunctuation = 66,
FirstToken = 0,
LastToken = 131,
LastToken = 132,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
LastLiteralToken = 10,
FirstTemplateToken = 10,
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 65,
FirstNode = 132,
LastTriviaToken = 7,
FirstLiteralToken = 8,
LastLiteralToken = 11,
FirstTemplateToken = 11,
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 66,
FirstNode = 133,
}
const enum NodeFlags {
Export = 1,
@@ -452,9 +454,9 @@ declare namespace ts {
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
* Examples:
* FunctionDeclaration
* MethodDeclaration
* AccessorDeclaration
* - FunctionDeclaration
* - MethodDeclaration
* - AccessorDeclaration
*/
interface FunctionLikeDeclaration extends SignatureDeclaration {
_functionLikeDeclarationBrand: any;
@@ -944,7 +946,7 @@ declare namespace ts {
getSourceFile(fileName: string): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
interface ParseConfigHost extends ModuleResolutionHost {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
@@ -958,6 +960,10 @@ declare namespace ts {
throwIfCancellationRequested(): void;
}
interface Program extends ScriptReferenceHost {
/**
* Get a list of root file names that were passed to a 'createProgram'
*/
getRootFileNames(): string[];
/**
* Get a list of files in the program
*/
@@ -1019,11 +1025,6 @@ declare namespace ts {
emitSkipped: boolean;
diagnostics: Diagnostic[];
}
interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
getSourceFiles(): SourceFile[];
getSourceFile(fileName: string): SourceFile;
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
@@ -1031,6 +1032,7 @@ declare namespace ts {
getPropertyOfType(type: Type, propertyName: string): Symbol;
getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getBaseTypes(type: InterfaceType): ObjectType[];
getReturnTypeOfSignature(signature: Signature): Type;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
@@ -1054,6 +1056,7 @@ declare namespace ts {
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -1198,7 +1201,7 @@ declare namespace ts {
Anonymous = 65536,
Instantiated = 131072,
ObjectLiteral = 524288,
ESSymbol = 4194304,
ESSymbol = 16777216,
StringLike = 258,
NumberLike = 132,
ObjectType = 80896,
@@ -1218,8 +1221,6 @@ declare namespace ts {
typeParameters: TypeParameter[];
outerTypeParameters: TypeParameter[];
localTypeParameters: TypeParameter[];
resolvedBaseConstructorType?: Type;
resolvedBaseTypes: ObjectType[];
}
interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
declaredProperties: Symbol[];
@@ -1292,6 +1293,10 @@ declare namespace ts {
Error = 1,
Message = 2,
}
const enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2,
}
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
@@ -1299,6 +1304,7 @@ declare namespace ts {
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
@@ -1315,6 +1321,7 @@ declare namespace ts {
noLib?: boolean;
noResolve?: boolean;
out?: string;
outFile?: string;
outDir?: string;
preserveConstEnums?: boolean;
project?: string;
@@ -1330,6 +1337,7 @@ declare namespace ts {
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
moduleResolution?: ModuleResolutionKind;
[option: string]: string | number | boolean;
}
const enum ModuleKind {
@@ -1367,14 +1375,25 @@ declare namespace ts {
fileNames: string[];
errors: Diagnostic[];
}
interface CompilerHost {
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string;
}
interface ResolvedModule {
resolvedFileName: string;
failedLookupLocations: string[];
}
type ModuleNameResolver = (moduleName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => ResolvedModule;
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
}
interface TextSpan {
start: number;
@@ -1448,8 +1467,11 @@ declare namespace ts {
function couldStartTrivia(text: string, pos: number): boolean;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[];
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
/** Optionally, get the shebang */
function getShebang(text: string): string;
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean;
function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner;
}
declare namespace ts {
function getDefaultLibFileName(options: CompilerOptions): string;
@@ -1489,13 +1511,17 @@ declare namespace ts {
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version: string;
function findConfigFile(searchPath: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule;
function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModule;
function baseUrlModuleNameResolver(moduleName: string, containingFile: string, baseUrl: string, host: ModuleResolutionHost): ResolvedModule;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
@@ -1559,6 +1585,7 @@ declare namespace ts {
getConstructSignatures(): Signature[];
getStringIndexType(): Type;
getNumberIndexType(): Type;
getBaseTypes(): ObjectType[];
}
interface Signature {
getDeclaration(): SignatureDeclaration;
@@ -1600,6 +1627,7 @@ declare namespace ts {
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
}
interface HostCancellationToken {
@@ -1620,6 +1648,7 @@ declare namespace ts {
trace?(s: string): void;
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -1660,6 +1689,7 @@ declare namespace ts {
getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[];
getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[];
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[];
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
@@ -1696,6 +1726,11 @@ declare namespace ts {
span: TextSpan;
newText: string;
}
interface TextInsertion {
newText: string;
/** The position in newText the caret should point to after the insertion. */
caretOffset: number;
}
interface RenameLocation {
textSpan: TextSpan;
fileName: string;
@@ -1716,6 +1751,7 @@ declare namespace ts {
const writtenReference: string;
}
interface HighlightSpan {
fileName?: string;
textSpan: TextSpan;
kind: string;
}
@@ -1743,6 +1779,7 @@ declare namespace ts {
InsertSpaceAfterKeywordsInControlFlowStatements: boolean;
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean;
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean;
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean;
PlaceOpenBraceOnNewLineForFunctions: boolean;
PlaceOpenBraceOnNewLineForControlBlocks: boolean;
[s: string]: boolean | number | string;
@@ -1985,6 +2022,7 @@ declare namespace ts {
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
reportStats(): string;
}
module ScriptElementKind {
const unknown: string;
@@ -2071,10 +2109,24 @@ declare namespace ts {
}
function displayPartsToString(displayParts: SymbolDisplayPart[]): string;
function getDefaultCompilerOptions(): CompilerOptions;
interface TranspileOptions {
compilerOptions?: CompilerOptions;
fileName?: string;
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: Map<string>;
}
interface TranspileOutput {
outputText: string;
diagnostics?: Diagnostic[];
sourceMapText?: string;
}
function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput;
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry;
function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
File diff suppressed because it is too large Load Diff
+15 -4
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "1.6.0",
"version": "1.7.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@@ -19,8 +19,8 @@
"type": "git",
"url": "https://github.com/Microsoft/TypeScript.git"
},
"preferGlobal": true,
"main": "./bin/typescript.js",
"main": "./lib/typescript.js",
"typings": "./lib/typescript.d.ts",
"bin": {
"tsc": "./bin/tsc",
"tsserver": "./bin/tsserver"
@@ -38,6 +38,17 @@
"tslint": "latest"
},
"scripts": {
"test": "jake runtests"
"pretest": "jake tests",
"test": "jake runtests",
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "jake local",
"build:tests": "jake tests",
"clean": "jake clean"
},
"browser": {
"buffer": false,
"fs": false,
"os": false,
"path": false
}
}
+29 -6
View File
@@ -1,8 +1,16 @@
// word2md - Word to Markdown conversion tool
//
// word2md converts a Microsoft Word document to Markdown formatted text. The tool uses the
// Word Automation APIs to start an instance of Word and access the contents of the document
// being converted. The tool must be run using the cscript.exe script host and requires Word
// to be installed on the target machine. The name of the document to convert must be specified
// as a command line argument and the resulting Markdown is written to standard output. The
// tool recognizes the specific Word styles used in the TypeScript Language Specification.
var sys = (function () {
var fileStream = new ActiveXObject("ADODB.Stream");
fileStream.Type = 2;
fileStream.Type = 2 /*text*/;
var binaryStream = new ActiveXObject("ADODB.Stream");
binaryStream.Type = 1;
binaryStream.Type = 1 /*binary*/;
var args = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
@@ -17,11 +25,13 @@ var sys = (function () {
fileStream.Open();
binaryStream.Open();
try {
// Write characters in UTF-8 encoding
fileStream.Charset = "utf-8";
fileStream.WriteText(data);
// We don't want the BOM, skip it by setting the starting location to 3 (size of BOM).
fileStream.Position = 3;
fileStream.CopyTo(binaryStream);
binaryStream.SaveToFile(fileName, 2);
binaryStream.SaveToFile(fileName, 2 /*overwrite*/);
}
finally {
binaryStream.Close();
@@ -59,6 +69,17 @@ function convertDocumentToMarkdown(doc) {
setProperties(replace, replaceOptions);
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
function fixHyperlinks() {
var count = doc.hyperlinks.count;
for (var i = 0; i < count; i++) {
var hyperlink = doc.hyperlinks.item(i + 1);
var address = hyperlink.address;
if (address && address.length > 0) {
var textToDisplay = hyperlink.textToDisplay;
hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
}
}
}
function write(s) {
result += s;
}
@@ -184,14 +205,15 @@ function convertDocumentToMarkdown(doc) {
findReplace("&lt;", { style: "Code Fragment" }, "<", {});
findReplace("&lt;", { style: "Terminal" }, "<", {});
findReplace("", { font: { subscript: true } }, "<sub>^&</sub>", { font: { subscript: false } });
findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 });
findReplace("", { style: "Production" }, "*^&*", { style: -66 });
findReplace("", { style: "Terminal" }, "`^&`", { style: -66 });
findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ });
findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ });
findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } });
findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } });
doc.fields.toggleShowCodes();
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
fixHyperlinks();
writeDocument();
result = result.replace(/\x85/g, "\u2026");
result = result.replace(/\x96/g, "\u2013");
@@ -210,3 +232,4 @@ function main(args) {
app.quit();
}
main(sys.args);
//# sourceMappingURL=file:///c:/ts/scripts/word2md.js.map
+24
View File
@@ -100,9 +100,19 @@ module Word {
toggleShowCodes(): void;
}
export interface Hyperlink {
address: string;
textToDisplay: string;
range: Range;
}
export interface Hyperlinks extends Collection<Hyperlink> {
}
export interface Document {
fields: Fields;
paragraphs: Paragraphs;
hyperlinks: Hyperlinks;
builtInDocumentProperties: Collection<any>;
close(saveChanges: boolean): void;
range(): Range;
@@ -195,6 +205,18 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
find.execute(findText, false, false, false, false, false, true, 0, true, replaceText, 2);
}
function fixHyperlinks() {
var count = doc.hyperlinks.count;
for (var i = 0; i < count; i++) {
var hyperlink = doc.hyperlinks.item(i + 1);
var address = hyperlink.address;
if (address && address.length > 0) {
var textToDisplay = hyperlink.textToDisplay;
hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")";
}
}
}
function write(s: string) {
result += s;
}
@@ -347,6 +369,8 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
findReplace("^19 REF", {}, "[^&](#^&)", {});
doc.fields.toggleShowCodes();
fixHyperlinks();
writeDocument();
result = result.replace(/\x85/g, "\u2026");
+8 -4
View File
@@ -74,7 +74,7 @@ namespace ts {
// If the current node is a container that also container that also contains locals. Examples:
//
// Functions, Methods, Modules, Source-files.
IsContainerWithLocals = IsContainer | HasLocals
IsContainerWithLocals = IsContainer | HasLocals
}
export function bindSourceFile(file: SourceFile) {
@@ -139,7 +139,7 @@ namespace ts {
function getDeclarationName(node: Declaration): string {
if (node.name) {
if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {
return '"' + (<LiteralExpression>node.name).text + '"';
return `"${(<LiteralExpression>node.name).text}"`;
}
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
let nameExpression = (<ComputedPropertyName>node.name).expression;
@@ -830,7 +830,7 @@ namespace ts {
// Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the
// string to contain unicode escapes (as per ES5).
return nodeText === '"use strict"' || nodeText === "'use strict'";
return nodeText === "\"use strict\"" || nodeText === "'use strict'";
}
function bindWorker(node: Node) {
@@ -930,7 +930,7 @@ namespace ts {
function bindSourceFileIfExternalModule() {
setExportContextFlag(file);
if (isExternalModule(file)) {
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, '"' + removeFileExtension(file.fileName) + '"');
bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName)}"`);
}
}
@@ -973,6 +973,10 @@ namespace ts {
else {
let bindingName = node.name ? node.name.text : "__class";
bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName);
// Add name of class expression into the map for semantic classifier
if (node.name) {
classifiableNames[node.name.text] = node.name.text;
}
}
let symbol = node.symbol;
+606 -472
View File
File diff suppressed because it is too large Load Diff
+60 -11
View File
@@ -30,6 +30,11 @@ namespace ts {
type: "boolean",
description: Diagnostics.Print_this_message,
},
{
name: "init",
type: "boolean",
description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
},
{
name: "inlineSourceMap",
type: "boolean",
@@ -120,6 +125,13 @@ namespace ts {
{
name: "out",
type: "string",
isFilePath: false, // This is intentionally broken to support compatability with existing tsconfig files
// for correct behaviour, please use outFile
paramType: Diagnostics.FILE,
},
{
name: "outFile",
type: "string",
isFilePath: true,
description: Diagnostics.Concatenate_and_emit_output_to_single_file,
paramType: Diagnostics.FILE,
@@ -172,6 +184,12 @@ namespace ts {
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
paramType: Diagnostics.LOCATION,
},
{
name: "suppressExcessPropertyErrors",
type: "boolean",
description: Diagnostics.Suppress_excess_property_checks_for_object_literals,
experimental: true
},
{
name: "suppressImplicitAnyIndexErrors",
type: "boolean",
@@ -218,22 +236,50 @@ namespace ts {
type: "boolean",
experimental: true,
description: Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
}
},
{
name: "moduleResolution",
type: {
"node": ModuleResolutionKind.NodeJs,
"classic": ModuleResolutionKind.Classic
},
experimental: true,
description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_or_classic_TypeScript_pre_1_6
}
];
export function parseCommandLine(commandLine: string[]): ParsedCommandLine {
let options: CompilerOptions = {};
let fileNames: string[] = [];
let errors: Diagnostic[] = [];
let shortOptionNames: Map<string> = {};
let optionNameMap: Map<CommandLineOption> = {};
/* @internal */
export interface OptionNameMap {
optionNameMap: Map<CommandLineOption>;
shortOptionNames: Map<string>;
}
let optionNameMapCache: OptionNameMap;
/* @internal */
export function getOptionNameMap(): OptionNameMap {
if (optionNameMapCache) {
return optionNameMapCache;
}
let optionNameMap: Map<CommandLineOption> = {};
let shortOptionNames: Map<string> = {};
forEach(optionDeclarations, option => {
optionNameMap[option.name.toLowerCase()] = option;
if (option.shortName) {
shortOptionNames[option.shortName] = option.name;
}
});
optionNameMapCache = { optionNameMap, shortOptionNames };
return optionNameMapCache;
}
export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine {
let options: CompilerOptions = {};
let fileNames: string[] = [];
let errors: Diagnostic[] = [];
let { optionNameMap, shortOptionNames } = getOptionNameMap();
parseStrings(commandLine);
return {
options,
@@ -297,7 +343,7 @@ namespace ts {
}
function parseResponseFile(fileName: string) {
let text = sys.readFile(fileName);
let text = readFile ? readFile(fileName) : sys.readFile(fileName);
if (!text) {
errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName));
@@ -335,7 +381,7 @@ namespace ts {
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string): { config?: any; error?: Diagnostic } {
let text = '';
let text = "";
try {
text = sys.readFile(fileName);
}
@@ -422,10 +468,13 @@ namespace ts {
if (json["files"] instanceof Array) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
}
}
else {
let exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
@@ -447,4 +496,4 @@ namespace ts {
return fileNames;
}
}
}
}
+24 -12
View File
@@ -24,6 +24,7 @@ namespace ts {
set,
contains,
remove,
clear,
forEachValue: forEachValueInMap
};
@@ -51,6 +52,10 @@ namespace ts {
function normalizeKey(key: string) {
return getCanonicalFileName(normalizeSlashes(key));
}
function clear() {
files = {};
}
}
export const enum Comparison {
@@ -193,6 +198,13 @@ namespace ts {
return array[array.length - 1];
}
/**
* Performs a binary search, finding the index at which 'value' occurs in 'array'.
* If no such index is found, returns the 2's-complement of first index at which
* number[index] exceeds number.
* @param array A sorted array whose first element must be no larger than number
* @param number The value to be searched for in the array.
*/
export function binarySearch(array: number[], value: number): number {
let low = 0;
let high = array.length - 1;
@@ -219,10 +231,10 @@ namespace ts {
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceLeft<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
var count = array.length;
const count = array.length;
if (count > 0) {
var pos = 0;
var result = arguments.length <= 2 ? array[pos++] : initial;
let pos = 0;
let result = arguments.length <= 2 ? array[pos++] : initial;
while (pos < count) {
result = f(<U>result, array[pos++]);
}
@@ -236,9 +248,9 @@ namespace ts {
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial: U): U;
export function reduceRight<T, U>(array: T[], f: (a: U, x: T) => U, initial?: U): U {
if (array) {
var pos = array.length - 1;
let pos = array.length - 1;
if (pos >= 0) {
var result = arguments.length <= 2 ? array[pos--] : initial;
let result = arguments.length <= 2 ? array[pos--] : initial;
while (pos >= 0) {
result = f(<U>result, array[pos--]);
}
@@ -275,14 +287,14 @@ namespace ts {
return <T>result;
}
export function extend<T>(first: Map<T>, second: Map<T>): Map<T> {
let result: Map<T> = {};
export function extend<T1, T2>(first: Map<T1>, second: Map<T2>): Map<T1 & T2> {
let result: Map<T1 & T2> = {};
for (let id in first) {
result[id] = first[id];
(result as any)[id] = first[id];
}
for (let id in second) {
if (!hasProperty(result, id)) {
result[id] = second[id];
(result as any)[id] = second[id];
}
}
return result;
@@ -523,7 +535,7 @@ namespace ts {
if (path.lastIndexOf("file:///", 0) === 0) {
return "file:///".length;
}
let idx = path.indexOf('://');
let idx = path.indexOf("://");
if (idx !== -1) {
return idx + "://".length;
}
@@ -709,7 +721,7 @@ namespace ts {
/**
* List of supported extensions in order of file resolution precedence.
*/
export const supportedExtensions = [".tsx", ".ts", ".d.ts"];
export const supportedExtensions = [".ts", ".tsx", ".d.ts"];
const extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"];
export function removeFileExtension(path: string): string {
@@ -805,4 +817,4 @@ namespace ts {
Debug.assert(false, message);
}
}
}
}
+10 -6
View File
@@ -750,14 +750,18 @@ namespace ts {
}
function writeTypeAliasDeclaration(node: TypeAliasDeclaration) {
let prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
writeTextOfNode(currentSourceFile, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
write(";");
writeLine();
enclosingDeclaration = prevEnclosingDeclaration;
function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
return {
@@ -892,6 +896,9 @@ namespace ts {
if (isSupportedExpressionWithTypeArguments(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
}
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
write("null");
}
function getHeritageClauseVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
@@ -1371,7 +1378,7 @@ namespace ts {
else {
writeTextOfNode(currentSourceFile, node.name);
}
if (node.initializer || hasQuestionToken(node)) {
if (resolver.isOptionalParameter(node)) {
write("?");
}
decreaseIndent();
@@ -1497,11 +1504,8 @@ namespace ts {
// emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void;
writeTextOfNode(currentSourceFile, bindingElement.propertyName);
write(": ");
// If bindingElement has propertyName property, then its name must be another bindingPattern of SyntaxKind.ObjectBindingPattern
emitBindingPattern(<BindingPattern>bindingElement.name);
}
else if (bindingElement.name) {
if (bindingElement.name) {
if (isBindingPattern(bindingElement.name)) {
// If it is a nested binding pattern, we will recursively descend into each element and emit each one separately.
// In the case of rest element, we will omit rest element.
@@ -1573,7 +1577,7 @@ namespace ts {
? referencedFile.fileName // Declaration file, use declaration file name
: shouldEmitToOwnFile(referencedFile, compilerOptions)
? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file
: removeFileExtension(compilerOptions.out) + ".d.ts"; // Global out file
: removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file
declFileName = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizeSlashes(jsFilePath)),
@@ -294,7 +294,7 @@ namespace ts {
Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." },
Duplicate_function_implementation: { code: 2393, category: DiagnosticCategory.Error, key: "Duplicate function implementation." },
Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." },
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration {0} must be all exported or all local." },
Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration '{0}' must be all exported or all local." },
Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." },
Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." },
Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." },
@@ -425,6 +425,8 @@ namespace ts {
JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" },
The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" },
Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" },
A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: DiagnosticCategory.Error, key: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." },
Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -504,19 +506,12 @@ namespace ts {
Unknown_compiler_option_0: { code: 5023, category: DiagnosticCategory.Error, key: "Unknown compiler option '{0}'." },
Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: DiagnosticCategory.Error, key: "Compiler option '{0}' requires a value of type {1}." },
Could_not_write_file_0_Colon_1: { code: 5033, category: DiagnosticCategory.Error, key: "Could not write file '{0}': {1}" },
Option_mapRoot_cannot_be_specified_without_specifying_sourceMap_option: { code: 5038, category: DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified without specifying 'sourceMap' option." },
Option_sourceRoot_cannot_be_specified_without_specifying_sourceMap_option: { code: 5039, category: DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified without specifying 'sourceMap' option." },
Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." },
Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." },
Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." },
Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." },
Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." },
Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." },
Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: DiagnosticCategory.Error, key: "Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." },
Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap: { code: 5048, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'inlineSourceMap'." },
Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5049, category: DiagnosticCategory.Error, key: "Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'." },
Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap: { code: 5050, category: DiagnosticCategory.Error, key: "Option 'mapRoot' cannot be specified with option 'inlineSourceMap'." },
Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: DiagnosticCategory.Error, key: "Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." },
Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: DiagnosticCategory.Error, key: "Option '{0}' cannot be specified without specifying option '{1}'." },
Option_0_cannot_be_specified_with_option_1: { code: 5053, category: DiagnosticCategory.Error, key: "Option '{0}' cannot be specified with option '{1}'." },
A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5053, category: DiagnosticCategory.Error, key: "A 'tsconfig.json' file is already defined at: '{0}'." },
Concatenate_and_emit_output_to_single_file: { code: 6001, category: DiagnosticCategory.Message, key: "Concatenate and emit output to single file." },
Generates_corresponding_d_ts_file: { code: 6002, category: DiagnosticCategory.Message, key: "Generates corresponding '.d.ts' file." },
Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate map files instead of generated locations." },
@@ -567,11 +562,14 @@ namespace ts {
Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: DiagnosticCategory.Message, key: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: DiagnosticCategory.Message, key: "Argument for '--jsx' must be 'preserve' or 'react'." },
Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." },
Enables_experimental_support_for_ES7_decorators: { code: 6065, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 decorators." },
Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: DiagnosticCategory.Message, key: "Enables experimental support for emitting type metadata for decorators." },
Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower: { code: 6067, category: DiagnosticCategory.Message, key: "Option 'experimentalAsyncFunctions' cannot be specified when targeting ES5 or lower." },
Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 async functions." },
Specifies_module_resolution_strategy_Colon_node_Node_or_classic_TypeScript_pre_1_6: { code: 6069, category: DiagnosticCategory.Message, key: "Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6) ." },
Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: DiagnosticCategory.Message, key: "Initializes a TypeScript project and creates a tsconfig.json file." },
Successfully_created_a_tsconfig_json_file: { code: 6071, category: DiagnosticCategory.Message, key: "Successfully created a tsconfig.json file." },
Suppress_excess_property_checks_for_object_literals: { code: 6072, category: DiagnosticCategory.Message, key: "Suppress excess property checks for object literals." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." },
@@ -613,5 +611,6 @@ namespace ts {
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." },
A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: DiagnosticCategory.Error, key: "A constructor cannot contain a 'super' call when its class extends 'null'" },
};
}
+43 -47
View File
@@ -1,4 +1,4 @@
{
{
"Unterminated string literal.": {
"category": "Error",
"code": 1002
@@ -161,7 +161,7 @@
},
"Type '{0}' is not a valid async function return type.": {
"category": "Error",
"code": 1055
"code": 1055
},
"Accessors are only available when targeting ECMAScript 5 and higher.": {
"category": "Error",
@@ -1165,7 +1165,7 @@
"category": "Error",
"code": 2394
},
"Individual declarations in merged declaration {0} must be all exported or all local.": {
"Individual declarations in merged declaration '{0}' must be all exported or all local.": {
"category": "Error",
"code": 2395
},
@@ -1689,6 +1689,14 @@
"category": "Error",
"code": 2650
},
"A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums.": {
"category": "Error",
"code": 2651
},
"Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead.": {
"category": "Error",
"code": 2652
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -2005,58 +2013,30 @@
"category": "Error",
"code": 5033
},
"Option 'mapRoot' cannot be specified without specifying 'sourceMap' option.": {
"category": "Error",
"code": 5038
},
"Option 'sourceRoot' cannot be specified without specifying 'sourceMap' option.": {
"category": "Error",
"code": 5039
},
"Option 'noEmit' cannot be specified with option 'out' or 'outDir'.": {
"category": "Error",
"code": 5040
},
"Option 'noEmit' cannot be specified with option 'declaration'.": {
"category": "Error",
"code": 5041
},
"Option 'project' cannot be mixed with source files on a command line.": {
"category": "Error",
"code": 5042
},
"Option 'declaration' cannot be specified with option 'isolatedModules'.": {
"category": "Error",
"code": 5044
},
"Option 'noEmitOnError' cannot be specified with option 'isolatedModules'.": {
"category": "Error",
"code": 5045
},
"Option 'out' cannot be specified with option 'isolatedModules'.": {
"category": "Error",
"code": 5046
},
"Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher.": {
"category": "Error",
"code": 5047
},
"Option 'sourceMap' cannot be specified with option 'inlineSourceMap'.": {
"category": "Error",
"code": 5048
},
"Option 'sourceRoot' cannot be specified with option 'inlineSourceMap'.": {
"category": "Error",
"code": 5049
},
"Option 'mapRoot' cannot be specified with option 'inlineSourceMap'.": {
"category": "Error",
"code": 5050
},
"Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.": {
"category": "Error",
"code": 5051
},
"Option '{0}' cannot be specified without specifying option '{1}'.": {
"category": "Error",
"code": 5052
},
"Option '{0}' cannot be specified with option '{1}'.": {
"category": "Error",
"code": 5053
},
"A 'tsconfig.json' file is already defined at: '{0}'.": {
"category": "Error",
"code": 5053
},
"Concatenate and emit output to single file.": {
"category": "Message",
@@ -2258,10 +2238,6 @@
"category": "Message",
"code": 6081
},
"Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified.": {
"category": "Error",
"code": 6064
},
"Enables experimental support for ES7 decorators.": {
"category": "Message",
"code": 6065
@@ -2278,6 +2254,22 @@
"category": "Message",
"code": 6068
},
"Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6) .": {
"category": "Message",
"code": 6069
},
"Initializes a TypeScript project and creates a tsconfig.json file.": {
"category": "Message",
"code": 6070
},
"Successfully created a tsconfig.json file.": {
"category": "Message",
"code": 6071
},
"Suppress excess property checks for object literals.": {
"category": "Message",
"code": 6072
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
@@ -2445,5 +2437,9 @@
"Cannot use JSX unless the '--jsx' flag is provided.": {
"category": "Error",
"code": 17004
},
"A constructor cannot contain a 'super' call when its class extends 'null'": {
"category": "Error",
"code": 17005
}
}
+780 -377
View File
File diff suppressed because it is too large Load Diff
+52 -22
View File
@@ -844,6 +844,10 @@ namespace ts {
return token = scanner.scanJsxIdentifier();
}
function scanJsxText(): SyntaxKind {
return token = scanner.scanJsxToken();
}
function speculationHelper<T>(callback: () => T, isLookAhead: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
@@ -913,9 +917,11 @@ namespace ts {
return token > SyntaxKind.LastReservedWord;
}
function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage): boolean {
function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage, shouldAdvance = true): boolean {
if (token === kind) {
nextToken();
if (shouldAdvance) {
nextToken();
}
return true;
}
@@ -3148,7 +3154,7 @@ namespace ts {
}
function parseAwaitExpression() {
var node = <AwaitExpression>createNode(SyntaxKind.AwaitExpression);
const node = <AwaitExpression>createNode(SyntaxKind.AwaitExpression);
nextToken();
node.expression = parseUnaryExpressionOrHigher();
return finishNode(node);
@@ -3178,7 +3184,7 @@ namespace ts {
return parseTypeAssertion();
}
if (lookAhead(nextTokenIsIdentifierOrKeyword)) {
return parseJsxElementOrSelfClosingElement();
return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true);
}
// Fall through
default:
@@ -3308,14 +3314,14 @@ namespace ts {
return finishNode(node);
}
function parseJsxElementOrSelfClosingElement(): JsxElement|JsxSelfClosingElement {
let opening = parseJsxOpeningOrSelfClosingElement();
function parseJsxElementOrSelfClosingElement(inExpressionContext: boolean): JsxElement | JsxSelfClosingElement {
let opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext);
if (opening.kind === SyntaxKind.JsxOpeningElement) {
let node = <JsxElement>createNode(SyntaxKind.JsxElement, opening.pos);
node.openingElement = opening;
node.children = parseJsxChildren(node.openingElement.tagName);
node.closingElement = parseJsxClosingElement();
node.closingElement = parseJsxClosingElement(inExpressionContext);
return finishNode(node);
}
else {
@@ -3336,11 +3342,11 @@ namespace ts {
case SyntaxKind.JsxText:
return parseJsxText();
case SyntaxKind.OpenBraceToken:
return parseJsxExpression();
return parseJsxExpression(/*inExpressionContext*/ false);
case SyntaxKind.LessThanToken:
return parseJsxElementOrSelfClosingElement();
return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false);
}
Debug.fail('Unknown JSX child kind ' + token);
Debug.fail("Unknown JSX child kind " + token);
}
function parseJsxChildren(openingTagName: EntityName): NodeArray<JsxChild> {
@@ -3368,7 +3374,7 @@ namespace ts {
return result;
}
function parseJsxOpeningOrSelfClosingElement(): JsxOpeningElement|JsxSelfClosingElement {
function parseJsxOpeningOrSelfClosingElement(inExpressionContext: boolean): JsxOpeningElement|JsxSelfClosingElement {
let fullStart = scanner.getStartPos();
parseExpected(SyntaxKind.LessThanToken);
@@ -3378,12 +3384,22 @@ namespace ts {
let attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute);
let node: JsxOpeningLikeElement;
if (parseOptional(SyntaxKind.GreaterThanToken)) {
if (token === SyntaxKind.GreaterThanToken) {
// Closing tag, so scan the immediately-following text with the JSX scanning instead
// of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
// scanning errors
node = <JsxOpeningElement>createNode(SyntaxKind.JsxOpeningElement, fullStart);
scanJsxText();
}
else {
parseExpected(SyntaxKind.SlashToken);
parseExpected(SyntaxKind.GreaterThanToken);
if (inExpressionContext) {
parseExpected(SyntaxKind.GreaterThanToken);
}
else {
parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*advance*/ false);
scanJsxText();
}
node = <JsxSelfClosingElement>createNode(SyntaxKind.JsxSelfClosingElement, fullStart);
}
@@ -3406,14 +3422,20 @@ namespace ts {
return elementName;
}
function parseJsxExpression(): JsxExpression {
function parseJsxExpression(inExpressionContext: boolean): JsxExpression {
let node = <JsxExpression>createNode(SyntaxKind.JsxExpression);
parseExpected(SyntaxKind.OpenBraceToken);
if (token !== SyntaxKind.CloseBraceToken) {
node.expression = parseExpression();
}
parseExpected(SyntaxKind.CloseBraceToken);
if (inExpressionContext) {
parseExpected(SyntaxKind.CloseBraceToken);
}
else {
parseExpected(SyntaxKind.CloseBraceToken, /*message*/ undefined, /*advance*/ false);
scanJsxText();
}
return finishNode(node);
}
@@ -3432,7 +3454,7 @@ namespace ts {
node.initializer = parseLiteralNode();
break;
default:
node.initializer = parseJsxExpression();
node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
break;
}
}
@@ -3448,11 +3470,17 @@ namespace ts {
return finishNode(node);
}
function parseJsxClosingElement(): JsxClosingElement {
function parseJsxClosingElement(inExpressionContext: boolean): JsxClosingElement {
let node = <JsxClosingElement>createNode(SyntaxKind.JsxClosingElement);
parseExpected(SyntaxKind.LessThanSlashToken);
node.tagName = parseJsxElementName();
parseExpected(SyntaxKind.GreaterThanToken);
if (inExpressionContext) {
parseExpected(SyntaxKind.GreaterThanToken);
}
else {
parseExpected(SyntaxKind.GreaterThanToken, /*diagnostic*/ undefined, /*advance*/ false);
scanJsxText();
}
return finishNode(node);
}
@@ -4913,12 +4941,15 @@ namespace ts {
function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray, flags: NodeFlags): ModuleDeclaration {
let node = <ModuleDeclaration>createNode(SyntaxKind.ModuleDeclaration, fullStart);
// If we are parsing a dotted namespace name, we want to
// propagate the 'Namespace' flag across the names if set.
let namespaceFlag = flags & NodeFlags.Namespace;
node.decorators = decorators;
setModifiers(node, modifiers);
node.flags |= flags;
node.name = parseIdentifier();
node.body = parseOptional(SyntaxKind.DotToken)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.Export)
? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, NodeFlags.Export | namespaceFlag)
: parseModuleBlock();
return finishNode(node);
}
@@ -5140,7 +5171,7 @@ namespace ts {
// the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
// If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
if (token === SyntaxKind.FromKeyword || (token === SyntaxKind.StringLiteral && !scanner.hasPrecedingLineBreak())) {
parseExpected(SyntaxKind.FromKeyword)
parseExpected(SyntaxKind.FromKeyword);
node.moduleSpecifier = parseModuleSpecifier();
}
}
@@ -5803,7 +5834,6 @@ namespace ts {
if (!name) {
parseErrorAtPosition(pos, 0, Diagnostics.Identifier_expected);
return undefined;
}
let preName: Identifier, postName: Identifier;
@@ -6011,7 +6041,7 @@ namespace ts {
return;
function visitNode(node: IncrementalNode) {
let text = '';
let text = "";
if (aggressiveChecks && shouldCheckNode(node)) {
text = oldText.substring(node.pos, node.end);
}
+448 -90
View File
@@ -1,5 +1,6 @@
/// <reference path="sys.ts" />
/// <reference path="emitter.ts" />
/// <reference path="core.ts" />
namespace ts {
/* @internal */ export let programTime = 0;
@@ -8,7 +9,10 @@ namespace ts {
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
export const version = "1.6.0";
let emptyArray: any[] = [];
export const version = "1.7.0";
export function findConfigFile(searchPath: string): string {
let fileName = "tsconfig.json";
@@ -25,6 +29,211 @@ namespace ts {
}
return undefined;
}
export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
let basePath = getDirectoryPath(containingFile);
let referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
return normalizePath(referencedFileName);
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {
let moduleResolution = compilerOptions.moduleResolution !== undefined
? compilerOptions.moduleResolution
: compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
switch (moduleResolution) {
case ModuleResolutionKind.NodeJs: return nodeModuleNameResolver(moduleName, containingFile, host);
case ModuleResolutionKind.Classic: return classicNameResolver(moduleName, containingFile, compilerOptions, host);
}
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModule {
let containingDirectory = getDirectoryPath(containingFile);
if (getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
let failedLookupLocations: string[] = [];
let candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let resolvedFileName = loadNodeModuleFromFile(candidate, /* loadOnlyDts */ false, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedFileName, failedLookupLocations };
}
resolvedFileName = loadNodeModuleFromDirectory(candidate, /* loadOnlyDts */ false, failedLookupLocations, host);
return { resolvedFileName, failedLookupLocations };
}
else {
return loadModuleFromNodeModules(moduleName, containingDirectory, host);
}
}
function loadNodeModuleFromFile(candidate: string, loadOnlyDts: boolean, failedLookupLocation: string[], host: ModuleResolutionHost): string {
if (loadOnlyDts) {
return tryLoad(".d.ts");
}
else {
return forEach(supportedExtensions, tryLoad);
}
function tryLoad(ext: string): string {
let fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (host.fileExists(fileName)) {
return fileName;
}
else {
failedLookupLocation.push(fileName);
return undefined;
}
}
}
function loadNodeModuleFromDirectory(candidate: string, loadOnlyDts: boolean, failedLookupLocation: string[], host: ModuleResolutionHost): string {
let packageJsonPath = combinePaths(candidate, "package.json");
if (host.fileExists(packageJsonPath)) {
let jsonContent: { typings?: string };
try {
let jsonText = host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined };
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
let result = loadNodeModuleFromFile(normalizePath(combinePaths(candidate, jsonContent.typings)), loadOnlyDts, failedLookupLocation, host);
if (result) {
return result;
}
}
}
else {
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
}
return loadNodeModuleFromFile(combinePaths(candidate, "index"), loadOnlyDts, failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName: string, directory: string, host: ModuleResolutionHost): ResolvedModule {
let failedLookupLocations: string[] = [];
directory = normalizeSlashes(directory);
while (true) {
let baseName = getBaseFileName(directory);
if (baseName !== "node_modules") {
let nodeModulesFolder = combinePaths(directory, "node_modules");
let candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
let result = loadNodeModuleFromFile(candidate, /* loadOnlyDts */ true, failedLookupLocations, host);
if (result) {
return { resolvedFileName: result, failedLookupLocations };
}
result = loadNodeModuleFromDirectory(candidate, /* loadOnlyDts */ true, failedLookupLocations, host);
if (result) {
return { resolvedFileName: result, failedLookupLocations };
}
}
let parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
break;
}
directory = parentPath;
}
return { resolvedFileName: undefined, failedLookupLocations };
}
export function baseUrlModuleNameResolver(moduleName: string, containingFile: string, baseUrl: string, host: ModuleResolutionHost): ResolvedModule {
Debug.assert(baseUrl !== undefined);
let normalizedModuleName = normalizeSlashes(moduleName);
let basePart = useBaseUrl(moduleName) ? baseUrl : getDirectoryPath(containingFile);
let candidate = normalizePath(combinePaths(basePart, moduleName));
let failedLookupLocations: string[] = [];
return forEach(supportedExtensions, ext => tryLoadFile(candidate + ext)) || { resolvedFileName: undefined, failedLookupLocations };
function tryLoadFile(location: string): ResolvedModule {
if (host.fileExists(location)) {
return { resolvedFileName: location, failedLookupLocations };
}
else {
failedLookupLocations.push(location);
return undefined;
}
}
}
function nameStartsWithDotSlashOrDotDotSlash(name: string) {
let i = name.lastIndexOf("./", 1);
return i === 0 || (i === 1 && name.charCodeAt(0) === CharacterCodes.dot);
}
function useBaseUrl(moduleName: string): boolean {
// path is not rooted
// module name does not start with './' or '../'
return getRootLength(moduleName) === 0 && !nameStartsWithDotSlashOrDotDotSlash(moduleName);
}
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {
// module names that contain '!' are used to reference resources and are not resolved to actual files on disk
if (moduleName.indexOf('!') != -1) {
return { resolvedFileName: undefined, failedLookupLocations: [] };
}
let searchPath = getDirectoryPath(containingFile);
let searchName: string;
let failedLookupLocations: string[] = [];
let referencedSourceFile: string;
while (true) {
searchName = normalizePath(combinePaths(searchPath, moduleName));
referencedSourceFile = forEach(supportedExtensions, extension => {
if (extension === ".tsx" && !compilerOptions.jsx) {
// resolve .tsx files only if jsx support is enabled
// 'logical not' handles both undefined and None cases
return undefined;
}
let candidate = searchName + extension;
if (host.fileExists(candidate)) {
return candidate;
}
else {
failedLookupLocations.push(candidate);
}
});
if (referencedSourceFile) {
break;
}
let parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
return { resolvedFileName: referencedSourceFile, failedLookupLocations };
}
/* @internal */
export const defaultInitCompilerOptions: CompilerOptions = {
module: ModuleKind.CommonJS,
target: ScriptTarget.ES3,
noImplicitAny: false,
outDir: "built",
rootDir: ".",
sourceMap: false,
};
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
let currentDirectory: string;
@@ -92,7 +301,8 @@ namespace ts {
}
const newLine = getNewLineCharacter(options);
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
@@ -100,7 +310,9 @@ namespace ts {
getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName,
getNewLine: () => newLine
getNewLine: () => newLine,
fileExists: fileName => sys.fileExists(fileName),
readFile: fileName => sys.readFile(fileName)
};
}
@@ -143,7 +355,7 @@ namespace ts {
}
}
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program {
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
let diagnostics = createDiagnosticCollection();
@@ -158,24 +370,46 @@ namespace ts {
let start = new Date().getTime();
host = host || createCompilerHost(options);
const resolveModuleNamesWorker =
host.resolveModuleNames ||
((moduleNames, containingFile) => map(moduleNames, moduleName => resolveModuleName(moduleName, containingFile, options, host).resolvedFileName));
let filesByName = createFileMap<SourceFile>(fileName => host.getCanonicalFileName(fileName));
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
// processing the root files.
if (!skipDefaultLib) {
processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib:*/ true);
if (oldProgram) {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
let oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
forEach(rootNames, name => processRootFile(name, false));
// Do not process the default library if:
// - The '--noLib' flag is used.
// - A 'no-default-lib' reference comment is encountered in
// processing the root files.
if (!skipDefaultLib) {
processRootFile(host.getDefaultLibFileName(options), true);
}
}
verifyCompilerOptions();
// unconditionally set oldProgram to undefined to prevent it from being captured in closure
oldProgram = undefined;
programTime += new Date().getTime() - start;
program = {
getRootFileNames: () => rootNames,
getSourceFile: getSourceFile,
getSourceFiles: () => files,
getCompilerOptions: () => options,
@@ -211,6 +445,82 @@ namespace ts {
return classifiableNames;
}
function tryReuseStructureFromOldProgram(): boolean {
if (!oldProgram) {
return false;
}
Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
let oldRootNames = oldProgram.getRootFileNames();
if (!arrayIsEqualTo(oldRootNames, rootNames)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
let newSourceFiles: SourceFile[] = [];
for (let oldSourceFile of oldProgram.getSourceFiles()) {
let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
return false;
}
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
// value of no-default-lib has changed
// this will affect if default library is injected into the list of files
return false;
}
// check tripleslash references
if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
// tripleslash references has changed
return false;
}
// check imports
collectExternalModuleReferences(newSourceFile);
if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
// imports has changed
return false;
}
if (resolveModuleNamesWorker) {
let moduleNames = map(newSourceFile.imports, name => name.text);
let resolutions = resolveModuleNamesWorker(moduleNames, newSourceFile.fileName);
// ensure that module resolution results are still correct
for (let i = 0; i < moduleNames.length; ++i) {
let oldResolution = getResolvedModuleFileName(oldSourceFile, moduleNames[i]);
if (oldResolution !== resolutions[i]) {
return false;
}
}
}
// pass the cache of module resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
}
else {
// file has no changes - use it as is
newSourceFile = oldSourceFile;
}
// if file has passed all checks it should be safe to reuse it
newSourceFiles.push(newSourceFile);
}
// update fileName -> file mapping
for (let file of newSourceFiles) {
filesByName.set(file.fileName, file);
}
files = newSourceFiles;
oldProgram.structureIsReused = true;
return true;
}
function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost {
return {
getCanonicalFileName: fileName => host.getCanonicalFileName(fileName),
@@ -253,7 +563,7 @@ namespace ts {
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
let emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(options.out ? undefined : sourceFile);
let emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out)? undefined : sourceFile);
let start = new Date().getTime();
@@ -370,16 +680,66 @@ namespace ts {
function processRootFile(fileName: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(fileName), isDefaultLib);
}
function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean {
return a.fileName === b.fileName;
}
function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean {
return a.text === b.text;
}
function collectExternalModuleReferences(file: SourceFile): void {
if (file.imports) {
return;
}
let imports: LiteralExpression[];
for (let node of file.statements) {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ExportDeclaration:
let moduleNameExpr = getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) {
break;
}
if (!(<LiteralExpression>moduleNameExpr).text) {
break;
}
(imports || (imports = [])).push(<LiteralExpression>moduleNameExpr);
break;
case SyntaxKind.ModuleDeclaration:
if ((<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
forEachChild((<ModuleDeclaration>node).body, node => {
if (isExternalModuleImportEqualsDeclaration(node) &&
getExternalModuleImportEqualsDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
let moduleName = <LiteralExpression>getExternalModuleImportEqualsDeclarationExpression(node);
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
if (moduleName) {
(imports || (imports = [])).push(moduleName);
}
}
});
}
break;
}
}
file.imports = imports || emptyArray;
}
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
let start: number;
let length: number;
let diagnosticArgument: string[];
if (refEnd !== undefined && refPos !== undefined) {
start = refPos;
length = refEnd - refPos;
}
let diagnostic: DiagnosticMessage;
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) {
@@ -411,8 +771,8 @@ namespace ts {
}
if (diagnostic) {
if (refFile) {
diagnostics.add(createFileDiagnostic(refFile, start, length, diagnostic, ...diagnosticArgument));
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
}
else {
diagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
@@ -421,7 +781,7 @@ namespace ts {
}
// Get source file from normalized fileName
function findSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile {
function findSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
let canonicalName = host.getCanonicalFileName(normalizeSlashes(fileName));
if (filesByName.contains(canonicalName)) {
// We've already looked for this file, use cached result
@@ -436,8 +796,8 @@ namespace ts {
// We haven't looked for this file, do so now and cache result
let file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile) {
diagnostics.add(createFileDiagnostic(refFile, refStart, refLength,
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
@@ -450,12 +810,15 @@ namespace ts {
// Set the source file for normalized absolute path
filesByName.set(canonicalAbsolutePath, file);
let basePath = getDirectoryPath(fileName);
if (!options.noResolve) {
let basePath = getDirectoryPath(fileName);
processReferencedFiles(file, basePath);
processImportedModules(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
file.isDefaultLib = true;
files.unshift(file);
@@ -473,8 +836,13 @@ namespace ts {
if (file && host.useCaseSensitiveFileNames()) {
let sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName;
if (canonicalName !== sourceFileName) {
diagnostics.add(createFileDiagnostic(refFile, refStart, refLength,
Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
}
else {
diagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
}
}
}
return file;
@@ -483,60 +851,33 @@ namespace ts {
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
let referencedFileName = isRootedDiskPath(ref.fileName) ? ref.fileName : combinePaths(basePath, ref.fileName);
processSourceFile(normalizePath(referencedFileName), /* isDefaultLib */ false, file, ref.pos, ref.end);
let referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
function processImportedModules(file: SourceFile, basePath: string) {
forEach(file.statements, node => {
if (node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.ExportDeclaration) {
let moduleNameExpr = getExternalModuleName(node);
if (moduleNameExpr && moduleNameExpr.kind === SyntaxKind.StringLiteral) {
let moduleNameText = (<LiteralExpression>moduleNameExpr).text;
if (moduleNameText) {
let searchPath = basePath;
let searchName: string;
while (true) {
searchName = normalizePath(combinePaths(searchPath, moduleNameText));
if (forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, moduleNameExpr))) {
break;
}
let parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
}
collectExternalModuleReferences(file);
if (file.imports.length) {
file.resolvedModules = {};
let moduleNames = map(file.imports, name => name.text);
let resolutions = resolveModuleNamesWorker(moduleNames, file.fileName);
for (let i = 0; i < file.imports.length; ++i) {
let resolution = resolutions[i];
setResolvedModuleName(file, moduleNames[i], resolution);
if (resolution && !options.noResolve) {
findModuleSourceFile(resolution, file.imports[i]);
}
}
else if (node.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
forEachChild((<ModuleDeclaration>node).body, node => {
if (isExternalModuleImportEqualsDeclaration(node) &&
getExternalModuleImportEqualsDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
let nameLiteral = <LiteralExpression>getExternalModuleImportEqualsDeclarationExpression(node);
let moduleName = nameLiteral.text;
if (moduleName) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
let searchName = normalizePath(combinePaths(basePath, moduleName));
forEach(supportedExtensions, extension => findModuleSourceFile(searchName + extension, nameLiteral));
}
}
});
}
});
}
else {
// no imports - drop cached module resolutions
file.resolvedModules = undefined;
}
return;
function findModuleSourceFile(fileName: string, nameLiteral: Expression) {
return findSourceFile(fileName, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos);
return findSourceFile(fileName, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end);
}
}
@@ -603,27 +944,31 @@ namespace ts {
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.declaration) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
}
if (options.noEmitOnError) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
}
if (options.out) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_out_cannot_be_specified_with_option_isolatedModules));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
}
if (options.outFile) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
}
}
if (options.inlineSourceMap) {
if (options.sourceMap) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceMap_cannot_be_specified_with_option_inlineSourceMap));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
}
if (options.mapRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_mapRoot_cannot_be_specified_with_option_inlineSourceMap));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
if (options.sourceRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceRoot_cannot_be_specified_with_option_inlineSourceMap));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap"));
}
}
@@ -634,18 +979,23 @@ namespace ts {
}
}
if (options.out && options.outFile) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourceMap_option));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
if (options.sourceRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourceMap_option));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
return;
}
let languageVersion = options.target || ScriptTarget.ES3;
let outFile = options.outFile || options.out;
let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (options.isolatedModules) {
@@ -675,7 +1025,7 @@ namespace ts {
if (options.outDir || // there is --outDir specified
options.sourceRoot || // there is --sourceRoot specified
(options.mapRoot && // there is --mapRoot specified and there would be multiple js files generated
(!options.out || firstExternalModuleSourceFile !== undefined))) {
(!outFile || firstExternalModuleSourceFile !== undefined))) {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
@@ -695,18 +1045,26 @@ namespace ts {
}
if (options.noEmit) {
if (options.out || options.outDir) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_out_or_outDir));
if (options.out) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
}
if (options.outFile) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
}
if (options.outDir) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
}
if (options.declaration) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified));
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
if (options.experimentalAsyncFunctions &&
+65 -12
View File
@@ -319,14 +319,21 @@ namespace ts {
}
/* @internal */
/**
* We assume the first line starts at position 0 and 'position' is non-negative.
*/
export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) {
let lineNumber = binarySearch(lineStarts, position);
if (lineNumber < 0) {
// If the actual position was not found,
// the binary search returns the negative value of the next line start
// the binary search returns the 2's-complement of the next line start
// e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
// then the search will return -2
// then the search will return -2.
//
// We want the index of the previous line start, so we subtract 1.
// Review 2's-complement if this is confusing.
lineNumber = ~lineNumber - 1;
Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
}
return {
line: lineNumber,
@@ -401,6 +408,9 @@ namespace ts {
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
case CharacterCodes.hash:
// Only if its the beginning can we have #! trivia
return pos === 0;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
@@ -461,6 +471,13 @@ namespace ts {
}
break;
case CharacterCodes.hash:
if (pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
continue;
}
break;
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
pos++;
@@ -528,13 +545,31 @@ namespace ts {
return pos;
}
// Extract comments from the given source text starting at the given position. If trailing is
// false, whitespace is skipped until the first line break and comments between that location
// and the next token are returned.If trailing is true, comments occurring between the given
// position and the next line break are returned.The return value is an array containing a
// TextRange for each comment. Single-line comment ranges include the beginning '//' characters
// but not the ending line break. Multi - line comment ranges include the beginning '/* and
// ending '*/' characters.The return value is undefined if no comments were found.
const shebangTriviaRegex = /^#!.*/;
function isShebangTrivia(text: string, pos: number) {
// Shebangs check must only be done at the start of the file
Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
function scanShebangTrivia(text: string, pos: number) {
let shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
/**
* Extract comments from text prefixing the token closest following `pos`.
* The return value is an array containing a TextRange for each comment.
* Single-line comment ranges include the beginning '//' characters but not the ending line break.
* Multi - line comment ranges include the beginning '/* and ending '<asterisk>/' characters.
* The return value is undefined if no comments were found.
* @param trailing
* If false, whitespace is skipped until the first line break and comments between that location
* and the next token are returned.
* If true, comments occurring between the given position and the next line break are returned.
*/
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
let collecting = trailing || pos === 0;
@@ -617,6 +652,13 @@ namespace ts {
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ true);
}
/** Optionally, get the shebang */
export function getShebang(text: string): string {
return shebangTriviaRegex.test(text)
? shebangTriviaRegex.exec(text)[0]
: undefined;
}
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean {
return ch >= CharacterCodes.A && ch <= CharacterCodes.Z || ch >= CharacterCodes.a && ch <= CharacterCodes.z ||
@@ -629,9 +671,8 @@ namespace ts {
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
// Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
@@ -1087,6 +1128,18 @@ namespace ts {
return token = SyntaxKind.EndOfFileToken;
}
let ch = text.charCodeAt(pos);
// Special handling for shebang
if (ch === CharacterCodes.hash && pos === 0 && isShebangTrivia(text, pos)) {
pos = scanShebangTrivia(text, pos);
if (skipTrivia) {
continue;
}
else {
return token = SyntaxKind.ShebangTrivia;
}
}
switch (ch) {
case CharacterCodes.lineFeed:
case CharacterCodes.carriageReturn:
+16 -14
View File
@@ -30,8 +30,8 @@ namespace ts {
declare var global: any;
declare var __filename: string;
declare var Buffer: {
new (str: string, encoding ?: string): any;
}
new (str: string, encoding?: string): any;
};
declare class Enumerator {
public atEnd(): boolean;
@@ -188,13 +188,13 @@ namespace ts {
};
}
function getNodeSystem(): System {
var _fs = require("fs");
var _path = require("path");
var _os = require('os');
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
var platform: string = _os.platform();
const platform: string = _os.platform();
// win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive
var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
const useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin";
function readFile(fileName: string, encoding?: string): string {
if (!_fs.existsSync(fileName)) {
@@ -228,7 +228,7 @@ namespace ts {
function writeFile(fileName: string, data: string, writeByteOrderMark?: boolean): void {
// If a BOM is required, emit one
if (writeByteOrderMark) {
data = '\uFEFF' + data;
data = "\uFEFF" + data;
}
_fs.writeFileSync(fileName, data, "utf8");
@@ -271,10 +271,10 @@ namespace ts {
newLine: _os.EOL,
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
write(s: string): void {
var buffer = new Buffer(s, 'utf8');
var offset: number = 0;
var toWrite: number = buffer.length;
var written = 0;
const buffer = new Buffer(s, "utf8");
let offset: number = 0;
let toWrite: number = buffer.length;
let written = 0;
// 1 is a standard descriptor for stdout
while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) {
offset += written;
@@ -297,7 +297,7 @@ namespace ts {
}
callback(fileName);
};
}
},
resolvePath: function (path: string): string {
return _path.resolve(path);
@@ -334,7 +334,9 @@ namespace ts {
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
else if (typeof module !== "undefined" && module.exports) {
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
// process and process.nextTick checks if current environment is node-like
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
else {
+81 -11
View File
@@ -3,7 +3,7 @@
namespace ts {
export interface SourceFile {
fileWatcher: FileWatcher;
fileWatcher?: FileWatcher;
}
/**
@@ -14,7 +14,7 @@ namespace ts {
let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, 'en', 'ja-jp'));
errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
return false;
}
@@ -49,7 +49,7 @@ namespace ts {
}
// TODO: Add codePage support for readFile?
let fileContents = '';
let fileContents = "";
try {
fileContents = sys.readFile(filePath);
}
@@ -159,6 +159,11 @@ namespace ts {
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (commandLine.options.init) {
writeConfigFile(commandLine.options, commandLine.fileNames);
return sys.exit(ExitStatus.Success);
}
if (commandLine.options.version) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Version_0, ts.version));
return sys.exit(ExitStatus.Success);
@@ -245,7 +250,7 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Compilation_complete_Watching_for_file_changes));
}
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError ?: (message: string) => void) {
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) {
// Return existing SourceFile object if one is available
if (cachedProgram) {
let sourceFile = cachedProgram.getSourceFile(fileName);
@@ -355,22 +360,23 @@ namespace ts {
return { program, exitStatus };
function compileProgram(): ExitStatus {
// First get any syntactic errors.
let diagnostics = program.getSyntacticDiagnostics();
reportDiagnostics(diagnostics);
let diagnostics: Diagnostic[];
// First get and report any syntactic errors.
diagnostics = program.getSyntacticDiagnostics();
// If we didn't have any syntactic errors, then also try getting the global and
// semantic errors.
if (diagnostics.length === 0) {
let diagnostics = program.getGlobalDiagnostics();
reportDiagnostics(diagnostics);
diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics());
if (diagnostics.length === 0) {
let diagnostics = program.getSemanticDiagnostics();
reportDiagnostics(diagnostics);
diagnostics = program.getSemanticDiagnostics();
}
}
reportDiagnostics(diagnostics);
// If the user doesn't want us to emit, then we're done at this point.
if (compilerOptions.noEmit) {
return diagnostics.length
@@ -488,6 +494,70 @@ namespace ts {
return Array(paddingLength + 1).join(" ");
}
}
function writeConfigFile(options: CompilerOptions, fileNames: string[]) {
let currentDirectory = sys.getCurrentDirectory();
let file = combinePaths(currentDirectory, 'tsconfig.json');
if (sys.fileExists(file)) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file));
}
else {
let compilerOptions = extend(options, defaultInitCompilerOptions);
let configurations: any = {
compilerOptions: serializeCompilerOptions(compilerOptions),
exclude: ["node_modules"]
};
if (fileNames && fileNames.length) {
// only set the files property if we have at least one file
configurations.files = fileNames;
}
sys.writeFile(file, JSON.stringify(configurations, undefined, 4));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file));
}
return;
function serializeCompilerOptions(options: CompilerOptions): Map<string|number|boolean> {
let result: Map<string|number|boolean> = {};
let optionsNameMap = getOptionNameMap().optionNameMap;
for (let name in options) {
if (hasProperty(options, name)) {
let value = options[name];
switch (name) {
case "init":
case "watch":
case "version":
case "help":
case "project":
break;
default:
let optionDefinition = optionsNameMap[name.toLowerCase()];
if (optionDefinition) {
if (typeof optionDefinition.type === "string") {
// string, number or boolean
result[name] = value;
}
else {
// Enum
let typeMap = <Map<number>>optionDefinition.type;
for (let key in typeMap) {
if (hasProperty(typeMap, key)) {
if (typeMap[key] === value)
result[name] = key;
}
}
}
}
break;
}
}
}
return result;
}
}
}
ts.executeCommandLine(ts.sys.args);
+74 -13
View File
@@ -9,6 +9,7 @@ namespace ts {
contains(fileName: string): boolean;
remove(fileName: string): void;
forEachValue(f: (v: T) => void): void;
clear(): void;
}
export interface TextRange {
@@ -17,6 +18,7 @@ namespace ts {
}
// token > SyntaxKind.Identifer => token is a keyword
// Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
export const enum SyntaxKind {
Unknown,
EndOfFileToken,
@@ -24,6 +26,8 @@ namespace ts {
MultiLineCommentTrivia,
NewLineTrivia,
WhitespaceTrivia,
// We detect and preserve #! on the first line
ShebangTrivia,
// We detect and provide better error recovery when we encounter a git merge marker. This
// allows us to edit files with git-conflict markers in them in a much more pleasant manner.
ConflictMarkerTrivia,
@@ -583,9 +587,9 @@ namespace ts {
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
* Examples:
* FunctionDeclaration
* MethodDeclaration
* AccessorDeclaration
* - FunctionDeclaration
* - MethodDeclaration
* - AccessorDeclaration
*/
export interface FunctionLikeDeclaration extends SignatureDeclaration {
_functionLikeDeclarationBrand: any;
@@ -1240,6 +1244,10 @@ namespace ts {
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
// this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
/* @internal */
renamedDependencies?: Map<string>;
/**
* lib.d.ts should have a reference comment like
@@ -1272,8 +1280,12 @@ namespace ts {
// Stores a line map for the file.
// This field should never be used directly to obtain line map, use getLineMap function instead.
/* @internal */ lineMap: number[];
/* @internal */ classifiableNames?: Map<string>;
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
// It is used to resolve module names in the checker.
// Content of this fiels should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<string>;
/* @internal */ imports: LiteralExpression[];
}
export interface ScriptReferenceHost {
@@ -1282,7 +1294,7 @@ namespace ts {
getCurrentDirectory(): string;
}
export interface ParseConfigHost {
export interface ParseConfigHost extends ModuleResolutionHost {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
@@ -1300,6 +1312,12 @@ namespace ts {
}
export interface Program extends ScriptReferenceHost {
/**
* Get a list of root file names that were passed to a 'createProgram'
*/
getRootFileNames(): string[]
/**
* Get a list of files in the program
*/
@@ -1340,6 +1358,9 @@ namespace ts {
/* @internal */ getIdentifierCount(): number;
/* @internal */ getSymbolCount(): number;
/* @internal */ getTypeCount(): number;
// For testing purposes only.
/* @internal */ structureIsReused?: boolean;
}
export interface SourceMapSpan {
@@ -1390,6 +1411,7 @@ namespace ts {
/* @internal */ sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
}
/* @internal */
export interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
@@ -1431,6 +1453,7 @@ namespace ts {
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -1529,8 +1552,8 @@ namespace ts {
export interface SymbolAccessiblityResult extends SymbolVisibilityResult {
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator
* metadata */
/* @internal */
export enum TypeReferenceSerializationKind {
@@ -1574,7 +1597,8 @@ namespace ts {
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getBlockScopedVariableId(node: Identifier): number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind;
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
}
export const enum SymbolFlags {
@@ -1768,7 +1792,9 @@ namespace ts {
ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type
/* @internal */
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
ESSymbol = 0x00800000, // Type of symbol primitive introduced in ES6
/* @internal */
ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type
ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
@@ -1777,10 +1803,12 @@ namespace ts {
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
/* @internal */
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral
RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral,
/* @internal */
PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
// Properties common to all types
@@ -1925,6 +1953,7 @@ namespace ts {
/* @internal */
export interface TypeMapper {
(t: TypeParameter): Type;
instantiations?: Type[]; // Cache of instantiations created using this type mapper.
context?: InferenceContext; // The inference context this mapper was created from.
// Only inference mappers have this set (in createInferenceMapper).
// The identity mapper and regular instantiation mappers do not need it.
@@ -1981,7 +2010,12 @@ namespace ts {
Error,
Message,
}
export const enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2
}
export interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
@@ -1989,6 +2023,7 @@ namespace ts {
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
@@ -2005,6 +2040,7 @@ namespace ts {
noLib?: boolean;
noResolve?: boolean;
out?: string;
outFile?: string;
outDir?: string;
preserveConstEnums?: boolean;
project?: string;
@@ -2012,6 +2048,7 @@ namespace ts {
rootDir?: string;
sourceMap?: boolean;
sourceRoot?: string;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
version?: boolean;
@@ -2020,6 +2057,7 @@ namespace ts {
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
emitDecoratorMetadata?: boolean;
moduleResolution?: ModuleResolutionKind
/* @internal */ stripInternal?: boolean;
// Skip checking lib.d.ts to help speed up tests.
@@ -2220,9 +2258,23 @@ namespace ts {
byteOrderMark = 0xFEFF,
tab = 0x09, // \t
verticalTab = 0x0B, // \v
}
export interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
// readFile function is used to read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json'
// to determine location of bundled typings for node module
readFile(fileName: string): string;
}
export interface ResolvedModule {
resolvedFileName: string;
failedLookupLocations: string[];
}
export type ModuleNameResolver = (moduleName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => ResolvedModule;
export interface CompilerHost {
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
@@ -2231,6 +2283,15 @@ namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
/*
* CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
* module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
* will appply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
* If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
* 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
}
export interface TextSpan {
+78 -23
View File
@@ -80,6 +80,41 @@ namespace ts {
return node.end - node.pos;
}
export function arrayIsEqualTo<T>(arr1: T[], arr2: T[], comparer?: (a: T, b: T) => boolean): boolean {
if (!arr1 || !arr2) {
return arr1 === arr2;
}
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; ++i) {
let equals = comparer ? comparer(arr1[i], arr2[i]) : arr1[i] === arr2[i];
if (!equals) {
return false;
}
}
return true;
}
export function hasResolvedModuleName(sourceFile: SourceFile, moduleNameText: string): boolean {
return sourceFile.resolvedModules && hasProperty(sourceFile.resolvedModules, moduleNameText);
}
export function getResolvedModuleFileName(sourceFile: SourceFile, moduleNameText: string): string {
return hasResolvedModuleName(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined;
}
export function setResolvedModuleName(sourceFile: SourceFile, moduleNameText: string, resolvedFileName: string): void {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = {};
}
sourceFile.resolvedModules[moduleNameText] = resolvedFileName;
}
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
@@ -205,7 +240,7 @@ namespace ts {
// Make an identifier from an external module name by extracting the string after the last "/" and replacing
// all non-alphanumeric characters with underscores
export function makeIdentifierFromModuleName(moduleName: string): string {
return getBaseFileName(moduleName).replace(/\W/g, "_");
return getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
}
export function isBlockOrCatchScoped(declaration: Declaration) {
@@ -434,24 +469,15 @@ namespace ts {
}
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile) {
// If parameter/type parameter, the prev token trailing comments are part of this node too
if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
// e.g. (/** blah */ a, /** blah */ b);
// e.g.: (
// /** blah */ a,
// /** blah */ b);
return concatenate(
getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
getLeadingCommentRanges(sourceFileOfNode.text, node.pos));
}
else {
return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) {
return filter(getLeadingCommentRangesOfNode(node, sourceFileOfNode), isJsDocComment);
let commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ?
concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
getLeadingCommentRangesOfNode(node, sourceFileOfNode);
return filter(commentRanges, isJsDocComment);
function isJsDocComment(comment: CommentRange) {
// True if the comment starts with '/**' but not if it is '/**/'
@@ -638,11 +664,11 @@ namespace ts {
return false;
}
export function isAccessor(node: Node): boolean {
export function isAccessor(node: Node): node is AccessorDeclaration {
return node && (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor);
}
export function isClassLike(node: Node): boolean {
export function isClassLike(node: Node): node is ClassLikeDeclaration {
return node && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression);
}
@@ -668,6 +694,20 @@ namespace ts {
return false;
}
export function introducesArgumentsExoticObject(node: Node) {
switch (node.kind) {
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
return true;
}
return false;
}
export function isFunctionBlock(node: Node) {
return node && node.kind === SyntaxKind.Block && isFunctionLike(node.parent);
}
@@ -1027,6 +1067,7 @@ namespace ts {
case SyntaxKind.ComputedPropertyName:
return node === (<ComputedPropertyName>parent).expression;
case SyntaxKind.Decorator:
case SyntaxKind.JsxExpression:
return true;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>parent).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent, getAncestorOrSelf, offset + 1);
@@ -1077,15 +1118,13 @@ namespace ts {
if (node) {
switch (node.kind) {
case SyntaxKind.Parameter:
return (<ParameterDeclaration>node).questionToken !== undefined;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
return (<MethodDeclaration>node).questionToken !== undefined;
case SyntaxKind.ShorthandPropertyAssignment:
case SyntaxKind.PropertyAssignment:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
return (<PropertyDeclaration>node).questionToken !== undefined;
return (<ParameterDeclaration | MethodDeclaration | PropertyDeclaration>node).questionToken !== undefined;
}
}
@@ -1517,6 +1556,22 @@ namespace ts {
return isFunctionLike(n) || n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.SourceFile;
}
export function cloneEntityName(node: EntityName): EntityName {
if (node.kind === SyntaxKind.Identifier) {
let clone = <Identifier>createSynthesizedNode(SyntaxKind.Identifier);
clone.text = (<Identifier>node).text;
return clone;
}
else {
let clone = <QualifiedName>createSynthesizedNode(SyntaxKind.QualifiedName);
clone.left = cloneEntityName((<QualifiedName>node).left);
clone.left.parent = clone;
clone.right = <Identifier>cloneEntityName((<QualifiedName>node).right);
clone.right.parent = clone;
return clone;
}
}
export function nodeIsSynthesized(node: Node): boolean {
return node.pos === -1;
}
@@ -1805,7 +1860,7 @@ namespace ts {
export function shouldEmitToOwnFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
if (!isDeclarationFile(sourceFile)) {
if ((isExternalModule(sourceFile) || !compilerOptions.out)) {
if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) {
// 1. in-browser single file compilation scenario
// 2. non .js file
return compilerOptions.isolatedModules || !fileExtensionIs(sourceFile.fileName, ".js");
@@ -1961,7 +2016,7 @@ namespace ts {
function writeTrimmedCurrentLine(pos: number, nextLineStart: number) {
let end = Math.min(comment.end, nextLineStart - 1);
let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, '');
let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
if (currentLineText) {
// trimmed forward and ending spaces text
writer.write(currentLineText);
+60 -60
View File
@@ -1,6 +1,6 @@
/// <reference path='harness.ts' />
/// <reference path='runnerbase.ts' />
/// <reference path='typeWriter.ts' />
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/// <reference path="typeWriter.ts" />
const enum CompilerTestType {
Conformance,
@@ -9,7 +9,7 @@ const enum CompilerTestType {
}
class CompilerBaselineRunner extends RunnerBase {
private basePath = 'tests/cases';
private basePath = "tests/cases";
private testSuiteName: string;
private errors: boolean;
private emit: boolean;
@@ -25,21 +25,21 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = true;
this.output = true;
if (testType === CompilerTestType.Conformance) {
this.testSuiteName = 'conformance';
this.testSuiteName = "conformance";
}
else if (testType === CompilerTestType.Regressions) {
this.testSuiteName = 'compiler';
this.testSuiteName = "compiler";
}
else if (testType === CompilerTestType.Test262) {
this.testSuiteName = 'test262';
this.testSuiteName = "test262";
} else {
this.testSuiteName = 'compiler'; // default to this for historical reasons
this.testSuiteName = "compiler"; // default to this for historical reasons
}
this.basePath += '/' + this.testSuiteName;
this.basePath += "/" + this.testSuiteName;
}
public checkTestCodeOutput(fileName: string) {
describe('compiler tests for ' + fileName, () => {
describe("compiler tests for " + fileName, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let justName: string;
@@ -64,14 +64,14 @@ class CompilerBaselineRunner extends RunnerBase {
let createNewInstance = false;
before(() => {
justName = fileName.replace(/^.*[\\\/]/, ''); // strips the fileName from the path.
justName = fileName.replace(/^.*[\\\/]/, ""); // strips the fileName from the path.
content = Harness.IO.readFile(fileName);
testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, fileName);
units = testCaseContent.testUnitData;
tcSettings = testCaseContent.settings;
createNewInstance = false;
lastUnit = units[units.length - 1];
rootDir = lastUnit.originalFilePath.indexOf('conformance') === -1 ? 'tests/cases/compiler/' : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf('/')) + '/';
rootDir = lastUnit.originalFilePath.indexOf("conformance") === -1 ? "tests/cases/compiler/" : lastUnit.originalFilePath.substring(0, lastUnit.originalFilePath.lastIndexOf("/")) + "/";
harnessCompiler = Harness.Compiler.getCompiler();
// We need to assemble the list of input files for the compiler and other related files on the 'filesystem' (ie in a multi-file test)
// If the last file in a test uses require or a triple slash reference we'll assume all other files will be brought in via references,
@@ -106,7 +106,7 @@ class CompilerBaselineRunner extends RunnerBase {
eventually to remove this limitation. */
for (let i = 0; i < tcSettings.length; ++i) {
// noImplicitAny is passed to getCompiler, but target is just passed in the settings blob to setCompilerSettings
if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === 'target')) {
if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === "target")) {
harnessCompiler = Harness.Compiler.getCompiler();
harnessCompiler.setCompilerSettings(tcSettings);
createNewInstance = true;
@@ -148,9 +148,9 @@ class CompilerBaselineRunner extends RunnerBase {
}
// check errors
it('Correct errors for ' + fileName, () => {
it("Correct errors for " + fileName, () => {
if (this.errors) {
Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.tsx?$/, '.errors.txt'), (): string => {
Harness.Baseline.runBaseline("Correct errors for " + fileName, justName.replace(/\.tsx?$/, ".errors.txt"), (): string => {
if (result.errors.length === 0) return null;
return getErrorBaseline(toBeCompiled, otherFiles, result);
});
@@ -158,12 +158,12 @@ class CompilerBaselineRunner extends RunnerBase {
});
// Source maps?
it('Correct sourcemap content for ' + fileName, () => {
it("Correct sourcemap content for " + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => {
let record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn"t required.
return null;
}
return record;
@@ -171,35 +171,35 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it('Correct JS output for ' + fileName, () => {
if (!ts.fileExtensionIs(lastUnit.name, '.d.ts') && this.emit) {
it("Correct JS output for " + fileName, () => {
if (!ts.fileExtensionIs(lastUnit.name, ".d.ts") && this.emit) {
if (result.files.length === 0 && result.errors.length === 0) {
throw new Error('Expected at least one js file to be emitted or at least one error to be created.');
throw new Error("Expected at least one js file to be emitted or at least one error to be created.");
}
// check js output
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => {
let tsCode = '';
Harness.Baseline.runBaseline("Correct JS output for " + fileName, justName.replace(/\.tsx?/, ".js"), () => {
let tsCode = "";
let tsSources = otherFiles.concat(toBeCompiled);
if (tsSources.length > 1) {
tsCode += '//// [' + fileName + '] ////\r\n\r\n';
tsCode += "//// [" + fileName + "] ////\r\n\r\n";
}
for (let i = 0; i < tsSources.length; i++) {
tsCode += '//// [' + Harness.Path.getFileName(tsSources[i].unitName) + ']\r\n';
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? '\r\n' : '');
tsCode += "//// [" + Harness.Path.getFileName(tsSources[i].unitName) + "]\r\n";
tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? "\r\n" : "");
}
let jsCode = '';
let jsCode = "";
for (let i = 0; i < result.files.length; i++) {
jsCode += '//// [' + Harness.Path.getFileName(result.files[i].fileName) + ']\r\n';
jsCode += "//// [" + Harness.Path.getFileName(result.files[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.files[i]);
jsCode += result.files[i].code;
}
if (result.declFilesCode.length > 0) {
jsCode += '\r\n\r\n';
jsCode += "\r\n\r\n";
for (let i = 0; i < result.declFilesCode.length; i++) {
jsCode += '//// [' + Harness.Path.getFileName(result.declFilesCode[i].fileName) + ']\r\n';
jsCode += "//// [" + Harness.Path.getFileName(result.declFilesCode[i].fileName) + "]\r\n";
jsCode += getByteOrderMarkText(result.declFilesCode[i]);
jsCode += result.declFilesCode[i].code;
}
@@ -210,13 +210,13 @@ class CompilerBaselineRunner extends RunnerBase {
}, options);
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
jsCode += '\r\n\r\n//// [DtsFileErrors]\r\n';
jsCode += '\r\n\r\n';
jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n";
jsCode += "\r\n\r\n";
jsCode += getErrorBaseline(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles, declFileCompilationResult.declResult);
}
if (jsCode.length > 0) {
return tsCode + '\r\n\r\n' + jsCode;
return tsCode + "\r\n\r\n" + jsCode;
} else {
return null;
}
@@ -224,28 +224,28 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it('Correct Sourcemap output for ' + fileName, () => {
it("Correct Sourcemap output for " + fileName, () => {
if (options.inlineSourceMap) {
if (result.sourceMaps.length > 0) {
throw new Error('No sourcemap files should be generated if inlineSourceMaps was set.');
throw new Error("No sourcemap files should be generated if inlineSourceMaps was set.");
}
return null;
}
else if (options.sourceMap) {
if (result.sourceMaps.length !== result.files.length) {
throw new Error('Number of sourcemap files should be same as js files.');
throw new Error("Number of sourcemap files should be same as js files.");
}
Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.tsx?/, '.js.map'), () => {
Harness.Baseline.runBaseline("Correct Sourcemap output for " + fileName, justName.replace(/\.tsx?/, ".js.map"), () => {
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
// We need to return null here or the runBaseLine will actually create a empty file.
// Baselining isn't required here because there is no output.
return null;
}
let sourceMapCode = '';
let sourceMapCode = "";
for (let i = 0; i < result.sourceMaps.length; i++) {
sourceMapCode += '//// [' + Harness.Path.getFileName(result.sourceMaps[i].fileName) + ']\r\n';
sourceMapCode += "//// [" + Harness.Path.getFileName(result.sourceMaps[i].fileName) + "]\r\n";
sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]);
sourceMapCode += result.sourceMaps[i].code;
}
@@ -255,7 +255,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
it('Correct type/symbol baselines for ' + fileName, () => {
it("Correct type/symbol baselines for " + fileName, () => {
if (fileName.indexOf("APISample") >= 0) {
return;
}
@@ -317,15 +317,15 @@ class CompilerBaselineRunner extends RunnerBase {
let fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
let pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
let fullExtension = isSymbolBaseLine ? '.symbols' : '.types';
let pullExtension = isSymbolBaseLine ? '.symbols.pull' : '.types.pull';
let fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
let pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
@@ -334,7 +334,7 @@ class CompilerBaselineRunner extends RunnerBase {
let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
let codeLines = file.content.split('\n');
let codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
@@ -354,30 +354,30 @@ class CompilerBaselineRunner extends RunnerBase {
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push('=== ' + file.unitName + ' ===\r\n');
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
let currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + '\r\n');
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
let typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push('>' + ty + '\r\n');
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === '')) {
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push('\r\n');
typeLines.push("\r\n");
}
}
}
else {
typeLines.push('No type information for this code.');
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join('');
return typeLines.join("");
}
}
});
@@ -385,7 +385,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
public initializeTests() {
describe(this.testSuiteName + ' tests', () => {
describe(this.testSuiteName + " tests", () => {
describe("Setup compiler for compiler baselines", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
this.parseOptions();
@@ -416,23 +416,23 @@ class CompilerBaselineRunner extends RunnerBase {
this.decl = false;
this.output = false;
let opts = this.options.split(',');
let opts = this.options.split(",");
for (let i = 0; i < opts.length; i++) {
switch (opts[i]) {
case 'error':
case "error":
this.errors = true;
break;
case 'emit':
case "emit":
this.emit = true;
break;
case 'decl':
case "decl":
this.decl = true;
break;
case 'output':
case "output":
this.output = true;
break;
default:
throw new Error('unsupported flag');
throw new Error("unsupported flag");
}
}
}
+365 -244
View File
File diff suppressed because it is too large Load Diff
+42 -37
View File
@@ -1,10 +1,11 @@
///<reference path='fourslash.ts' />
///<reference path='harness.ts'/>
///<reference path='runnerbase.ts' />
///<reference path="fourslash.ts" />
///<reference path="harness.ts"/>
///<reference path="runnerbase.ts" />
const enum FourSlashTestType {
Native,
Shims,
ShimsWithPreprocess,
Server
}
@@ -16,16 +17,20 @@ class FourSlashRunner extends RunnerBase {
super();
switch (testType) {
case FourSlashTestType.Native:
this.basePath = 'tests/cases/fourslash';
this.testSuiteName = 'fourslash';
this.basePath = "tests/cases/fourslash";
this.testSuiteName = "fourslash";
break;
case FourSlashTestType.Shims:
this.basePath = 'tests/cases/fourslash/shims';
this.testSuiteName = 'fourslash-shims';
this.basePath = "tests/cases/fourslash/shims";
this.testSuiteName = "fourslash-shims";
break;
case FourSlashTestType.ShimsWithPreprocess:
this.basePath = 'tests/cases/fourslash/shims-pp';
this.testSuiteName = 'fourslash-shims-pp';
break;
case FourSlashTestType.Server:
this.basePath = 'tests/cases/fourslash/server';
this.testSuiteName = 'fourslash-server';
this.basePath = "tests/cases/fourslash/server";
this.testSuiteName = "fourslash-server";
break;
}
}
@@ -35,25 +40,25 @@ class FourSlashRunner extends RunnerBase {
this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false });
}
describe(this.testSuiteName + ' tests', () => {
describe(this.testSuiteName + " tests", () => {
this.tests.forEach((fn: string) => {
describe(fn, () => {
fn = ts.normalizeSlashes(fn);
let justName = fn.replace(/^.*[\\\/]/, '');
let justName = fn.replace(/^.*[\\\/]/, "");
// Convert to relative path
let testIndex = fn.indexOf('tests/');
let testIndex = fn.indexOf("tests/");
if (testIndex >= 0) fn = fn.substr(testIndex);
if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) {
it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => {
it(this.testSuiteName + " test " + justName + " runs correctly", () => {
FourSlash.runFourSlashTest(this.basePath, this.testType, fn);
});
}
});
});
describe('Generate Tao XML', () => {
describe("Generate Tao XML", () => {
let invalidReasons: any = {};
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
@@ -69,37 +74,37 @@ class FourSlashRunner extends RunnerBase {
invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1);
let lines: string[] = [];
lines.push('<!-- Blocked Test Report');
lines.push("<!-- Blocked Test Report");
invalidReport.forEach((reasonAndCount) => {
lines.push(reasonAndCount.count + ' tests blocked by ' + reasonAndCount.reason);
lines.push(reasonAndCount.count + " tests blocked by " + reasonAndCount.reason);
});
lines.push('-->');
lines.push('<TaoTest xmlns="http://microsoft.com/schemas/VSLanguages/TAO">');
lines.push(' <InitTest>');
lines.push(' <StartTarget />');
lines.push(' </InitTest>');
lines.push(' <ScenarioList>');
lines.push("-->");
lines.push("<TaoTest xmlns=\"http://microsoft.com/schemas/VSLanguages/TAO\">");
lines.push(" <InitTest>");
lines.push(" <StartTarget />");
lines.push(" </InitTest>");
lines.push(" <ScenarioList>");
FourSlash.xmlData.forEach(xml => {
if (xml.invalidReason !== null) {
lines.push('<!-- Skipped ' + xml.originalName + ', reason: ' + xml.invalidReason + ' -->');
lines.push("<!-- Skipped " + xml.originalName + ", reason: " + xml.invalidReason + " -->");
} else {
lines.push(' <Scenario Name="' + xml.originalName + '">');
lines.push(" <Scenario Name=\"" + xml.originalName + "\">");
xml.actions.forEach(action => {
lines.push(' ' + action);
lines.push(" " + action);
});
lines.push(' </Scenario>');
lines.push(" </Scenario>");
}
});
lines.push(' </ScenarioList>');
lines.push(' <CleanupScenario>');
lines.push(' <CloseAllDocuments />');
lines.push(' <CleanupCreatedFiles />');
lines.push(' </CleanupScenario>');
lines.push(' <CleanupTest>');
lines.push(' <CloseTarget />');
lines.push(' </CleanupTest>');
lines.push('</TaoTest>');
Harness.IO.writeFile('built/local/fourslash.xml', lines.join('\r\n'));
lines.push(" </ScenarioList>");
lines.push(" <CleanupScenario>");
lines.push(" <CloseAllDocuments />");
lines.push(" <CleanupCreatedFiles />");
lines.push(" </CleanupScenario>");
lines.push(" <CleanupTest>");
lines.push(" <CloseTarget />");
lines.push(" </CleanupTest>");
lines.push("</TaoTest>");
Harness.IO.writeFile("built/local/fourslash.xml", lines.join("\r\n"));
});
});
}
@@ -108,6 +113,6 @@ class FourSlashRunner extends RunnerBase {
class GeneratedFourslashRunner extends FourSlashRunner {
constructor(testType: FourSlashTestType) {
super(testType);
this.basePath += '/generated/';
this.basePath += "/generated/";
}
}
+289 -213
View File
File diff suppressed because it is too large Load Diff
+43 -9
View File
@@ -1,7 +1,7 @@
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='..\server\client.ts' />
/// <reference path='harness.ts' />
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\shims.ts" />
/// <reference path="..\server\client.ts" />
/// <reference path="harness.ts" />
module Harness.LanguageService {
export class ScriptInfo {
@@ -203,9 +203,35 @@ module Harness.LanguageService {
/// Shim adapter
class ShimLanguageServiceHost extends LanguageServiceAdapterHost implements ts.LanguageServiceShimHost, ts.CoreServicesShimHost {
private nativeHost: NativeLanguageServiceHost;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
public getModuleResolutionsForFile: (fileName: string)=> string;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
this.nativeHost = new NativeLanguageServiceHost(cancellationToken, options);
if (preprocessToResolve) {
let compilerOptions = this.nativeHost.getCompilationSettings()
let moduleResolutionHost: ts.ModuleResolutionHost = {
fileExists: fileName => this.getScriptInfo(fileName) !== undefined,
readFile: fileName => {
let scriptInfo = this.getScriptInfo(fileName);
return scriptInfo && scriptInfo.content;
}
};
this.getModuleResolutionsForFile = (fileName) => {
let scriptInfo = this.getScriptInfo(fileName);
let preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ true);
let imports: ts.Map<string> = {};
for (let module of preprocessInfo.importedFiles) {
let resolutionInfo = ts.resolveModuleName(module.fileName, fileName, compilerOptions, moduleResolutionHost);
if (resolutionInfo.resolvedFileName) {
imports[module.fileName] = resolutionInfo.resolvedFileName;
}
}
return JSON.stringify(imports);
}
}
}
getFilenames(): string[] { return this.nativeHost.getFilenames(); }
@@ -229,7 +255,11 @@ module Harness.LanguageService {
readDirectory(rootDir: string, extension: string): string {
throw new Error("NYI");
}
fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; }
readFile(fileName: string) {
let snapshot = this.nativeHost.getScriptSnapshot(fileName);
return snapshot && snapshot.getText(0, snapshot.getLength());
}
log(s: string): void { this.nativeHost.log(s); }
trace(s: string): void { this.nativeHost.trace(s); }
error(s: string): void { this.nativeHost.error(s); }
@@ -242,7 +272,7 @@ module Harness.LanguageService {
throw new Error("NYI");
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split("\n");
let entries: ts.ClassificationInfo[] = [];
let i = 0;
let position = 0;
@@ -381,6 +411,9 @@ module Harness.LanguageService {
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: ts.FormatCodeOptions): ts.TextChange[] {
return unwrapJSONCallResult(this.shim.getFormattingEditsAfterKeystroke(fileName, position, key, JSON.stringify(options)));
}
getDocCommentTemplateAtPosition(fileName: string, position: number): ts.TextInsertion {
return unwrapJSONCallResult(this.shim.getDocCommentTemplateAtPosition(fileName, position));
}
getEmitOutput(fileName: string): ts.EmitOutput {
return unwrapJSONCallResult(this.shim.getEmitOutput(fileName));
}
@@ -396,8 +429,8 @@ module Harness.LanguageService {
export class ShimLanugageServiceAdapter implements LanguageServiceAdapter {
private host: ShimLanguageServiceHost;
private factory: ts.TypeScriptServicesFactory;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new ShimLanguageServiceHost(cancellationToken, options);
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
this.host = new ShimLanguageServiceHost(preprocessToResolve, cancellationToken, options);
this.factory = new TypeScript.Services.TypeScriptServicesFactory();
}
getHost() { return this.host; }
@@ -416,6 +449,7 @@ module Harness.LanguageService {
let convertResult: ts.PreProcessedFileInfo = {
referencedFiles: [],
importedFiles: [],
ambientExternalModules: [],
isLibFile: shimResult.isLibFile
};
+30 -24
View File
@@ -73,7 +73,7 @@ interface PlaybackControl {
module Playback {
let recordLog: IOLog = undefined;
let replayLog: IOLog = undefined;
let recordLogFileNameBase = '';
let recordLogFileNameBase = "";
interface Memoized<T> {
(s: string): T;
@@ -93,13 +93,13 @@ module Playback {
return run;
}
export interface PlaybackSystem extends ts.System, PlaybackControl { }
export interface PlaybackIO extends Harness.IO, PlaybackControl { }
function createEmptyLog(): IOLog {
return {
timestamp: (new Date()).toString(),
arguments: [],
currentDirectory: '',
currentDirectory: "",
filesRead: [],
filesWritten: [],
filesDeleted: [],
@@ -110,7 +110,7 @@ module Playback {
dirExists: [],
dirsCreated: [],
pathsResolved: [],
executingPath: ''
executingPath: ""
};
}
@@ -170,7 +170,7 @@ module Playback {
if (defaultValue !== undefined) {
return defaultValue;
} else {
throw new Error('No matching result in log array for: ' + JSON.stringify(expectedFields));
throw new Error("No matching result in log array for: " + JSON.stringify(expectedFields));
}
}
return results[0].result;
@@ -195,7 +195,7 @@ module Playback {
}
// If we got here, we didn't find a match
if (defaultValue === undefined) {
throw new Error('No matching result in log array for path: ' + expectedPath);
throw new Error("No matching result in log array for path: " + expectedPath);
} else {
return defaultValue;
}
@@ -203,7 +203,7 @@ module Playback {
let pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
let key = left + '-~~-' + right;
let key = left + "-~~-" + right;
function areSame(a: string, b: string) {
return ts.normalizeSlashes(a).toLowerCase() === ts.normalizeSlashes(b).toLowerCase();
}
@@ -223,8 +223,8 @@ module Playback {
// console.log("Swallowed write operation during replay: " + name);
}
export function wrapSystem(underlying: ts.System): PlaybackSystem {
let wrapper: PlaybackSystem = <any>{};
export function wrapIO(underlying: Harness.IO): PlaybackIO {
let wrapper: PlaybackIO = <any>{};
initWrapper(wrapper, underlying);
wrapper.startReplayFromFile = logFn => {
@@ -233,24 +233,30 @@ module Playback {
wrapper.endRecord = () => {
if (recordLog !== undefined) {
let i = 0;
let fn = () => recordLogFileNameBase + i + '.json';
let fn = () => recordLogFileNameBase + i + ".json";
while (underlying.fileExists(fn())) i++;
underlying.writeFile(fn(), JSON.stringify(recordLog));
recordLog = undefined;
}
};
Object.defineProperty(wrapper, 'args', {
get() {
if (replayLog !== undefined) {
return replayLog.arguments;
} else if (recordLog !== undefined) {
recordLog.arguments = underlying.args;
}
return underlying.args;
wrapper.args = () => {
if (replayLog !== undefined) {
return replayLog.arguments;
} else if (recordLog !== undefined) {
recordLog.arguments = underlying.args();
}
});
return underlying.args();
}
wrapper.newLine = () => underlying.newLine();
wrapper.useCaseSensitiveFileNames = () => underlying.useCaseSensitiveFileNames();
wrapper.directoryName = (path): string => { throw new Error("NotSupported"); };
wrapper.createDirectory = path => { throw new Error("NotSupported"); };
wrapper.directoryExists = (path): boolean => { throw new Error("NotSupported"); };
wrapper.deleteFile = path => { throw new Error("NotSupported"); };
wrapper.listFiles = (path, filter, options): string[] => { throw new Error("NotSupported"); };
wrapper.log = text => underlying.log(text);
wrapper.fileExists = recordReplay(wrapper.fileExists, underlying)(
(path) => callAndRecord(underlying.fileExists(path), recordLog.fileExists, { path: path }),
@@ -276,7 +282,7 @@ module Playback {
wrapper.getCurrentDirectory = () => {
if (replayLog !== undefined) {
return replayLog.currentDirectory || '';
return replayLog.currentDirectory || "";
} else if (recordLog !== undefined) {
return recordLog.currentDirectory = underlying.getCurrentDirectory();
} else {
@@ -286,7 +292,7 @@ module Playback {
wrapper.resolvePath = recordReplay(wrapper.resolvePath, underlying)(
(path) => callAndRecord(underlying.resolvePath(path), recordLog.pathsResolved, { path: path }),
memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + '/' + path : ts.normalizeSlashes(path))));
memoize((path) => findResultByFields(replayLog.pathsResolved, { path: path }, !ts.isRootedDiskPath(ts.normalizeSlashes(path)) && replayLog.currentDirectory ? replayLog.currentDirectory + "/" + path : ts.normalizeSlashes(path))));
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
(path) => {
@@ -299,7 +305,7 @@ module Playback {
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path: path, contents: contents, bom: false }),
(path, contents) => noOpReplay('writeFile'));
(path, contents) => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {
+30 -27
View File
@@ -62,7 +62,7 @@ class ProjectRunner extends RunnerBase {
let testFileText: string = null;
try {
testFileText = ts.sys.readFile(testCaseFileName);
testFileText = Harness.IO.readFile(testCaseFileName);
}
catch (e) {
assert(false, "Unable to open testcase file: " + testCaseFileName + ": " + e.message);
@@ -74,7 +74,7 @@ class ProjectRunner extends RunnerBase {
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
}
let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, "").replace(/\.json/, "");
function moduleNameToString(moduleKind: ts.ModuleKind) {
return moduleKind === ts.ModuleKind.AMD
@@ -98,7 +98,7 @@ class ProjectRunner extends RunnerBase {
}
function cleanProjectUrl(url: string) {
let diskProjectPath = ts.normalizeSlashes(ts.sys.resolvePath(testCase.projectRoot));
let diskProjectPath = ts.normalizeSlashes(Harness.IO.resolvePath(testCase.projectRoot));
let projectRootUrl = "file:///" + diskProjectPath;
let normalizedProjectRoot = ts.normalizeSlashes(testCase.projectRoot);
diskProjectPath = diskProjectPath.substr(0, diskProjectPath.lastIndexOf(normalizedProjectRoot));
@@ -122,7 +122,7 @@ class ProjectRunner extends RunnerBase {
}
function getCurrentDirectory() {
return ts.sys.resolvePath(testCase.projectRoot);
return Harness.IO.resolvePath(testCase.projectRoot);
}
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: () => string[],
@@ -158,11 +158,12 @@ class ProjectRunner extends RunnerBase {
return {
declaration: !!testCase.declaration,
sourceMap: !!testCase.sourceMap,
out: testCase.out,
outFile: testCase.out,
outDir: testCase.outDir,
mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? ts.sys.resolvePath(testCase.mapRoot) : testCase.mapRoot,
sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? ts.sys.resolvePath(testCase.sourceRoot) : testCase.sourceRoot,
mapRoot: testCase.resolveMapRoot && testCase.mapRoot ? Harness.IO.resolvePath(testCase.mapRoot) : testCase.mapRoot,
sourceRoot: testCase.resolveSourceRoot && testCase.sourceRoot ? Harness.IO.resolvePath(testCase.sourceRoot) : testCase.sourceRoot,
module: moduleKind,
moduleResolution: ts.ModuleResolutionKind.Classic, // currently all tests use classic module resolution kind, this will change in the future
noResolve: testCase.noResolve,
rootDir: testCase.rootDir
};
@@ -190,8 +191,10 @@ class ProjectRunner extends RunnerBase {
writeFile,
getCurrentDirectory,
getCanonicalFileName: Harness.Compiler.getCanonicalFileName,
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
getNewLine: () => ts.sys.newLine
useCaseSensitiveFileNames: () => Harness.IO.useCaseSensitiveFileNames(),
getNewLine: () => Harness.IO.newLine(),
fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
readFile: fileName => Harness.IO.readFile(fileName)
};
}
}
@@ -214,7 +217,7 @@ class ProjectRunner extends RunnerBase {
function getSourceFileText(fileName: string): string {
let text: string = undefined;
try {
text = ts.sys.readFile(ts.isRootedDiskPath(fileName)
text = Harness.IO.readFile(ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName));
}
@@ -261,14 +264,14 @@ class ProjectRunner extends RunnerBase {
// Actual writing of file as in tc.ts
function ensureDirectoryStructure(directoryname: string) {
if (directoryname) {
if (!ts.sys.directoryExists(directoryname)) {
if (!Harness.IO.directoryExists(directoryname)) {
ensureDirectoryStructure(ts.getDirectoryPath(directoryname));
ts.sys.createDirectory(directoryname);
Harness.IO.createDirectory(directoryname);
}
}
}
ensureDirectoryStructure(ts.getDirectoryPath(ts.normalizePath(outputFilePath)));
ts.sys.writeFile(outputFilePath, data, writeByteOrderMark);
Harness.IO.writeFile(outputFilePath, data);
outputFiles.push({ emittedFileName: fileName, code: data, fileName: diskRelativeName, writeByteOrderMark: writeByteOrderMark });
}
@@ -297,7 +300,7 @@ class ProjectRunner extends RunnerBase {
allInputFiles.unshift(findOutpuDtsFile(outputDtsFileName));
}
else {
let outputDtsFileName = ts.removeFileExtension(compilerOptions.out) + ".d.ts";
let outputDtsFileName = ts.removeFileExtension(compilerOptions.outFile|| compilerOptions.out) + ".d.ts";
let outputDtsFile = findOutpuDtsFile(outputDtsFileName);
if (!ts.contains(allInputFiles, outputDtsFile)) {
allInputFiles.unshift(outputDtsFile);
@@ -331,9 +334,9 @@ class ProjectRunner extends RunnerBase {
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
let name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
let name = "Compiling project for " + testCase.scenario + ": testcase " + testCaseFileName;
describe('Projects tests', () => {
describe("Projects tests", () => {
describe(name, () => {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
let compilerResult: BatchCompileProjectTestCaseResult;
@@ -367,29 +370,29 @@ class ProjectRunner extends RunnerBase {
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
it('Resolution information of (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.json', () => {
it("Resolution information of (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
Harness.Baseline.runBaseline("Resolution information of (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".json", () => {
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
});
});
it('Errors for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("Errors for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.errors.length) {
Harness.Baseline.runBaseline('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.errors.txt', () => {
Harness.Baseline.runBaseline("Errors for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".errors.txt", () => {
return getErrorsBaseline(compilerResult);
});
}
});
it('Baseline of emitted result (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("Baseline of emitted result (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
Harness.Baseline.runBaseline('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
Harness.Baseline.runBaseline("Baseline of emitted result (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return ts.sys.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
return Harness.IO.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
}
catch (e) {
return undefined;
@@ -400,9 +403,9 @@ class ProjectRunner extends RunnerBase {
});
it('SourceMapRecord for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("SourceMapRecord for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
Harness.Baseline.runBaseline("SourceMapRecord for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".sourcemap.txt", () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
@@ -411,11 +414,11 @@ class ProjectRunner extends RunnerBase {
// Verify that all the generated .d.ts files compile
it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
it("Errors in generated Dts files for (" + moduleNameToString(moduleKind) + "): " + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
let dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
Harness.Baseline.runBaseline("Errors in generated Dts files for (" + moduleNameToString(compilerResult.moduleKind) + "): " + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + ".dts.errors.txt", () => {
return getErrorsBaseline(dTsCompileResult);
});
}
+22 -20
View File
@@ -13,12 +13,12 @@
// limitations under the License.
//
/// <reference path='test262Runner.ts' />
/// <reference path='compilerRunner.ts' />
/// <reference path='fourslashRunner.ts' />
/// <reference path='projectsRunner.ts' />
/// <reference path='rwcRunner.ts' />
/// <reference path='harness.ts' />
/// <reference path="test262Runner.ts" />
/// <reference path="compilerRunner.ts" />
/// <reference path="fourslashRunner.ts" />
/// <reference path="projectsRunner.ts" />
/// <reference path="rwcRunner.ts" />
/// <reference path="harness.ts" />
let runners: RunnerBase[] = [];
let iterations: number = 1;
@@ -32,13 +32,13 @@ function runTests(runners: RunnerBase[]) {
}
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
let mytestconfig = 'mytest.config';
let testconfig = 'test.config';
let mytestconfig = "mytest.config";
let testconfig = "test.config";
let testConfigFile =
Harness.IO.fileExists(mytestconfig) ? Harness.IO.readFile(mytestconfig) :
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : '');
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : "");
if (testConfigFile !== '') {
if (testConfigFile !== "") {
let testConfig = JSON.parse(testConfigFile);
if (testConfig.light) {
Harness.lightMode = true;
@@ -51,33 +51,36 @@ if (testConfigFile !== '') {
}
switch (option) {
case 'compiler':
case "compiler":
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
runners.push(new CompilerBaselineRunner(CompilerTestType.Regressions));
runners.push(new ProjectRunner());
break;
case 'conformance':
case "conformance":
runners.push(new CompilerBaselineRunner(CompilerTestType.Conformance));
break;
case 'project':
case "project":
runners.push(new ProjectRunner());
break;
case 'fourslash':
case "fourslash":
runners.push(new FourSlashRunner(FourSlashTestType.Native));
break;
case 'fourslash-shims':
case "fourslash-shims":
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
break;
case 'fourslash-shims-pp':
runners.push(new FourSlashRunner(FourSlashTestType.ShimsWithPreprocess));
break;
case 'fourslash-server':
runners.push(new FourSlashRunner(FourSlashTestType.Server));
break;
case 'fourslash-generated':
case "fourslash-generated":
runners.push(new GeneratedFourslashRunner(FourSlashTestType.Native));
break;
case 'rwc':
case "rwc":
runners.push(new RWCRunner());
break;
case 'test262':
case "test262":
runners.push(new Test262BaselineRunner());
break;
}
@@ -98,10 +101,9 @@ if (runners.length === 0) {
// language services
runners.push(new FourSlashRunner(FourSlashTestType.Native));
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
runners.push(new FourSlashRunner(FourSlashTestType.ShimsWithPreprocess));
runners.push(new FourSlashRunner(FourSlashTestType.Server));
// runners.push(new GeneratedFourslashRunner());
}
ts.sys.newLine = '\r\n';
runTests(runners);
+1 -1
View File
@@ -33,7 +33,7 @@ abstract class RunnerBase {
// when running in the browser the 'full path' is the host name, shows up in error baselines
let localHost = /http:\/localhost:\d+/g;
fixedPath = fixedPath.replace(localHost, '');
fixedPath = fixedPath.replace(localHost, "");
return fixedPath;
}
}
+38 -37
View File
@@ -1,21 +1,21 @@
/// <reference path='harness.ts'/>
/// <reference path='runnerbase.ts' />
/// <reference path='loggedIO.ts' />
/// <reference path='..\compiler\commandLineParser.ts'/>
/// <reference path="harness.ts"/>
/// <reference path="runnerbase.ts" />
/// <reference path="loggedIO.ts" />
/// <reference path="..\compiler\commandLineParser.ts"/>
module RWC {
function runWithIOLog(ioLog: IOLog, fn: () => void) {
let oldSys = ts.sys;
function runWithIOLog(ioLog: IOLog, fn: (oldIO: Harness.IO) => void) {
let oldIO = Harness.IO;
let wrappedSys = Playback.wrapSystem(ts.sys);
wrappedSys.startReplayFromData(ioLog);
ts.sys = wrappedSys;
let wrappedIO = Playback.wrapIO(oldIO);
wrappedIO.startReplayFromData(ioLog);
Harness.IO = wrappedIO;
try {
fn();
fn(oldIO);
} finally {
wrappedSys.endReplay();
ts.sys = oldSys;
wrappedIO.endReplay();
Harness.IO = oldIO;
}
}
@@ -26,13 +26,12 @@ module RWC {
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: 'rwc',
Baselinefolder: 'internal/baselines'
Subfolder: "rwc",
Baselinefolder: "internal/baselines"
};
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
let useCustomLibraryFile: boolean;
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
@@ -49,7 +48,7 @@ module RWC {
useCustomLibraryFile = undefined;
});
it('can compile', () => {
it("can compile", () => {
let harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
@@ -57,7 +56,7 @@ module RWC {
currentDirectory = ioLog.currentDirectory;
useCustomLibraryFile = ioLog.useCustomLibraryFile;
runWithIOLog(ioLog, () => {
opts = ts.parseCommandLine(ioLog.arguments);
opts = ts.parseCommandLine(ioLog.arguments, fileName => Harness.IO.readFile(fileName));
assert.equal(opts.errors.length, 0);
// To provide test coverage of output javascript file,
@@ -65,7 +64,7 @@ module RWC {
opts.options.noEmitOnError = false;
});
runWithIOLog(ioLog, () => {
runWithIOLog(ioLog, oldIO => {
harnessCompiler.reset();
// Load the files
@@ -74,10 +73,11 @@ module RWC {
});
// Add files to compilation
let isInInputList = (resolvedPath: string) => (inputFile: { unitName: string; content: string; }) => inputFile.unitName === resolvedPath;
for (let fileRead of ioLog.filesRead) {
// Check if the file is already added into the set of input files.
var resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
let inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
const resolvedPath = ts.normalizeSlashes(Harness.IO.resolvePath(fileRead.path));
let inInputList = ts.forEach(inputFiles, isInInputList(resolvedPath));
if (!Harness.isLibraryFile(fileRead.path)) {
if (inInputList) {
@@ -96,7 +96,8 @@ module RWC {
inputFiles.push(getHarnessCompilerInputUnit(fileRead.path));
}
else {
inputFiles.push(Harness.getDefaultLibraryFile());
// set the flag to put default library to the beginning of the list
inputFiles.unshift(Harness.getDefaultLibraryFile(oldIO));
}
}
}
@@ -117,27 +118,27 @@ module RWC {
});
function getHarnessCompilerInputUnit(fileName: string) {
let unitName = ts.normalizeSlashes(ts.sys.resolvePath(fileName));
let unitName = ts.normalizeSlashes(Harness.IO.resolvePath(fileName));
let content: string = null;
try {
content = ts.sys.readFile(unitName);
content = Harness.IO.readFile(unitName);
}
catch (e) {
content = ts.sys.readFile(fileName);
content = Harness.IO.readFile(fileName);
}
return { unitName, content };
}
});
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
it("has the expected emitted code", () => {
Harness.Baseline.runBaseline("has the expected emitted code", baseName + ".output.js", () => {
return Harness.Compiler.collateOutputs(compilerResult.files);
}, false, baselineOpts);
});
it('has the expected declaration file content', () => {
Harness.Baseline.runBaseline('has the expected declaration file content', baseName + '.d.ts', () => {
it("has the expected declaration file content", () => {
Harness.Baseline.runBaseline("has the expected declaration file content", baseName + ".d.ts", () => {
if (!compilerResult.declFilesCode.length) {
return null;
}
@@ -146,8 +147,8 @@ module RWC {
}, false, baselineOpts);
});
it('has the expected source maps', () => {
Harness.Baseline.runBaseline('has the expected source maps', baseName + '.map', () => {
it("has the expected source maps", () => {
Harness.Baseline.runBaseline("has the expected source maps", baseName + ".map", () => {
if (!compilerResult.sourceMaps.length) {
return null;
}
@@ -156,16 +157,16 @@ module RWC {
}, false, baselineOpts);
});
/*it('has correct source map record', () => {
/*it("has correct source map record", () => {
if (compilerOptions.sourceMap) {
Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
Harness.Baseline.runBaseline("has correct source map record", baseName + ".sourcemap.txt", () => {
return compilerResult.getSourceMapRecord();
}, false, baselineOpts);
}
});*/
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
it("has the expected errors", () => {
Harness.Baseline.runBaseline("has the expected errors", baseName + ".errors.txt", () => {
if (compilerResult.errors.length === 0) {
return null;
}
@@ -176,9 +177,9 @@ module RWC {
// Ideally, a generated declaration file will have no errors. But we allow generated
// declaration file errors as part of the baseline.
it('has the expected errors in generated declaration files', () => {
it("has the expected errors in generated declaration files", () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => {
Harness.Baseline.runBaseline("has the expected errors in generated declaration files", baseName + ".dts.errors.txt", () => {
let declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
/*settingscallback*/ undefined, compilerOptions, currentDirectory);
if (declFileCompilationResult.declResult.errors.length === 0) {
@@ -186,7 +187,7 @@ module RWC {
}
return Harness.Compiler.minimalDiagnosticsToString(declFileCompilationResult.declResult.errors) +
ts.sys.newLine + ts.sys.newLine +
Harness.IO.newLine() + Harness.IO.newLine() +
Harness.Compiler.getErrorBaseline(declFileCompilationResult.declInputFiles.concat(declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.errors);
}, false, baselineOpts);
}
+6 -6
View File
@@ -13,7 +13,7 @@
// limitations under the License.
//
///<reference path='harness.ts'/>
///<reference path="harness.ts"/>
module Harness.SourceMapRecoder {
@@ -50,11 +50,11 @@ module Harness.SourceMapRecoder {
return true;
}
if (sourceMapMappings.charAt(decodingIndex) == ',') {
if (sourceMapMappings.charAt(decodingIndex) == ",") {
return true;
}
if (sourceMapMappings.charAt(decodingIndex) == ';') {
if (sourceMapMappings.charAt(decodingIndex) == ";") {
return true;
}
@@ -117,7 +117,7 @@ module Harness.SourceMapRecoder {
}
while (decodingIndex < sourceMapMappings.length) {
if (sourceMapMappings.charAt(decodingIndex) == ';') {
if (sourceMapMappings.charAt(decodingIndex) == ";") {
// New line
decodeOfEncodedMapping.emittedLine++;
decodeOfEncodedMapping.emittedColumn = 1;
@@ -125,7 +125,7 @@ module Harness.SourceMapRecoder {
continue;
}
if (sourceMapMappings.charAt(decodingIndex) == ',') {
if (sourceMapMappings.charAt(decodingIndex) == ",") {
// Next entry is on same line - no action needed
decodingIndex++;
continue;
@@ -459,6 +459,6 @@ module Harness.SourceMapRecoder {
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
return sourceMapRecoder.lines.join('\r\n');
return sourceMapRecoder.lines.join("\r\n");
}
}
+15 -15
View File
@@ -1,9 +1,9 @@
/// <reference path='harness.ts' />
/// <reference path='runnerbase.ts' />
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
class Test262BaselineRunner extends RunnerBase {
private static basePath = 'internal/cases/test262';
private static helpersFilePath = 'tests/cases/test262-harness/helpers.d.ts';
private static basePath = "internal/cases/test262";
private static helpersFilePath = "tests/cases/test262-harness/helpers.d.ts";
private static helperFile = {
unitName: Test262BaselineRunner.helpersFilePath,
content: Harness.IO.readFile(Test262BaselineRunner.helpersFilePath)
@@ -15,8 +15,8 @@ class Test262BaselineRunner extends RunnerBase {
module: ts.ModuleKind.CommonJS
};
private static baselineOptions: Harness.Baseline.BaselineOptions = {
Subfolder: 'test262',
Baselinefolder: 'internal/baselines'
Subfolder: "test262",
Baselinefolder: "internal/baselines"
};
private static getTestFilePath(filename: string): string {
@@ -24,7 +24,7 @@ class Test262BaselineRunner extends RunnerBase {
}
private runTest(filePath: string) {
describe('test262 test for ' + filePath, () => {
describe("test262 test for " + filePath, () => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Everything declared here should be cleared out in the "after" callback.
let testState: {
@@ -36,7 +36,7 @@ class Test262BaselineRunner extends RunnerBase {
before(() => {
let content = Harness.IO.readFile(filePath);
let testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
let testFilename = ts.removeFileExtension(filePath).replace(/\//g, "_") + ".test";
let testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
let inputFiles = testCaseContent.testUnitData.map(unit => {
@@ -61,15 +61,15 @@ class Test262BaselineRunner extends RunnerBase {
testState = undefined;
});
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', testState.filename + '.output.js', () => {
it("has the expected emitted code", () => {
Harness.Baseline.runBaseline("has the expected emitted code", testState.filename + ".output.js", () => {
let files = testState.compilerResult.files.filter(f => f.fileName !== Test262BaselineRunner.helpersFilePath);
return Harness.Compiler.collateOutputs(files);
}, false, Test262BaselineRunner.baselineOptions);
});
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', testState.filename + '.errors.txt', () => {
it("has the expected errors", () => {
Harness.Baseline.runBaseline("has the expected errors", testState.filename + ".errors.txt", () => {
let errors = testState.compilerResult.errors;
if (errors.length === 0) {
return null;
@@ -79,13 +79,13 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
it('satisfies inletiants', () => {
it("satisfies inletiants", () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it('has the expected AST', () => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt', () => {
it("has the expected AST", () => {
Harness.Baseline.runBaseline("has the expected AST", testState.filename + ".AST.txt", () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
+1 -1
View File
@@ -71,4 +71,4 @@ class TypeWriterWalker {
symbol: symbolString
});
}
}
}
+2650 -9
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -8,4 +8,4 @@ interface NodeList {
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>
}
}
+37 -14
View File
@@ -2459,7 +2459,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, "fullscreen=yes, toolbar=yes"). The following values are supported.
* @param replace Specifies whether the existing entry for the document is replaced in the history list.
*/
open(url?: string, name?: string, features?: string, replace?: boolean): Document | Window;
open(url?: string, name?: string, features?: string, replace?: boolean): Document;
/**
* Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.
* @param commandId Specifies a command identifier.
@@ -2916,6 +2916,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec
webkitMatchesSelector(selectors: string): boolean;
webkitRequestFullScreen(): void;
webkitRequestFullscreen(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void;
@@ -3030,7 +3031,7 @@ interface File extends Blob {
declare var File: {
prototype: File;
new(): File;
new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;
}
interface FileList {
@@ -3903,7 +3904,6 @@ interface HTMLElement extends Element {
contains(child: HTMLElement): boolean;
dragDrop(): boolean;
focus(): void;
getElementsByClassName(classNames: string): NodeListOf<Element>;
insertAdjacentElement(position: string, insertedElement: Element): Element;
insertAdjacentHTML(where: string, html: string): void;
insertAdjacentText(where: string, text: string): void;
@@ -6865,7 +6865,7 @@ interface IDBDatabase extends EventTarget {
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -6986,7 +6986,7 @@ interface IDBTransaction extends EventTarget {
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -7016,11 +7016,14 @@ interface ImageData {
width: number;
}
declare var ImageData: {
interface ImageDataConstructor {
prototype: ImageData;
new(): ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
}
declare var ImageData: ImageDataConstructor;
interface KeyboardEvent extends UIEvent {
altKey: boolean;
char: string;
@@ -7703,7 +7706,7 @@ interface MessageEvent extends Event {
declare var MessageEvent: {
prototype: MessageEvent;
new(): MessageEvent;
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
interface MessagePort extends EventTarget {
@@ -8445,7 +8448,7 @@ interface ProgressEvent extends Event {
declare var ProgressEvent: {
prototype: ProgressEvent;
new(): ProgressEvent;
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
interface Range {
@@ -11962,7 +11965,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
onvolumechange: (ev: Event) => any;
onwaiting: (ev: Event) => any;
opener: Window;
orientation: string;
orientation: string | number;
outerHeight: number;
outerWidth: number;
pageXOffset: number;
@@ -12169,7 +12172,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
LOADING: number;
OPENED: number;
UNSENT: number;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -12439,7 +12442,7 @@ interface MSBaseReader {
DONE: number;
EMPTY: number;
LOADING: number;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -12595,7 +12598,7 @@ interface XMLHttpRequestEventTarget {
onloadstart: (ev: Event) => any;
onprogress: (ev: ProgressEvent) => any;
ontimeout: (ev: ProgressEvent) => any;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -12617,12 +12620,32 @@ interface BlobPropertyBag {
endings?: string;
}
interface FilePropertyBag {
type?: string;
lastModified?: number;
}
interface EventListenerObject {
handleEvent(evt: Event): void;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface MessageEventInit extends EventInit {
data?: any;
origin?: string;
lastEventId?: string;
channel?: string;
source?: any;
ports?: MessagePort[];
}
interface ProgressEventInit extends EventInit {
lengthComputable?: boolean;
loaded?: number;
total?: number;
}
interface ErrorEventHandler {
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
@@ -12777,7 +12800,7 @@ declare var onunload: (ev: Event) => any;
declare var onvolumechange: (ev: Event) => any;
declare var onwaiting: (ev: Event) => any;
declare var opener: Window;
declare var orientation: string;
declare var orientation: string | number;
declare var outerHeight: number;
declare var outerWidth: number;
declare var pageXOffset: number;
+146 -2535
View File
File diff suppressed because it is too large Load Diff
-2305
View File
File diff suppressed because it is too large Load Diff
+142 -21
View File
@@ -3,10 +3,28 @@
/// IE Worker APIs
/////////////////////////////
interface EventInit {
bubbles?: boolean;
cancelable?: boolean;
}
interface EventListener {
(evt: Event): void;
}
interface AudioBuffer {
duration: number;
length: number;
numberOfChannels: number;
sampleRate: number;
getChannelData(channel: number): any;
}
declare var AudioBuffer: {
prototype: AudioBuffer;
new(): AudioBuffer;
}
interface Blob {
size: number;
type: string;
@@ -60,6 +78,21 @@ declare var Console: {
new(): Console;
}
interface Coordinates {
accuracy: number;
altitude: number;
altitudeAccuracy: number;
heading: number;
latitude: number;
longitude: number;
speed: number;
}
declare var Coordinates: {
prototype: Coordinates;
new(): Coordinates;
}
interface DOMError {
name: string;
toString(): string;
@@ -210,7 +243,7 @@ interface File extends Blob {
declare var File: {
prototype: File;
new(): File;
new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;
}
interface FileList {
@@ -281,7 +314,7 @@ interface IDBDatabase extends EventTarget {
createObjectStore(name: string, optionalParameters?: any): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: any, mode?: string): IDBTransaction;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
@@ -402,7 +435,7 @@ interface IDBTransaction extends EventTarget {
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -432,11 +465,14 @@ interface ImageData {
width: number;
}
declare var ImageData: {
interface ImageDataConstructor {
prototype: ImageData;
new(): ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
}
declare var ImageData: ImageDataConstructor;
interface MSApp {
clearTemporaryWebDataAsync(): MSAppAsyncOperation;
createBlobFromRandomAccessStream(type: string, seeker: any): Blob;
@@ -460,6 +496,29 @@ interface MSApp {
}
declare var MSApp: MSApp;
interface MSAppAsyncOperation extends EventTarget {
error: DOMError;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
readyState: number;
result: any;
start(): void;
COMPLETED: number;
ERROR: number;
STARTED: number;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var MSAppAsyncOperation: {
prototype: MSAppAsyncOperation;
new(): MSAppAsyncOperation;
COMPLETED: number;
ERROR: number;
STARTED: number;
}
interface MSBlobBuilder {
append(data: any, endings?: string): void;
getBlob(contentType?: string): Blob;
@@ -496,6 +555,18 @@ declare var MSStreamReader: {
new(): MSStreamReader;
}
interface MediaQueryList {
matches: boolean;
media: string;
addListener(listener: MediaQueryListListener): void;
removeListener(listener: MediaQueryListListener): void;
}
declare var MediaQueryList: {
prototype: MediaQueryList;
new(): MediaQueryList;
}
interface MessageChannel {
port1: MessagePort;
port2: MessagePort;
@@ -516,7 +587,7 @@ interface MessageEvent extends Event {
declare var MessageEvent: {
prototype: MessageEvent;
new(): MessageEvent;
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
interface MessagePort extends EventTarget {
@@ -533,6 +604,33 @@ declare var MessagePort: {
new(): MessagePort;
}
interface Position {
coords: Coordinates;
timestamp: number;
}
declare var Position: {
prototype: Position;
new(): Position;
}
interface PositionError {
code: number;
message: string;
toString(): string;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
}
declare var PositionError: {
prototype: PositionError;
new(): PositionError;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
}
interface ProgressEvent extends Event {
lengthComputable: boolean;
loaded: number;
@@ -542,7 +640,7 @@ interface ProgressEvent extends Event {
declare var ProgressEvent: {
prototype: ProgressEvent;
new(): ProgressEvent;
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
interface WebSocket extends EventTarget {
@@ -620,7 +718,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
LOADING: number;
OPENED: number;
UNSENT: number;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -642,6 +740,15 @@ declare var XMLHttpRequest: {
create(): XMLHttpRequest;
}
interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var XMLHttpRequestUpload: {
prototype: XMLHttpRequestUpload;
new(): XMLHttpRequestUpload;
}
interface AbstractWorker {
onerror: (ev: Event) => any;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
@@ -661,7 +768,7 @@ interface MSBaseReader {
DONE: number;
EMPTY: number;
LOADING: number;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -702,7 +809,7 @@ interface XMLHttpRequestEventTarget {
onloadstart: (ev: Event) => any;
onprogress: (ev: ProgressEvent) => any;
ontimeout: (ev: ProgressEvent) => any;
addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
@@ -788,25 +895,39 @@ interface WorkerUtils extends Object, WindowBase64 {
}
interface NodeListOf<TNode extends Node> extends NodeList {
length: number;
item(index: number): TNode;
[index: number]: TNode;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
}
interface FilePropertyBag {
type?: string;
lastModified?: number;
}
interface EventListenerObject {
handleEvent(evt: Event): void;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface MessageEventInit extends EventInit {
data?: any;
origin?: string;
lastEventId?: string;
channel?: string;
source?: any;
ports?: MessagePort[];
}
interface ProgressEventInit extends EventInit {
lengthComputable?: boolean;
loaded?: number;
total?: number;
}
interface ErrorEventHandler {
(event: Event | string, source?: string, fileno?: number, columnNumber?: number): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}
interface PositionCallback {
(position: Position): void;
@@ -820,11 +941,11 @@ interface MediaQueryListListener {
interface MSLaunchUriCallback {
(): void;
}
interface FrameRequestCallback {
(time: number): void;
interface MSUnsafeFunctionCallback {
(): any;
}
interface MutationCallback {
(mutations: MutationRecord[], observer: MutationObserver): void;
interface MSExecAtPriorityFunctionCallback {
(...args: any[]): any;
}
interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
+32 -3
View File
@@ -183,7 +183,7 @@ namespace ts.server {
return {
configFileName: response.body.configFileName,
fileNameList: response.body.fileNameList
fileNames: response.body.fileNames
};
}
@@ -527,8 +527,33 @@ namespace ts.server {
});
}
getDocumentHighlights(fileName: string, position: number): DocumentHighlights[] {
throw new Error("Not Implemented Yet.");
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] {
let { line, offset } = this.positionToOneBasedLineOffset(fileName, position);
let args: protocol.DocumentHighlightsRequestArgs = { file: fileName, line, offset, filesToSearch };
let request = this.processRequest<protocol.DocumentHighlightsRequest>(CommandNames.DocumentHighlights, args);
let response = this.processResponse<protocol.DocumentHighlightsResponse>(request);
let self = this;
return response.body.map(convertToDocumentHighlights);
function convertToDocumentHighlights(item: ts.server.protocol.DocumentHighlightsItem): ts.DocumentHighlights {
let { file, highlightSpans } = item;
return {
fileName: file,
highlightSpans: highlightSpans.map(convertHighlightSpan)
};
function convertHighlightSpan(span: ts.server.protocol.HighlightSpan): ts.HighlightSpan {
let start = self.lineOffsetToPosition(file, span.start);
let end = self.lineOffsetToPosition(file, span.end);
return {
textSpan: ts.createTextSpanFromBounds(start, end),
kind: span.kind
};
}
}
}
getOutliningSpans(fileName: string): OutliningSpan[] {
@@ -538,6 +563,10 @@ namespace ts.server {
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[] {
throw new Error("Not Implemented Yet.");
}
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion {
throw new Error("Not Implemented Yet.");
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
+256 -64
View File
@@ -78,15 +78,76 @@ namespace ts.server {
return this.snap().getChangeRange(oldSnapshot);
}
}
interface TimestampedResolvedModule extends ResolvedModule {
lastCheckTime: number;
}
export class LSHost implements ts.LanguageServiceHost {
ls: ts.LanguageService = null;
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.Map<ScriptInfo> = {};
roots: ScriptInfo[] = [];
private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>;
private moduleResolutionHost: ts.ModuleResolutionHost;
constructor(public host: ServerHost, public project: Project) {
this.resolvedModuleNames = ts.createFileMap<Map<TimestampedResolvedModule>>(ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames))
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
readFile: fileName => this.host.readFile(fileName)
}
}
resolveModuleNames(moduleNames: string[], containingFile: string): string[] {
let currentResolutionsInFile = this.resolvedModuleNames.get(containingFile);
let newResolutions: Map<TimestampedResolvedModule> = {};
let resolvedFileNames: string[] = [];
let compilerOptions = this.getCompilationSettings();
for (let moduleName of moduleNames) {
// check if this is a duplicate entry in the list
let resolution = lookUp(newResolutions, moduleName);
if (!resolution) {
let existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
resolution = existingResolution;
}
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedFileNames.push(resolution.resolvedFileName);
}
// replace old results with a new one
this.resolvedModuleNames.set(containingFile, newResolutions);
return resolvedFileNames;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedFileName) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
}
// consider situation if we have no candidate locations as valid resolution.
// after all there is no point to invalidate it if we have no idea where to look for the module.
return resolution.failedLookupLocations.length === 0;
}
}
getDefaultLibFileName() {
var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
@@ -102,6 +163,8 @@ namespace ts.server {
setCompilationSettings(opt: ts.CompilerOptions) {
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
}
lineAffectsRefs(filename: string, line: number) {
@@ -137,6 +200,7 @@ namespace ts.server {
removeReferencedFile(info: ScriptInfo) {
if (!info.isOpen) {
this.filenameToScript[info.fileName] = undefined;
this.resolvedModuleNames.remove(info.fileName);
}
}
@@ -160,6 +224,14 @@ namespace ts.server {
this.roots.push(info);
}
}
removeRoot(info: ScriptInfo) {
var scriptInfo = ts.lookUp(this.filenameToScript, info.fileName);
if (scriptInfo) {
this.filenameToScript[info.fileName] = undefined;
this.roots = copyListRemovingItem(info, this.roots);
}
}
saveTo(filename: string, tmpfilename: string) {
var script = this.getScriptInfo(filename);
@@ -281,6 +353,7 @@ namespace ts.server {
export class Project {
compilerService: CompilerService;
projectFilename: string;
projectFileWatcher: FileWatcher;
program: ts.Program;
filenameToSourceFile: ts.Map<ts.SourceFile> = {};
updateGraphSeq = 0;
@@ -288,7 +361,7 @@ namespace ts.server {
openRefCount = 0;
constructor(public projectService: ProjectService, public projectOptions?: ProjectOptions) {
this.compilerService = new CompilerService(this,projectOptions && projectOptions.compilerOptions);
this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions);
}
addOpenRef() {
@@ -304,7 +377,7 @@ namespace ts.server {
return this.projectService.openFile(filename, false);
}
getFileNameList() {
getFileNames() {
let sourceFiles = this.program.getSourceFiles();
return sourceFiles.map(sourceFile => sourceFile.fileName);
}
@@ -359,6 +432,12 @@ namespace ts.server {
info.defaultProject = this;
this.compilerService.host.addRoot(info);
}
// remove a root file from project
removeRoot(info: ScriptInfo) {
info.defaultProject = undefined;
this.compilerService.host.removeRoot(info);
}
filesToString() {
var strBuilder = "";
@@ -453,6 +532,12 @@ namespace ts.server {
}
}
watchedProjectConfigFileChanged(project: Project) {
this.log("Config File Changed: " + project.projectFilename);
this.updateConfiguredProject(project);
this.updateProjectStructure();
}
log(msg: string, type = "Err") {
this.psLogger.msg(msg, type);
}
@@ -530,16 +615,29 @@ namespace ts.server {
this.configuredProjects = configuredProjects;
}
removeConfiguredProject(project: Project) {
project.projectFileWatcher.close();
this.configuredProjects = copyListRemovingItem(project, this.configuredProjects);
let fileNames = project.getFileNames();
for (let fileName of fileNames) {
let info = this.getScriptInfo(fileName);
if (info.defaultProject == project) {
info.defaultProject = undefined;
}
}
}
setConfiguredProjectRoot(info: ScriptInfo) {
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
let configuredProject = this.configuredProjects[i];
if (configuredProject.isRoot(info)) {
info.defaultProject = configuredProject;
configuredProject.addOpenRef();
return true;
}
}
return false;
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
let configuredProject = this.configuredProjects[i];
if (configuredProject.isRoot(info)) {
info.defaultProject = configuredProject;
configuredProject.addOpenRef();
return true;
}
}
return false;
}
addOpenFile(info: ScriptInfo) {
@@ -583,7 +681,6 @@ namespace ts.server {
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
* @param openedByConfig True if info has become a root of a configured project
*/
closeOpenFile(info: ScriptInfo) {
var openFileRoots: ScriptInfo[] = [];
@@ -672,18 +769,42 @@ namespace ts.server {
return referencingProjects;
}
reloadProjects() {
// First check if there is new tsconfig file added for inferred project roots
for (let info of this.openFileRoots) {
this.openOrUpdateConfiguredProjectForFile(info.fileName);
}
this.updateProjectStructure();
}
/**
* This function is to update the project structure for every projects.
* It is called on the premise that all the configured projects are
* up to date.
*/
updateProjectStructure() {
this.log("updating project structure from ...", "Info");
this.printProjects();
let unattachedOpenFiles: ScriptInfo[] = [];
let openFileRootsConfigured: ScriptInfo[] = [];
for (let info of this.openFileRootsConfigured) {
let project = info.defaultProject;
if (!project || !(project.getSourceFile(info))) {
info.defaultProject = undefined;
unattachedOpenFiles.push(info);
}
else {
openFileRootsConfigured.push(info);
}
}
this.openFileRootsConfigured = openFileRootsConfigured;
// First loop through all open files that are referenced by projects but are not
// project roots. For each referenced file, see if the default project still
// references that file. If so, then just keep the file in the referenced list.
// If not, add the file to an unattached list, to be rechecked later.
var openFilesReferenced: ScriptInfo[] = [];
var unattachedOpenFiles: ScriptInfo[] = [];
for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
var referencedFile = this.openFilesReferenced[i];
referencedFile.defaultProject.updateGraph();
@@ -793,35 +914,40 @@ namespace ts.server {
* Open file whose contents is managed by the client
* @param filename is absolute pathname
*/
openClientFile(fileName: string) {
var searchPath = ts.normalizePath(getDirectoryPath(fileName));
this.log("Search path: " + searchPath,"Info");
var configFileName = this.findConfigFile(searchPath);
if (configFileName) {
this.log("Config file name: " + configFileName, "Info");
} else {
this.log("no config file");
}
if (configFileName) {
configFileName = getAbsolutePath(configFileName, searchPath);
}
if (configFileName && (!this.configProjectIsActive(configFileName))) {
var configResult = this.openConfigFile(configFileName, fileName);
if (!configResult.success) {
this.log("Error opening config file " + configFileName + " " + configResult.errorMsg);
}
else {
this.log("Opened configuration file " + configFileName,"Info");
this.configuredProjects.push(configResult.project);
}
}
this.openOrUpdateConfiguredProjectForFile(fileName);
var info = this.openFile(fileName, true);
this.addOpenFile(info);
this.printProjects();
return info;
}
openOrUpdateConfiguredProjectForFile(fileName: string) {
let searchPath = ts.normalizePath(getDirectoryPath(fileName));
this.log("Search path: " + searchPath, "Info");
let configFileName = this.findConfigFile(searchPath);
if (configFileName) {
this.log("Config file name: " + configFileName, "Info");
let project = this.findConfiguredProjectByConfigFile(configFileName);
if (!project) {
var configResult = this.openConfigFile(configFileName, fileName);
if (!configResult.success) {
this.log("Error opening config file " + configFileName + " " + configResult.errorMsg);
}
else {
this.log("Opened configuration file " + configFileName, "Info");
this.configuredProjects.push(configResult.project);
}
}
else {
this.updateConfiguredProject(project);
}
}
else {
this.log("No config files found.");
}
}
/**
* Close file whose contents is managed by the client
* @param filename is absolute pathname
@@ -874,7 +1000,7 @@ namespace ts.server {
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
var project = this.configuredProjects[i];
project.updateGraph();
this.psLogger.info("Project (configured) " + (i+this.inferredProjects.length).toString());
this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString());
this.psLogger.info(project.filesToString());
this.psLogger.info("-----------------------------------------------");
}
@@ -898,48 +1024,113 @@ namespace ts.server {
}
configProjectIsActive(fileName: string) {
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
if (this.configuredProjects[i].projectFilename == fileName) {
return true;
}
}
return false;
return this.findConfiguredProjectByConfigFile(fileName) === undefined;
}
openConfigFile(configFilename: string, clientFileName?: string): ProjectOpenResult {
findConfiguredProjectByConfigFile(configFileName: string) {
for (var i = 0, len = this.configuredProjects.length; i < len; i++) {
if (this.configuredProjects[i].projectFilename == configFileName) {
return this.configuredProjects[i];
}
}
return undefined;
}
configFileToProjectOptions(configFilename: string): { succeeded: boolean, projectOptions?: ProjectOptions, error?: ProjectOpenResult } {
configFilename = ts.normalizePath(configFilename);
// file references will be relative to dirPath (or absolute)
var dirPath = ts.getDirectoryPath(configFilename);
var rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.readConfigFile(configFilename);
var contents = this.host.readFile(configFilename)
var rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.parseConfigFileText(configFilename, contents);
if (rawConfig.error) {
return rawConfig.error;
return { succeeded: false, error: rawConfig.error };
}
else {
var parsedCommandLine = ts.parseConfigFile(rawConfig.config, this.host, dirPath);
if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) {
return { errorMsg: "tsconfig option errors" };
return { succeeded: false, error: { errorMsg: "tsconfig option errors" } };
}
else if (parsedCommandLine.fileNames) {
else if (parsedCommandLine.fileNames == null) {
return { succeeded: false, error: { errorMsg: "no files found" } }
}
else {
var projectOptions: ProjectOptions = {
files: parsedCommandLine.fileNames,
compilerOptions: parsedCommandLine.options
};
var proj = this.createProject(configFilename, projectOptions);
for (var i = 0, len = parsedCommandLine.fileNames.length; i < len; i++) {
var rootFilename = parsedCommandLine.fileNames[i];
if (this.host.fileExists(rootFilename)) {
var info = this.openFile(rootFilename, clientFileName == rootFilename);
proj.addRoot(info);
}
else {
return { errorMsg: "specified file " + rootFilename + " not found" };
}
return { succeeded: true, projectOptions };
}
}
}
openConfigFile(configFilename: string, clientFileName?: string): ProjectOpenResult {
let { succeeded, projectOptions, error } = this.configFileToProjectOptions(configFilename);
if (!succeeded) {
return error;
}
else {
let proj = this.createProject(configFilename, projectOptions);
for (let i = 0, len = projectOptions.files.length; i < len; i++) {
let rootFilename = projectOptions.files[i];
if (this.host.fileExists(rootFilename)) {
let info = this.openFile(rootFilename, /*openedByClient*/ clientFileName == rootFilename);
proj.addRoot(info);
}
proj.finishGraph();
return { success: true, project: proj };
else {
return { errorMsg: "specified file " + rootFilename + " not found" };
}
}
proj.finishGraph();
proj.projectFileWatcher = this.host.watchFile(configFilename, _ => this.watchedProjectConfigFileChanged(proj));
return { success: true, project: proj };
}
}
updateConfiguredProject(project: Project) {
if (!this.host.fileExists(project.projectFilename)) {
this.log("Config file deleted");
this.removeConfiguredProject(project);
}
else {
let { succeeded, projectOptions, error } = this.configFileToProjectOptions(project.projectFilename);
if (!succeeded) {
return error;
}
else {
return { errorMsg: "no files found" };
let oldFileNames = project.compilerService.host.roots.map(info => info.fileName);
let newFileNames = projectOptions.files;
let fileNamesToRemove = oldFileNames.filter(f => newFileNames.indexOf(f) < 0);
let fileNamesToAdd = newFileNames.filter(f => oldFileNames.indexOf(f) < 0);
for (let fileName of fileNamesToRemove) {
let info = this.getScriptInfo(fileName);
project.removeRoot(info);
}
for (let fileName of fileNamesToAdd) {
let info = this.getScriptInfo(fileName);
if (!info) {
info = this.openFile(fileName, false);
}
else {
// if the root file was opened by client, it would belong to either
// openFileRoots or openFileReferenced.
if (info.isOpen) {
if (this.openFileRoots.indexOf(info) >= 0) {
this.openFileRoots = copyListRemovingItem(info, this.openFileRoots);
}
if (this.openFilesReferenced.indexOf(info) >= 0) {
this.openFilesReferenced = copyListRemovingItem(info, this.openFilesReferenced);
}
this.openFileRootsConfigured.push(info);
}
}
project.addRoot(info);
}
project.setProjectOptions(projectOptions);
project.finishGraph();
}
}
}
@@ -992,6 +1183,7 @@ namespace ts.server {
InsertSpaceAfterKeywordsInControlFlowStatements: true,
InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
PlaceOpenBraceOnNewLineForFunctions: false,
PlaceOpenBraceOnNewLineForControlBlocks: false,
}
+7 -2
View File
@@ -123,9 +123,14 @@ declare module NodeJS {
export interface ReadWriteStream extends ReadableStream, WritableStream { }
interface WindowSize {
columns: number;
rows: number;
}
export interface Process extends EventEmitter {
stdout: WritableStream;
stderr: WritableStream;
stdout: WritableStream & WindowSize;
stderr: WritableStream & WindowSize;
stdin: ReadableStream;
argv: string[];
execPath: string;
+75 -1
View File
@@ -31,6 +31,12 @@ declare namespace ts.server.protocol {
*/
arguments?: any;
}
/**
* Request to reload the project structure for all the opened files
*/
export interface ReloadProjectsRequest extends Message {
}
/**
* Server-initiated event message
@@ -116,7 +122,7 @@ declare namespace ts.server.protocol {
/**
* The list of normalized file name in the project, including 'lib.d.ts'
*/
fileNameList?: string[];
fileNames?: string[];
}
/**
@@ -156,6 +162,17 @@ declare namespace ts.server.protocol {
arguments: FileLocationRequestArgs;
}
/**
* Arguments in document highlight request; include: filesToSearch, file,
* line, offset.
*/
export interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs {
/**
* List of files to search for document highlights.
*/
filesToSearch: string[];
}
/**
* Go to definition request; value of command field is
* "definition". Return response giving the file locations that
@@ -238,6 +255,35 @@ declare namespace ts.server.protocol {
body?: OccurrencesResponseItem[];
}
/**
* Get document highlights request; value of command field is
* "documentHighlights". Return response giving spans that are relevant
* in the file at a given line and column.
*/
export interface DocumentHighlightsRequest extends FileLocationRequest {
arguments: DocumentHighlightsRequestArgs
}
export interface HighlightSpan extends TextSpan {
kind: string
}
export interface DocumentHighlightsItem {
/**
* File containing highlight spans.
*/
file: string,
/**
* Spans to highlight in file.
*/
highlightSpans: HighlightSpan[];
}
export interface DocumentHighlightsResponse extends Response {
body?: DocumentHighlightsItem[];
}
/**
* Find references request; value of command field is
* "references". Return response giving the file locations that
@@ -412,6 +458,9 @@ declare namespace ts.server.protocol {
/** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean;
/** Defines space handling after opening and before closing non empty brackets. Default value is false. */
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean;
/** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */
placeOpenBraceOnNewLineForFunctions?: boolean;
@@ -854,6 +903,31 @@ declare namespace ts.server.protocol {
export interface SignatureHelpResponse extends Response {
body?: SignatureHelpItems;
}
/**
* Arguments for GeterrForProject request.
*/
export interface GeterrForProjectRequestArgs {
/**
* the file requesting project error list
*/
file: string;
/**
* Delay in milliseconds to wait before starting to compute
* errors for the files in the file list
*/
delay: number;
}
/**
* GeterrForProjectRequest request; value of command field is
* "geterrForProject". It works similarly with 'Geterr', only
* it request for every file in this project.
*/
export interface GeterrForProjectRequest extends Request {
arguments: GeterrForProjectRequestArgs
}
/**
* Arguments for geterr messages.
+106 -5
View File
@@ -86,9 +86,11 @@ namespace ts.server {
export const Format = "format";
export const Formatonkey = "formatonkey";
export const Geterr = "geterr";
export const GeterrForProject = "geterrForProject";
export const NavBar = "navbar";
export const Navto = "navto";
export const Occurrences = "occurrences";
export const DocumentHighlights = "documentHighlights";
export const Open = "open";
export const Quickinfo = "quickinfo";
export const References = "references";
@@ -98,6 +100,7 @@ namespace ts.server {
export const SignatureHelp = "signatureHelp";
export const TypeDefinition = "typeDefinition";
export const ProjectInfo = "projectInfo";
export const ReloadProjects = "reloadProjects";
export const Unknown = "unknown";
}
@@ -224,6 +227,10 @@ namespace ts.server {
this.syntacticCheck(file, project);
this.semanticCheck(file, project);
}
private reloadProjects() {
this.projectService.reloadProjects();
}
private updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) {
setTimeout(() => {
@@ -234,7 +241,7 @@ namespace ts.server {
}
private updateErrorCheck(checkList: PendingErrorCheck[], seq: number,
matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200) {
matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200, requireOpen = true) {
if (followMs > ms) {
followMs = ms;
}
@@ -249,7 +256,7 @@ namespace ts.server {
var checkOne = () => {
if (matchSeq(seq)) {
var checkSpec = checkList[index++];
if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, true)) {
if (checkSpec.project.getSourceFileFromName(checkSpec.fileName, requireOpen)) {
this.syntacticCheck(checkSpec.fileName, checkSpec.project);
this.immediateId = setImmediate(() => {
this.semanticCheck(checkSpec.fileName, checkSpec.project);
@@ -313,7 +320,7 @@ namespace ts.server {
}));
}
private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[]{
private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[] {
fileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(fileName);
@@ -343,6 +350,42 @@ namespace ts.server {
});
}
private getDocumentHighlights(line: number, offset: number, fileName: string, filesToSearch: string[]): protocol.DocumentHighlightsItem[] {
fileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(fileName);
if (!project) {
throw Errors.NoProject;
}
let { compilerService } = project;
let position = compilerService.host.lineOffsetToPosition(fileName, line, offset);
let documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch);
if (!documentHighlights) {
return undefined;
}
return documentHighlights.map(convertToDocumentHighlightsItem);
function convertToDocumentHighlightsItem(documentHighlights: ts.DocumentHighlights): ts.server.protocol.DocumentHighlightsItem {
let { fileName, highlightSpans } = documentHighlights;
return {
file: fileName,
highlightSpans: highlightSpans.map(convertHighlightSpan)
};
function convertHighlightSpan(highlightSpan: ts.HighlightSpan): ts.server.protocol.HighlightSpan {
let { textSpan, kind } = highlightSpan;
let start = compilerService.host.positionToLineOffset(fileName, textSpan.start);
let end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan));
return { start, end, kind };
}
}
}
private getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo {
fileName = ts.normalizePath(fileName)
let project = this.projectService.getProjectForFile(fileName)
@@ -352,7 +395,7 @@ namespace ts.server {
}
if (needFileNameList) {
projectInfo.fileNameList = project.getFileNameList();
projectInfo.fileNames = project.getFileNames();
}
return projectInfo;
@@ -836,7 +879,53 @@ namespace ts.server {
}));
}
public exit() {
getDiagnosticsForProject(delay: number, fileName: string) {
let { configFileName, fileNames: fileNamesInProject } = this.getProjectInfo(fileName, true);
// No need to analyze lib.d.ts
fileNamesInProject = fileNamesInProject.filter((value, index, array) => value.indexOf("lib.d.ts") < 0);
// Sort the file name list to make the recently touched files come first
let highPriorityFiles: string[] = [];
let mediumPriorityFiles: string[] = [];
let lowPriorityFiles: string[] = [];
let veryLowPriorityFiles: string[] = [];
let normalizedFileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(normalizedFileName);
for (let fileNameInProject of fileNamesInProject) {
if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName))
highPriorityFiles.push(fileNameInProject);
else {
let info = this.projectService.getScriptInfo(fileNameInProject);
if (!info.isOpen) {
if (fileNameInProject.indexOf(".d.ts") > 0)
veryLowPriorityFiles.push(fileNameInProject);
else
lowPriorityFiles.push(fileNameInProject);
}
else
mediumPriorityFiles.push(fileNameInProject);
}
}
fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles);
if (fileNamesInProject.length > 0) {
let checkList = fileNamesInProject.map<PendingErrorCheck>((fileName: string) => {
let normalizedFileName = ts.normalizePath(fileName);
return { fileName: normalizedFileName, project };
});
// Project level error analysis runs on background files too, therefore
// doesn't require the file to be opened
this.updateErrorCheck(checkList, this.changeSeq, (n) => n == this.changeSeq, delay, 200, /*requireOpen*/ false);
}
}
getCanonicalFileName(fileName: string) {
let name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
return ts.normalizePath(name);
}
exit() {
}
private handlers : Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = {
@@ -894,6 +983,10 @@ namespace ts.server {
var geterrArgs = <protocol.GeterrRequestArgs>request.arguments;
return {response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false};
},
[CommandNames.GeterrForProject]: (request: protocol.Request) => {
let { file, delay } = <protocol.GeterrForProjectRequestArgs>request.arguments;
return {response: this.getDiagnosticsForProject(delay, file), responseRequired: false};
},
[CommandNames.Change]: (request: protocol.Request) => {
var changeArgs = <protocol.ChangeRequestArgs>request.arguments;
this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset,
@@ -937,10 +1030,18 @@ namespace ts.server {
var { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getOccurrences(line, offset, fileName), responseRequired: true};
},
[CommandNames.DocumentHighlights]: (request: protocol.Request) => {
var { line, offset, file: fileName, filesToSearch } = <protocol.DocumentHighlightsRequestArgs>request.arguments;
return {response: this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true};
},
[CommandNames.ProjectInfo]: (request: protocol.Request) => {
var { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments;
return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true};
},
[CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => {
this.reloadProjects();
return {responseRequired: false};
}
};
public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) {
if (this.handlers[command]) {
+89 -19
View File
@@ -39,12 +39,12 @@ namespace ts.formatting {
public SpaceBetweenCloseBraceAndWhile: Rule;
public NoSpaceAfterCloseBrace: Rule;
// No space for indexer and dot
// No space for dot
public NoSpaceBeforeDot: Rule;
public NoSpaceAfterDot: Rule;
// No space before and after indexer
public NoSpaceBeforeOpenBracket: Rule;
public NoSpaceAfterOpenBracket: Rule;
public NoSpaceBeforeCloseBracket: Rule;
public NoSpaceAfterCloseBracket: Rule;
// Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}.
@@ -135,6 +135,7 @@ namespace ts.formatting {
public NoSpaceAfterOpenAngularBracket: Rule;
public NoSpaceBeforeCloseAngularBracket: Rule;
public NoSpaceAfterCloseAngularBracket: Rule;
public NoSpaceAfterTypeAssertion: Rule;
// Remove spaces in empty interface literals. e.g.: x: {}
public NoSpaceBetweenEmptyInterfaceBraceBrackets: Rule;
@@ -190,6 +191,13 @@ namespace ts.formatting {
public NoSpaceAfterOpenParen: Rule;
public NoSpaceBeforeCloseParen: Rule;
// Insert space after opening and before closing nonempty brackets
public SpaceAfterOpenBracket: Rule;
public SpaceBeforeCloseBracket: Rule;
public NoSpaceBetweenBrackets: Rule;
public NoSpaceAfterOpenBracket: Rule;
public NoSpaceBeforeCloseBracket: Rule;
// Insert space after function keyword for anonymous functions
public SpaceAfterAnonymousFunctionKeyword: Rule;
public NoSpaceAfterAnonymousFunctionKeyword: Rule;
@@ -205,6 +213,26 @@ namespace ts.formatting {
public NoSpaceBetweenYieldKeywordAndStar: Rule;
public SpaceBetweenYieldOrYieldStarAndOperand: Rule;
// Async-await
public SpaceBetweenAsyncAndFunctionKeyword: Rule;
public NoSpaceBetweenAsyncAndFunctionKeyword: Rule;
public SpaceAfterAwaitKeyword: Rule;
public NoSpaceAfterAwaitKeyword: Rule;
// Type alias declaration
public SpaceAfterTypeKeyword: Rule;
public NoSpaceAfterTypeKeyword: Rule;
// Tagged template string
public SpaceBetweenTagAndTemplateString: Rule;
public NoSpaceBetweenTagAndTemplateString: Rule;
// Union type
public SpaceBeforeBar: Rule;
public NoSpaceBeforeBar: Rule;
public SpaceAfterBar: Rule;
public NoSpaceAfterBar: Rule;
constructor() {
///
/// Common Rules
@@ -231,13 +259,13 @@ namespace ts.formatting {
this.SpaceBetweenCloseBraceAndWhile = new Rule(RuleDescriptor.create1(SyntaxKind.CloseBraceToken, SyntaxKind.WhileKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterCloseBrace = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBraceToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken, SyntaxKind.SemicolonToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// No space for indexer and dot
// No space for dot
this.NoSpaceBeforeDot = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.DotToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterDot = new Rule(RuleDescriptor.create3(SyntaxKind.DotToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// No space before and after indexer
this.NoSpaceBeforeOpenBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), RuleAction.Delete));
this.NoSpaceAfterCloseBracket = new Rule(RuleDescriptor.create3(SyntaxKind.CloseBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext ), RuleAction.Delete));
// Place a space before open brace in a function declaration
this.FunctionOpenBraceLeftTokenRange = Shared.TokenRange.AnyIncludingMultilineComments;
@@ -331,12 +359,13 @@ namespace ts.formatting {
this.NoSpaceAfterEllipsis = new Rule(RuleDescriptor.create1(SyntaxKind.DotDotDotToken, SyntaxKind.Identifier), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOptionalParameters = new Rule(RuleDescriptor.create3(SyntaxKind.QuestionToken, Shared.TokenRange.FromTokens([SyntaxKind.CloseParenToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), RuleAction.Delete));
// generics
this.NoSpaceBeforeOpenAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.TypeNames, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), RuleAction.Delete));
this.NoSpaceBetweenCloseParenAndAngularBracket = new Rule(RuleDescriptor.create1(SyntaxKind.CloseParenToken, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), RuleAction.Delete));
this.NoSpaceAfterOpenAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.LessThanToken, Shared.TokenRange.TypeNames), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), RuleAction.Delete));
this.NoSpaceBeforeCloseAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.GreaterThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), RuleAction.Delete));
this.NoSpaceAfterCloseAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.FromTokens([SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.GreaterThanToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterContext), RuleAction.Delete));
// generics and type assertions
this.NoSpaceBeforeOpenAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.TypeNames, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceBetweenCloseParenAndAngularBracket = new Rule(RuleDescriptor.create1(SyntaxKind.CloseParenToken, SyntaxKind.LessThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterOpenAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.LessThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceBeforeCloseAngularBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.GreaterThanToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterCloseAngularBracket = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.FromTokens([SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.GreaterThanToken, SyntaxKind.CommaToken])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), RuleAction.Delete));
this.NoSpaceAfterTypeAssertion = new Rule(RuleDescriptor.create3(SyntaxKind.GreaterThanToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), RuleAction.Delete));
// Remove spaces in empty interface literals. e.g.: x: {}
this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), RuleAction.Delete));
@@ -351,6 +380,27 @@ namespace ts.formatting {
this.NoSpaceBetweenYieldKeywordAndStar = new Rule(RuleDescriptor.create1(SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Delete));
this.SpaceBetweenYieldOrYieldStarAndOperand = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.YieldKeyword, SyntaxKind.AsteriskToken]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), RuleAction.Space));
// Async-await
this.SpaceBetweenAsyncAndFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.FunctionKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenAsyncAndFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.FunctionKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterAwaitKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.AwaitKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterAwaitKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.AwaitKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Type alias declaration
this.SpaceAfterTypeKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.TypeKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterTypeKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.TypeKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// template string
this.SpaceBetweenTagAndTemplateString = new Rule(RuleDescriptor.create3(SyntaxKind.Identifier, Shared.TokenRange.FromTokens([SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TemplateHead])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenTagAndTemplateString = new Rule(RuleDescriptor.create3(SyntaxKind.Identifier, Shared.TokenRange.FromTokens([SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TemplateHead])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// union type
this.SpaceBeforeBar = new Rule(RuleDescriptor.create3(SyntaxKind.BarToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBeforeBar = new Rule(RuleDescriptor.create3(SyntaxKind.BarToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterBar = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.BarToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterBar = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.BarToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// These rules are higher in priority than user-configurable rules.
this.HighPriorityCommonRules =
[
@@ -377,6 +427,11 @@ namespace ts.formatting {
this.NoSpaceBeforeOpenParenInFuncCall,
this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator,
this.SpaceAfterVoidOperator,
this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenAsyncAndFunctionKeyword,
this.SpaceAfterAwaitKeyword, this.NoSpaceAfterAwaitKeyword,
this.SpaceAfterTypeKeyword, this.NoSpaceAfterTypeKeyword,
this.SpaceBetweenTagAndTemplateString, this.NoSpaceBetweenTagAndTemplateString,
this.SpaceBeforeBar, this.NoSpaceBeforeBar, this.SpaceAfterBar, this.NoSpaceAfterBar,
// TypeScript-specific rules
this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport,
@@ -391,6 +446,7 @@ namespace ts.formatting {
this.NoSpaceAfterOpenAngularBracket,
this.NoSpaceBeforeCloseAngularBracket,
this.NoSpaceAfterCloseAngularBracket,
this.NoSpaceAfterTypeAssertion,
this.SpaceBeforeAt,
this.NoSpaceAfterAt,
this.SpaceAfterDecorator,
@@ -402,8 +458,8 @@ namespace ts.formatting {
this.NoSpaceBeforeSemicolon,
this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock,
this.NoSpaceBeforeComma,
this.NoSpaceBeforeOpenBracket, this.NoSpaceAfterOpenBracket,
this.NoSpaceBeforeCloseBracket, this.NoSpaceAfterCloseBracket,
this.NoSpaceBeforeOpenBracket,
this.NoSpaceAfterCloseBracket,
this.SpaceAfterSemicolon,
this.NoSpaceBeforeOpenParenInFuncDecl,
this.SpaceBetweenStatements, this.SpaceAfterTryFinally
@@ -448,6 +504,13 @@ namespace ts.formatting {
this.NoSpaceAfterOpenParen = new Rule(RuleDescriptor.create3(SyntaxKind.OpenParenToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseParen = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Insert space after opening and before closing nonempty brackets
this.SpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenBrackets = new Rule(RuleDescriptor.create1(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceAfterOpenBracket = new Rule(RuleDescriptor.create3(SyntaxKind.OpenBracketToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.NoSpaceBeforeCloseBracket = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CloseBracketToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Insert space after function keyword for anonymous functions
this.SpaceAfterAnonymousFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.FunctionKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space));
this.NoSpaceAfterAnonymousFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.FunctionKeyword, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Delete));
@@ -704,13 +767,15 @@ namespace ts.formatting {
return context.contextNode.kind === SyntaxKind.TypeLiteral;// && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration;
}
static IsTypeArgumentOrParameter(token: TextRangeWithKind, parent: Node): boolean {
static IsTypeArgumentOrParameterOrAssertion(token: TextRangeWithKind, parent: Node): boolean {
if (token.kind !== SyntaxKind.LessThanToken && token.kind !== SyntaxKind.GreaterThanToken) {
return false;
}
switch (parent.kind) {
case SyntaxKind.TypeReference:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
@@ -721,6 +786,7 @@ namespace ts.formatting {
case SyntaxKind.ConstructSignature:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.ExpressionWithTypeArguments:
return true;
default:
return false;
@@ -728,9 +794,13 @@ namespace ts.formatting {
}
}
static IsTypeArgumentOrParameterContext(context: FormattingContext): boolean {
return Rules.IsTypeArgumentOrParameter(context.currentTokenSpan, context.currentTokenParent) ||
Rules.IsTypeArgumentOrParameter(context.nextTokenSpan, context.nextTokenParent);
static IsTypeArgumentOrParameterOrAssertionContext(context: FormattingContext): boolean {
return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) ||
Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent);
}
static IsTypeAssertionContext(context: FormattingContext): boolean {
return context.contextNode.kind === SyntaxKind.TypeAssertionExpression;
}
static IsVoidOpContext(context: FormattingContext): boolean {
+11
View File
@@ -71,6 +71,17 @@ namespace ts.formatting {
rules.push(this.globalRules.NoSpaceBetweenParens);
}
if ( options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets ) {
rules.push( this.globalRules.SpaceAfterOpenBracket );
rules.push( this.globalRules.SpaceBeforeCloseBracket );
rules.push( this.globalRules.NoSpaceBetweenBrackets );
}
else {
rules.push( this.globalRules.NoSpaceAfterOpenBracket );
rules.push( this.globalRules.NoSpaceBeforeCloseBracket );
rules.push( this.globalRules.NoSpaceBetweenBrackets );
}
if (options.InsertSpaceAfterSemicolonInForStatements) {
rules.push(this.globalRules.SpaceAfterSemicolonInFor);
}
+13 -2
View File
@@ -408,6 +408,7 @@ namespace ts.formatting {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
@@ -418,6 +419,7 @@ namespace ts.formatting {
case SyntaxKind.DefaultClause:
case SyntaxKind.CaseClause:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.VariableStatement:
@@ -427,6 +429,17 @@ namespace ts.formatting {
case SyntaxKind.ConditionalExpression:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.JsxElement:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.Parameter:
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.UnionType:
case SyntaxKind.ParenthesizedType:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AwaitExpression:
return true;
}
return false;
@@ -446,8 +459,6 @@ namespace ts.formatting {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
+440 -199
View File
File diff suppressed because it is too large Load Diff
+48 -9
View File
@@ -60,10 +60,12 @@ namespace ts {
getNewLine?(): string;
getProjectVersion?(): string;
useCaseSensitiveFileNames?(): boolean;
getModuleResolutionsForFile?(fileName: string): string;
}
/** Public interface of the the of a config service shim instance.*/
export interface CoreServicesShimHost extends Logger {
export interface CoreServicesShimHost extends Logger, ModuleResolutionHost {
/**
* Returns a JSON-encoded value of the type: string[]
*
@@ -205,6 +207,11 @@ namespace ts {
getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string;
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string;
/**
* Returns JSON-encoded value of the type TextInsertion.
*/
getDocCommentTemplateAtPosition(fileName: string, position: number): string;
getEmitOutput(fileName: string): string;
}
@@ -265,8 +272,18 @@ namespace ts {
private files: string[];
private loggingEnabled = false;
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => string[];
constructor(private shimHost: LanguageServiceShimHost) {
// if shimHost is a COM object then property check will become method call with no arguments.
// 'in' does not have this effect.
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = (moduleNames: string[], containingFile: string) => {
let resolutionsInFile = <Map<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile));
return map(moduleNames, name => lookUp(resolutionsInFile, name));
};
}
}
public log(s: string): void {
@@ -405,6 +422,14 @@ namespace ts {
}
return JSON.parse(encoded);
}
public fileExists(fileName: string): boolean {
return this.shimHost.fileExists(fileName);
}
public readFile(fileName: string): string {
return this.shimHost.readFile(fileName);
}
}
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): any {
@@ -529,7 +554,7 @@ namespace ts {
}
private realizeDiagnostics(diagnostics: Diagnostic[]): { message: string; start: number; length: number; category: string; }[]{
var newLine = this.getNewLine();
var newLine = getNewLineOrDefaultFromHost(this.host);
return ts.realizeDiagnostics(diagnostics, newLine);
}
@@ -571,10 +596,6 @@ namespace ts {
});
}
private getNewLine(): string {
return this.host.getNewLine ? this.host.getNewLine() : "\r\n";
}
public getSyntacticDiagnostics(fileName: string): string {
return this.forwardJSONCall(
"getSyntacticDiagnostics('" + fileName + "')",
@@ -751,7 +772,10 @@ namespace ts {
return this.forwardJSONCall(
"getDocumentHighlights('" + fileName + "', " + position + ")",
() => {
return this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
var results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch));
// workaround for VS document higlighting issue - keep only items from the initial file
let normalizedName = normalizeSlashes(fileName).toLowerCase();
return filter(results, r => normalizeSlashes(r.fileName).toLowerCase() === normalizedName);
});
}
@@ -811,6 +835,13 @@ namespace ts {
});
}
public getDocCommentTemplateAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")",
() => this.languageService.getDocCommentTemplateAtPosition(fileName, position)
);
}
/// NAVIGATE TO
/** Return a list of symbols that are interesting to navigate to */
@@ -907,6 +938,13 @@ namespace ts {
private forwardJSONCall(actionDescription: string, action: () => any): any {
return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance);
}
public resolveModuleName(fileName: string, moduleName: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => {
let compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
return resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
});
}
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
@@ -916,6 +954,7 @@ namespace ts {
var convertResult = {
referencedFiles: <IFileReference[]>[],
importedFiles: <IFileReference[]>[],
ambientExternalModules: result.ambientExternalModules,
isLibFile: result.isLibFile
};
@@ -1058,4 +1097,4 @@ module TypeScript.Services {
}
/* @internal */
let toolsVersion = "1.5";
const toolsVersion = "1.6";
+1 -3
View File
@@ -611,13 +611,11 @@ namespace ts.SignatureHelp {
let displayParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation));
let isOptional = hasQuestionToken(parameter.valueDeclaration);
return {
name: parameter.name,
documentation: parameter.getDocumentationComment(),
displayParts,
isOptional
isOptional: typeChecker.isOptionalParameter(<ParameterDeclaration>parameter.valueDeclaration)
};
}
+95 -1
View File
@@ -414,6 +414,93 @@ namespace ts {
}
}
}
export function isInString(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
return token && token.kind === SyntaxKind.StringLiteral && position > token.getStart();
}
export function isInComment(sourceFile: SourceFile, position: number) {
return isInCommentHelper(sourceFile, position, /*predicate*/ undefined);
}
/**
* Returns true if the cursor at position in sourceFile is within a comment that additionally
* satisfies predicate, and false otherwise.
*/
export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean {
let token = getTokenAtPosition(sourceFile, position);
if (token && position <= token.getStart()) {
let 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):
//
// // asdf ^\n
//
// But for multi-line comments, we don't want to be inside the comment in the following case:
//
// /* asdf */^
//
// Internally, we represent the end of the comment at the newline and closing '/', respectively.
return predicate ?
forEach(commentRanges, c => c.pos < position &&
(c.kind == SyntaxKind.SingleLineCommentTrivia ? position <= c.end : position < c.end) &&
predicate(c)) :
forEach(commentRanges, c => c.pos < position &&
(c.kind == SyntaxKind.SingleLineCommentTrivia ? position <= c.end : position < c.end));
}
return false;
}
export function hasDocComment(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
// First, we have to see if this position actually landed in a comment.
let 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] === '*';
}
}
/**
* Get the corresponding JSDocTag node if the position is in a jsDoc comment
*/
export function getJsDocTagAtPosition(sourceFile: SourceFile, position: number): JSDocTag {
let node = ts.getTokenAtPosition(sourceFile, position);
if (isToken(node)) {
switch (node.kind) {
case SyntaxKind.VarKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
// if the current token is var, let or const, skip the VariableDeclarationList
node = node.parent === undefined ? undefined : node.parent.parent;
break;
default:
node = node.parent;
break;
}
}
if (node) {
let jsDocComment = node.jsDocComment;
if (jsDocComment) {
for (let tag of jsDocComment.tags) {
if (tag.pos <= position && position <= tag.end) {
return tag;
}
}
}
}
return undefined;
}
function nodeHasTokens(n: Node): boolean {
// If we have a token or node that has a non-zero width, it must have tokens.
@@ -586,7 +673,6 @@ namespace ts {
else if (flags & SymbolFlags.TypeAlias) { return SymbolDisplayPartKind.aliasName; }
else if (flags & SymbolFlags.Alias) { return SymbolDisplayPartKind.aliasName; }
return SymbolDisplayPartKind.text;
}
}
@@ -625,6 +711,14 @@ namespace ts {
return displayPart(text, SymbolDisplayPartKind.text);
}
const carriageReturnLineFeed = "\r\n";
/**
* The default is CRLF.
*/
export function getNewLineOrDefaultFromHost(host: LanguageServiceHost | LanguageServiceShimHost) {
return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed;
}
export function lineBreakPart() {
return displayPart("\n", SymbolDisplayPartKind.lineBreak);
}
+12 -12
View File
@@ -75,28 +75,28 @@ function delint(sourceFile) {
delintNode(sourceFile);
function delintNode(node) {
switch (node.kind) {
case 196 /* ForStatement */:
case 197 /* ForInStatement */:
case 195 /* WhileStatement */:
case 194 /* DoStatement */:
if (node.statement.kind !== 189 /* Block */) {
case 197 /* ForStatement */:
case 198 /* ForInStatement */:
case 196 /* WhileStatement */:
case 195 /* DoStatement */:
if (node.statement.kind !== 190 /* Block */) {
report(node, "A looping statement's contents should be wrapped in a block body.");
}
break;
case 193 /* IfStatement */:
case 194 /* IfStatement */:
var ifStatement = node;
if (ifStatement.thenStatement.kind !== 189 /* Block */) {
if (ifStatement.thenStatement.kind !== 190 /* Block */) {
report(ifStatement.thenStatement, "An if statement's contents should be wrapped in a block body.");
}
if (ifStatement.elseStatement &&
ifStatement.elseStatement.kind !== 189 /* Block */ &&
ifStatement.elseStatement.kind !== 193 /* IfStatement */) {
ifStatement.elseStatement.kind !== 190 /* Block */ &&
ifStatement.elseStatement.kind !== 194 /* IfStatement */) {
report(ifStatement.elseStatement, "An else statement's contents should be wrapped in a block body.");
}
break;
case 178 /* BinaryExpression */:
case 179 /* BinaryExpression */:
var op = node.operatorToken.kind;
if (op === 29 /* EqualsEqualsToken */ || op == 30 /* ExclamationEqualsToken */) {
if (op === 30 /* EqualsEqualsToken */ || op == 31 /* ExclamationEqualsToken */) {
report(node, "Use '===' and '!=='.");
}
break;
@@ -112,7 +112,7 @@ exports.delint = delint;
var fileNames = process.argv.slice(2);
fileNames.forEach(function (fileName) {
// Parse a file
var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), 2 /* ES6 */, true);
var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), 2 /* ES6 */, /*setParentNodes */ true);
// delint it
delint(sourceFile);
});
@@ -22,8 +22,8 @@ System.register(['foo'], function(exports_1) {
var cls, cls2, x, y, z, M;
return {
setters:[
function (_alias) {
alias = _alias;
function (alias_1) {
alias = alias_1;
}],
execute: function() {
cls = alias.Class;
@@ -21,8 +21,8 @@ System.register(["foo"], function(exports_1) {
var cls, cls2, x, y, z, M;
return {
setters:[
function (_foo_1) {
foo_1 = _foo_1;
function (foo_1_1) {
foo_1 = foo_1_1;
}],
execute: function() {
cls = foo_1.alias.Class;
@@ -1,6 +1,7 @@
tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts(9,7): error TS2415: Class 'Derived<U>' incorrectly extends base class 'Base'.
Types of property 'x' are incompatible.
Type 'U' is not assignable to type 'string'.
Type 'String' is not assignable to type 'string'.
==== tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSupertype.ts (1 errors) ====
@@ -17,5 +18,6 @@ tests/cases/conformance/types/typeRelationships/apparentType/apparentTypeSuperty
!!! error TS2415: Class 'Derived<U>' incorrectly extends base class 'Base'.
!!! error TS2415: Types of property 'x' are incompatible.
!!! error TS2415: Type 'U' is not assignable to type 'string'.
!!! error TS2415: Type 'String' is not assignable to type 'string'.
x: U;
}
@@ -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.d.ts, 1249, 31))
>Symbol : Symbol(Symbol, Decl(lib.d.ts, 1199, 52), Decl(lib.d.ts, 1305, 11))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 1249, 31))
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 3890, 31))
>Symbol : Symbol(Symbol, Decl(lib.d.ts, 3840, 52), Decl(lib.d.ts, 3946, 11))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, 3890, 31))
let result = [];
>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7))
@@ -294,8 +294,8 @@ module EmptyTypes {
// Order matters here so test all the variants
var a1 = [{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }];
>a1 : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>a1 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : { x: any; y: string; }[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -313,8 +313,8 @@ module EmptyTypes {
>'a' : string
var a2 = [{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }];
>a2 : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>a2 : { x: any; y: string; }[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>{ x: anyObj, y: 'a' } : { x: any; y: string; }
>x : any
>anyObj : any
@@ -332,8 +332,8 @@ module EmptyTypes {
>'a' : string
var a3 = [{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }];
>a3 : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>a3 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -639,7 +639,7 @@ module NonEmptyTypes {
>x : number
>y : base
>base : base
>[{ x: 7, y: new derived() }, { x: 5, y: new base() }] : ({ x: number; y: derived; } | { x: number; y: base; })[]
>[{ x: 7, y: new derived() }, { x: 5, y: new base() }] : { x: number; y: base; }[]
>{ x: 7, y: new derived() } : { x: number; y: derived; }
>x : number
>7 : number
@@ -658,7 +658,7 @@ module NonEmptyTypes {
>x : boolean
>y : base
>base : base
>[{ x: true, y: new derived() }, { x: false, y: new base() }] : ({ x: boolean; y: derived; } | { x: boolean; y: base; })[]
>[{ x: true, y: new derived() }, { x: false, y: new base() }] : { x: boolean; y: base; }[]
>{ x: true, y: new derived() } : { x: boolean; y: derived; }
>x : boolean
>true : boolean
@@ -697,8 +697,8 @@ module NonEmptyTypes {
// Order matters here so test all the variants
var a1 = [{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }];
>a1 : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>a1 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : { x: any; y: string; }[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -716,8 +716,8 @@ module NonEmptyTypes {
>'a' : string
var a2 = [{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }];
>a2 : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>a2 : { x: any; y: string; }[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>{ x: anyObj, y: 'a' } : { x: any; y: string; }
>x : any
>anyObj : any
@@ -735,8 +735,8 @@ module NonEmptyTypes {
>'a' : string
var a3 = [{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }];
>a3 : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>a3 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -769,29 +769,29 @@ module NonEmptyTypes {
>base2 : typeof base2
var b1 = [baseObj, base2Obj, ifaceObj];
>b1 : (base | base2 | iface)[]
>[baseObj, base2Obj, ifaceObj] : (base | base2 | iface)[]
>b1 : iface[]
>[baseObj, base2Obj, ifaceObj] : iface[]
>baseObj : base
>base2Obj : base2
>ifaceObj : iface
var b2 = [base2Obj, baseObj, ifaceObj];
>b2 : (base2 | base | iface)[]
>[base2Obj, baseObj, ifaceObj] : (base2 | base | iface)[]
>b2 : iface[]
>[base2Obj, baseObj, ifaceObj] : iface[]
>base2Obj : base2
>baseObj : base
>ifaceObj : iface
var b3 = [baseObj, ifaceObj, base2Obj];
>b3 : (base | iface | base2)[]
>[baseObj, ifaceObj, base2Obj] : (base | iface | base2)[]
>b3 : iface[]
>[baseObj, ifaceObj, base2Obj] : iface[]
>baseObj : base
>ifaceObj : iface
>base2Obj : base2
var b4 = [ifaceObj, baseObj, base2Obj];
>b4 : (iface | base | base2)[]
>[ifaceObj, baseObj, base2Obj] : (iface | base | base2)[]
>b4 : iface[]
>[ifaceObj, baseObj, base2Obj] : iface[]
>ifaceObj : iface
>baseObj : base
>base2Obj : base2
@@ -36,8 +36,8 @@ var cs = [a, b, c]; // { x: number; y?: number };[]
>c : { x: number; a?: number; }
var ds = [(x: Object) => 1, (x: string) => 2]; // { (x:Object) => number }[]
>ds : (((x: Object) => number) | ((x: string) => number))[]
>[(x: Object) => 1, (x: string) => 2] : (((x: Object) => number) | ((x: string) => number))[]
>ds : ((x: Object) => number)[]
>[(x: Object) => 1, (x: string) => 2] : ((x: Object) => number)[]
>(x: Object) => 1 : (x: Object) => number
>x : Object
>Object : Object
@@ -47,8 +47,8 @@ var ds = [(x: Object) => 1, (x: string) => 2]; // { (x:Object) => number }[]
>2 : number
var es = [(x: string) => 2, (x: Object) => 1]; // { (x:string) => number }[]
>es : (((x: string) => number) | ((x: Object) => number))[]
>[(x: string) => 2, (x: Object) => 1] : (((x: string) => number) | ((x: Object) => number))[]
>es : ((x: string) => number)[]
>[(x: string) => 2, (x: Object) => 1] : ((x: string) => number)[]
>(x: string) => 2 : (x: string) => number
>x : string
>2 : number
@@ -72,14 +72,14 @@ var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
interface myArray extends Array<Number> { }
>myArray : Symbol(myArray, Decl(arrayLiterals2ES6.ts, 40, 67))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1452, 1))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 4091, 1))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1452, 1))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 4091, 1))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1556, 1))
>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 4209, 1))
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES6.ts, 44, 3))
@@ -77,8 +77,8 @@ var myDerivedList: DerivedList<number>;
>DerivedList : DerivedList<U>
var as = [list, myDerivedList]; // List<number>[]
>as : (List<number> | DerivedList<number>)[]
>[list, myDerivedList] : (List<number> | DerivedList<number>)[]
>as : List<number>[]
>[list, myDerivedList] : List<number>[]
>list : List<number>
>myDerivedList : DerivedList<number>
@@ -1,35 +0,0 @@
tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts(17,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts(26,10): error TS2349: Cannot invoke an expression whose type lacks a call signature.
==== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts (2 errors) ====
// valid uses of arrays of function types
var x = [() => 1, () => { }];
var r2 = x[0]();
class C {
foo: string;
}
var y = [C, C];
var r3 = new y[0]();
var a: { (x: number): number; (x: string): string; };
var b: { (x: number): number; (x: string): string; };
var c: { (x: number): number; (x: any): any; };
var z = [a, b, c];
var r4 = z[0];
var r5 = r4(''); // any not string
~~
!!! error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
var r5b = r4(1);
var a2: { <T>(x: T): number; (x: string): string;};
var b2: { <T>(x: T): number; (x: string): string; };
var c2: { (x: number): number; <T>(x: T): any; };
var z2 = [a2, b2, c2];
var r6 = z2[0];
var r7 = r6(''); // any not string
~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature.
@@ -0,0 +1,93 @@
=== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts ===
// valid uses of arrays of function types
var x = [() => 1, () => { }];
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 2, 3))
var r2 = x[0]();
>r2 : Symbol(r2, Decl(arrayOfFunctionTypes3.ts, 3, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 2, 3))
class C {
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
foo: string;
>foo : Symbol(foo, Decl(arrayOfFunctionTypes3.ts, 5, 9))
}
var y = [C, C];
>y : Symbol(y, Decl(arrayOfFunctionTypes3.ts, 8, 3))
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
var r3 = new y[0]();
>r3 : Symbol(r3, Decl(arrayOfFunctionTypes3.ts, 9, 3))
>y : Symbol(y, Decl(arrayOfFunctionTypes3.ts, 8, 3))
var a: { (x: number): number; (x: string): string; };
>a : Symbol(a, Decl(arrayOfFunctionTypes3.ts, 11, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 11, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 11, 31))
var b: { (x: number): number; (x: string): string; };
>b : Symbol(b, Decl(arrayOfFunctionTypes3.ts, 12, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 12, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 12, 31))
var c: { (x: number): number; (x: any): any; };
>c : Symbol(c, Decl(arrayOfFunctionTypes3.ts, 13, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 13, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 13, 31))
var z = [a, b, c];
>z : Symbol(z, Decl(arrayOfFunctionTypes3.ts, 14, 3))
>a : Symbol(a, Decl(arrayOfFunctionTypes3.ts, 11, 3))
>b : Symbol(b, Decl(arrayOfFunctionTypes3.ts, 12, 3))
>c : Symbol(c, Decl(arrayOfFunctionTypes3.ts, 13, 3))
var r4 = z[0];
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
>z : Symbol(z, Decl(arrayOfFunctionTypes3.ts, 14, 3))
var r5 = r4(''); // any not string
>r5 : Symbol(r5, Decl(arrayOfFunctionTypes3.ts, 16, 3))
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
var r5b = r4(1);
>r5b : Symbol(r5b, Decl(arrayOfFunctionTypes3.ts, 17, 3))
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
var a2: { <T>(x: T): number; (x: string): string;};
>a2 : Symbol(a2, Decl(arrayOfFunctionTypes3.ts, 19, 3))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 19, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 19, 14))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 19, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 19, 30))
var b2: { <T>(x: T): number; (x: string): string; };
>b2 : Symbol(b2, Decl(arrayOfFunctionTypes3.ts, 20, 3))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 20, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 20, 14))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 20, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 20, 30))
var c2: { (x: number): number; <T>(x: T): any; };
>c2 : Symbol(c2, Decl(arrayOfFunctionTypes3.ts, 21, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 21, 11))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 21, 32))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 21, 35))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 21, 32))
var z2 = [a2, b2, c2];
>z2 : Symbol(z2, Decl(arrayOfFunctionTypes3.ts, 23, 3))
>a2 : Symbol(a2, Decl(arrayOfFunctionTypes3.ts, 19, 3))
>b2 : Symbol(b2, Decl(arrayOfFunctionTypes3.ts, 20, 3))
>c2 : Symbol(c2, Decl(arrayOfFunctionTypes3.ts, 21, 3))
var r6 = z2[0];
>r6 : Symbol(r6, Decl(arrayOfFunctionTypes3.ts, 24, 3))
>z2 : Symbol(z2, Decl(arrayOfFunctionTypes3.ts, 23, 3))
var r7 = r6(''); // any not string
>r7 : Symbol(r7, Decl(arrayOfFunctionTypes3.ts, 25, 3))
>r6 : Symbol(r6, Decl(arrayOfFunctionTypes3.ts, 24, 3))
@@ -0,0 +1,116 @@
=== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts ===
// valid uses of arrays of function types
var x = [() => 1, () => { }];
>x : (() => void)[]
>[() => 1, () => { }] : (() => void)[]
>() => 1 : () => number
>1 : number
>() => { } : () => void
var r2 = x[0]();
>r2 : void
>x[0]() : void
>x[0] : () => void
>x : (() => void)[]
>0 : number
class C {
>C : C
foo: string;
>foo : string
}
var y = [C, C];
>y : typeof C[]
>[C, C] : typeof C[]
>C : typeof C
>C : typeof C
var r3 = new y[0]();
>r3 : C
>new y[0]() : C
>y[0] : typeof C
>y : typeof C[]
>0 : number
var a: { (x: number): number; (x: string): string; };
>a : { (x: number): number; (x: string): string; }
>x : number
>x : string
var b: { (x: number): number; (x: string): string; };
>b : { (x: number): number; (x: string): string; }
>x : number
>x : string
var c: { (x: number): number; (x: any): any; };
>c : { (x: number): number; (x: any): any; }
>x : number
>x : any
var z = [a, b, c];
>z : { (x: number): number; (x: any): any; }[]
>[a, b, c] : { (x: number): number; (x: any): any; }[]
>a : { (x: number): number; (x: string): string; }
>b : { (x: number): number; (x: string): string; }
>c : { (x: number): number; (x: any): any; }
var r4 = z[0];
>r4 : { (x: number): number; (x: any): any; }
>z[0] : { (x: number): number; (x: any): any; }
>z : { (x: number): number; (x: any): any; }[]
>0 : number
var r5 = r4(''); // any not string
>r5 : any
>r4('') : any
>r4 : { (x: number): number; (x: any): any; }
>'' : string
var r5b = r4(1);
>r5b : number
>r4(1) : number
>r4 : { (x: number): number; (x: any): any; }
>1 : number
var a2: { <T>(x: T): number; (x: string): string;};
>a2 : { <T>(x: T): number; (x: string): string; }
>T : T
>x : T
>T : T
>x : string
var b2: { <T>(x: T): number; (x: string): string; };
>b2 : { <T>(x: T): number; (x: string): string; }
>T : T
>x : T
>T : T
>x : string
var c2: { (x: number): number; <T>(x: T): any; };
>c2 : { (x: number): number; <T>(x: T): any; }
>x : number
>T : T
>x : T
>T : T
var z2 = [a2, b2, c2];
>z2 : { (x: number): number; <T>(x: T): any; }[]
>[a2, b2, c2] : { (x: number): number; <T>(x: T): any; }[]
>a2 : { <T>(x: T): number; (x: string): string; }
>b2 : { <T>(x: T): number; (x: string): string; }
>c2 : { (x: number): number; <T>(x: T): any; }
var r6 = z2[0];
>r6 : { (x: number): number; <T>(x: T): any; }
>z2[0] : { (x: number): number; <T>(x: T): any; }
>z2 : { (x: number): number; <T>(x: T): any; }[]
>0 : number
var r7 = r6(''); // any not string
>r7 : any
>r6('') : any
>r6 : { (x: number): number; <T>(x: T): any; }
>'' : string
@@ -1,18 +1,21 @@
tests/cases/compiler/assignmentCompat1.ts(4,1): error TS2322: Type '{ [index: string]: any; }' is not assignable to type '{ one: number; }'.
Property 'one' is missing in type '{ [index: string]: any; }'.
tests/cases/compiler/assignmentCompat1.ts(5,1): error TS2322: Type '{ one: number; }' is not assignable to type '{ [index: string]: any; }'.
Index signature is missing in type '{ one: number; }'.
tests/cases/compiler/assignmentCompat1.ts(6,1): error TS2322: Type '{ [index: number]: any; }' is not assignable to type '{ one: number; }'.
Property 'one' is missing in type '{ [index: number]: any; }'.
==== tests/cases/compiler/assignmentCompat1.ts (2 errors) ====
var x = {one: 1};
var y: {[index:string]: any};
x = y;
var x = { one: 1 };
var y: { [index: string]: any };
var z: { [index: number]: any };
x = y; // Error
~
!!! error TS2322: Type '{ [index: string]: any; }' is not assignable to type '{ one: number; }'.
!!! error TS2322: Property 'one' is missing in type '{ [index: string]: any; }'.
y = x;
y = x; // Ok because index signature type is any
x = z; // Error
~
!!! error TS2322: Type '{ one: number; }' is not assignable to type '{ [index: string]: any; }'.
!!! error TS2322: Index signature is missing in type '{ one: number; }'.
!!! error TS2322: Type '{ [index: number]: any; }' is not assignable to type '{ one: number; }'.
!!! error TS2322: Property 'one' is missing in type '{ [index: number]: any; }'.
z = x; // Ok because index signature type is any
+13 -7
View File
@@ -1,12 +1,18 @@
//// [assignmentCompat1.ts]
var x = {one: 1};
var y: {[index:string]: any};
x = y;
y = x;
var x = { one: 1 };
var y: { [index: string]: any };
var z: { [index: number]: any };
x = y; // Error
y = x; // Ok because index signature type is any
x = z; // Error
z = x; // Ok because index signature type is any
//// [assignmentCompat1.js]
var x = { one: 1 };
var y;
x = y;
y = x;
var z;
x = y; // Error
y = x; // Ok because index signature type is any
x = z; // Error
z = x; // Ok because index signature type is any
@@ -12,12 +12,14 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts(33,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived'.
Type 'Base' is not assignable to type 'Derived'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts(36,9): error TS2322: Type '{ [x: number]: Derived2; }' is not assignable to type 'A<T>'.
Index signatures are incompatible.
Type 'Derived2' is not assignable to type 'T'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts(37,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived2; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived2'.
Type 'Base' is not assignable to type 'Derived2'.
==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts (6 errors) ====
@@ -72,6 +74,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived'.
var b2: { [x: number]: Derived2; }
a = b2; // error
@@ -84,6 +87,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived2; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived2'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'.
var b3: { [x: number]: T; }
a = b3; // ok
@@ -12,12 +12,14 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts(33,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived'.
Type 'Base' is not assignable to type 'Derived'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts(36,9): error TS2322: Type '{ [x: number]: Derived2; }' is not assignable to type 'A<T>'.
Index signatures are incompatible.
Type 'Derived2' is not assignable to type 'T'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts(37,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived2; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived2'.
Type 'Base' is not assignable to type 'Derived2'.
==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts (6 errors) ====
@@ -72,6 +74,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived'.
var b2: { [x: number]: Derived2; }
a = b2; // error
@@ -84,6 +87,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: number]: Derived2; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived2'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'.
var b3: { [x: number]: T; }
a = b3; // ok
@@ -18,12 +18,14 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts(47,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived'.
Type 'Base' is not assignable to type 'Derived'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts(50,9): error TS2322: Type '{ [x: string]: Derived2; }' is not assignable to type 'A<T>'.
Index signatures are incompatible.
Type 'Derived2' is not assignable to type 'T'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts(51,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived2; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived2'.
Type 'Base' is not assignable to type 'Derived2'.
==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts (8 errors) ====
@@ -100,6 +102,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived'.
var b4: { [x: string]: Derived2; };
a3 = b4; // error
@@ -112,5 +115,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived2; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived2'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'.
}
}
@@ -18,12 +18,14 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts(47,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived'.
Type 'Base' is not assignable to type 'Derived'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts(50,9): error TS2322: Type '{ [x: string]: Derived2; }' is not assignable to type 'A<T>'.
Index signatures are incompatible.
Type 'Derived2' is not assignable to type 'T'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts(51,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived2; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'Derived2'.
Type 'Base' is not assignable to type 'Derived2'.
==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts (8 errors) ====
@@ -100,6 +102,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived'.
var b4: { [x: string]: Derived2; };
a3 = b4; // error
@@ -112,5 +115,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: Derived2; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'Derived2'.
!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'.
}
}
@@ -5,6 +5,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer3.ts(21,9): error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: string; }'.
Index signatures are incompatible.
Type 'T' is not assignable to type 'string'.
Type 'Derived' is not assignable to type 'string'.
==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer3.ts (3 errors) ====
@@ -39,5 +40,6 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
!!! error TS2322: Type 'A<T>' is not assignable to type '{ [x: string]: string; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type 'T' is not assignable to type 'string'.
!!! error TS2322: Type 'Derived' is not assignable to type 'string'.
}
}
@@ -1,17 +0,0 @@
tests/cases/compiler/assignmentCompatability36.ts(9,1): error TS2322: Type 'interfaceWithPublicAndOptional<number, string>' is not assignable to type '{ [index: string]: any; }'.
Index signature is missing in type 'interfaceWithPublicAndOptional<number, string>'.
==== tests/cases/compiler/assignmentCompatability36.ts (1 errors) ====
module __test1__ {
export interface interfaceWithPublicAndOptional<T,U> { one: T; two?: U; }; var obj4: interfaceWithPublicAndOptional<number,string> = { one: 1 };;
export var __val__obj4 = obj4;
}
module __test2__ {
export var aa:{[index:string]:any;};;
export var __val__aa = aa;
}
__test2__.__val__aa = __test1__.__val__obj4
~~~~~~~~~~~~~~~~~~~
!!! error TS2322: Type 'interfaceWithPublicAndOptional<number, string>' is not assignable to type '{ [index: string]: any; }'.
!!! error TS2322: Index signature is missing in type 'interfaceWithPublicAndOptional<number, string>'.
@@ -0,0 +1,39 @@
=== tests/cases/compiler/assignmentCompatability36.ts ===
module __test1__ {
>__test1__ : Symbol(__test1__, Decl(assignmentCompatability36.ts, 0, 0))
export interface interfaceWithPublicAndOptional<T,U> { one: T; two?: U; }; var obj4: interfaceWithPublicAndOptional<number,string> = { one: 1 };;
>interfaceWithPublicAndOptional : Symbol(interfaceWithPublicAndOptional, Decl(assignmentCompatability36.ts, 0, 18))
>T : Symbol(T, Decl(assignmentCompatability36.ts, 1, 52))
>U : Symbol(U, Decl(assignmentCompatability36.ts, 1, 54))
>one : Symbol(one, Decl(assignmentCompatability36.ts, 1, 58))
>T : Symbol(T, Decl(assignmentCompatability36.ts, 1, 52))
>two : Symbol(two, Decl(assignmentCompatability36.ts, 1, 66))
>U : Symbol(U, Decl(assignmentCompatability36.ts, 1, 54))
>obj4 : Symbol(obj4, Decl(assignmentCompatability36.ts, 1, 83))
>interfaceWithPublicAndOptional : Symbol(interfaceWithPublicAndOptional, Decl(assignmentCompatability36.ts, 0, 18))
>one : Symbol(one, Decl(assignmentCompatability36.ts, 1, 139))
export var __val__obj4 = obj4;
>__val__obj4 : Symbol(__val__obj4, Decl(assignmentCompatability36.ts, 2, 14))
>obj4 : Symbol(obj4, Decl(assignmentCompatability36.ts, 1, 83))
}
module __test2__ {
>__test2__ : Symbol(__test2__, Decl(assignmentCompatability36.ts, 3, 1))
export var aa:{[index:string]:any;};;
>aa : Symbol(aa, Decl(assignmentCompatability36.ts, 5, 14))
>index : Symbol(index, Decl(assignmentCompatability36.ts, 5, 20))
export var __val__aa = aa;
>__val__aa : Symbol(__val__aa, Decl(assignmentCompatability36.ts, 6, 14))
>aa : Symbol(aa, Decl(assignmentCompatability36.ts, 5, 14))
}
__test2__.__val__aa = __test1__.__val__obj4
>__test2__.__val__aa : Symbol(__test2__.__val__aa, Decl(assignmentCompatability36.ts, 6, 14))
>__test2__ : Symbol(__test2__, Decl(assignmentCompatability36.ts, 3, 1))
>__val__aa : Symbol(__test2__.__val__aa, Decl(assignmentCompatability36.ts, 6, 14))
>__test1__.__val__obj4 : Symbol(__test1__.__val__obj4, Decl(assignmentCompatability36.ts, 2, 14))
>__test1__ : Symbol(__test1__, Decl(assignmentCompatability36.ts, 0, 0))
>__val__obj4 : Symbol(__test1__.__val__obj4, Decl(assignmentCompatability36.ts, 2, 14))
@@ -0,0 +1,42 @@
=== tests/cases/compiler/assignmentCompatability36.ts ===
module __test1__ {
>__test1__ : typeof __test1__
export interface interfaceWithPublicAndOptional<T,U> { one: T; two?: U; }; var obj4: interfaceWithPublicAndOptional<number,string> = { one: 1 };;
>interfaceWithPublicAndOptional : interfaceWithPublicAndOptional<T, U>
>T : T
>U : U
>one : T
>T : T
>two : U
>U : U
>obj4 : interfaceWithPublicAndOptional<number, string>
>interfaceWithPublicAndOptional : interfaceWithPublicAndOptional<T, U>
>{ one: 1 } : { one: number; }
>one : number
>1 : number
export var __val__obj4 = obj4;
>__val__obj4 : interfaceWithPublicAndOptional<number, string>
>obj4 : interfaceWithPublicAndOptional<number, string>
}
module __test2__ {
>__test2__ : typeof __test2__
export var aa:{[index:string]:any;};;
>aa : { [index: string]: any; }
>index : string
export var __val__aa = aa;
>__val__aa : { [index: string]: any; }
>aa : { [index: string]: any; }
}
__test2__.__val__aa = __test1__.__val__obj4
>__test2__.__val__aa = __test1__.__val__obj4 : __test1__.interfaceWithPublicAndOptional<number, string>
>__test2__.__val__aa : { [index: string]: any; }
>__test2__ : typeof __test2__
>__val__aa : { [index: string]: any; }
>__test1__.__val__obj4 : __test1__.interfaceWithPublicAndOptional<number, string>
>__test1__ : typeof __test1__
>__val__obj4 : __test1__.interfaceWithPublicAndOptional<number, string>
@@ -0,0 +1,42 @@
//// [assignmentNonObjectTypeConstraints.ts]
const enum E { A, B, C }
function foo<T extends number>(x: T) {
var y: number = x; // Ok
}
foo(5);
foo(E.A);
class A { a }
class B { b }
function bar<T extends A | B>(x: T) {
var y: A | B = x; // Ok
}
bar(new A);
bar(new B);
//// [assignmentNonObjectTypeConstraints.js]
function foo(x) {
var y = x; // Ok
}
foo(5);
foo(0 /* A */);
var A = (function () {
function A() {
}
return A;
})();
var B = (function () {
function B() {
}
return B;
})();
function bar(x) {
var y = x; // Ok
}
bar(new A);
bar(new B);
@@ -0,0 +1,58 @@
=== tests/cases/compiler/assignmentNonObjectTypeConstraints.ts ===
const enum E { A, B, C }
>E : Symbol(E, Decl(assignmentNonObjectTypeConstraints.ts, 0, 0))
>A : Symbol(E.A, Decl(assignmentNonObjectTypeConstraints.ts, 0, 14))
>B : Symbol(E.B, Decl(assignmentNonObjectTypeConstraints.ts, 0, 17))
>C : Symbol(E.C, Decl(assignmentNonObjectTypeConstraints.ts, 0, 20))
function foo<T extends number>(x: T) {
>foo : Symbol(foo, Decl(assignmentNonObjectTypeConstraints.ts, 0, 24))
>T : Symbol(T, Decl(assignmentNonObjectTypeConstraints.ts, 2, 13))
>x : Symbol(x, Decl(assignmentNonObjectTypeConstraints.ts, 2, 31))
>T : Symbol(T, Decl(assignmentNonObjectTypeConstraints.ts, 2, 13))
var y: number = x; // Ok
>y : Symbol(y, Decl(assignmentNonObjectTypeConstraints.ts, 3, 7))
>x : Symbol(x, Decl(assignmentNonObjectTypeConstraints.ts, 2, 31))
}
foo(5);
>foo : Symbol(foo, Decl(assignmentNonObjectTypeConstraints.ts, 0, 24))
foo(E.A);
>foo : Symbol(foo, Decl(assignmentNonObjectTypeConstraints.ts, 0, 24))
>E.A : Symbol(E.A, Decl(assignmentNonObjectTypeConstraints.ts, 0, 14))
>E : Symbol(E, Decl(assignmentNonObjectTypeConstraints.ts, 0, 0))
>A : Symbol(E.A, Decl(assignmentNonObjectTypeConstraints.ts, 0, 14))
class A { a }
>A : Symbol(A, Decl(assignmentNonObjectTypeConstraints.ts, 7, 9))
>a : Symbol(a, Decl(assignmentNonObjectTypeConstraints.ts, 9, 9))
class B { b }
>B : Symbol(B, Decl(assignmentNonObjectTypeConstraints.ts, 9, 13))
>b : Symbol(b, Decl(assignmentNonObjectTypeConstraints.ts, 10, 9))
function bar<T extends A | B>(x: T) {
>bar : Symbol(bar, Decl(assignmentNonObjectTypeConstraints.ts, 10, 13))
>T : Symbol(T, Decl(assignmentNonObjectTypeConstraints.ts, 12, 13))
>A : Symbol(A, Decl(assignmentNonObjectTypeConstraints.ts, 7, 9))
>B : Symbol(B, Decl(assignmentNonObjectTypeConstraints.ts, 9, 13))
>x : Symbol(x, Decl(assignmentNonObjectTypeConstraints.ts, 12, 30))
>T : Symbol(T, Decl(assignmentNonObjectTypeConstraints.ts, 12, 13))
var y: A | B = x; // Ok
>y : Symbol(y, Decl(assignmentNonObjectTypeConstraints.ts, 13, 7))
>A : Symbol(A, Decl(assignmentNonObjectTypeConstraints.ts, 7, 9))
>B : Symbol(B, Decl(assignmentNonObjectTypeConstraints.ts, 9, 13))
>x : Symbol(x, Decl(assignmentNonObjectTypeConstraints.ts, 12, 30))
}
bar(new A);
>bar : Symbol(bar, Decl(assignmentNonObjectTypeConstraints.ts, 10, 13))
>A : Symbol(A, Decl(assignmentNonObjectTypeConstraints.ts, 7, 9))
bar(new B);
>bar : Symbol(bar, Decl(assignmentNonObjectTypeConstraints.ts, 10, 13))
>B : Symbol(B, Decl(assignmentNonObjectTypeConstraints.ts, 9, 13))
@@ -0,0 +1,65 @@
=== tests/cases/compiler/assignmentNonObjectTypeConstraints.ts ===
const enum E { A, B, C }
>E : E
>A : E
>B : E
>C : E
function foo<T extends number>(x: T) {
>foo : <T extends number>(x: T) => void
>T : T
>x : T
>T : T
var y: number = x; // Ok
>y : number
>x : T
}
foo(5);
>foo(5) : void
>foo : <T extends number>(x: T) => void
>5 : number
foo(E.A);
>foo(E.A) : void
>foo : <T extends number>(x: T) => void
>E.A : E
>E : typeof E
>A : E
class A { a }
>A : A
>a : any
class B { b }
>B : B
>b : any
function bar<T extends A | B>(x: T) {
>bar : <T extends A | B>(x: T) => void
>T : T
>A : A
>B : B
>x : T
>T : T
var y: A | B = x; // Ok
>y : A | B
>A : A
>B : B
>x : T
}
bar(new A);
>bar(new A) : void
>bar : <T extends A | B>(x: T) => void
>new A : A
>A : typeof A
bar(new B);
>bar(new B) : void
>bar : <T extends A | B>(x: T) => void
>new B : B
>B : typeof B
@@ -2,6 +2,6 @@
var foo = async (): Promise<void> => {
>foo : Symbol(foo, Decl(asyncArrowFunction1_es6.ts, 1, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
};
@@ -2,16 +2,16 @@
type MyPromise<T> = Promise<T>;
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
>T : Symbol(T, Decl(asyncAwait_es6.ts, 0, 15))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
>T : Symbol(T, Decl(asyncAwait_es6.ts, 0, 15))
declare var MyPromise: typeof Promise;
>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es6.ts, 0, 0), Decl(asyncAwait_es6.ts, 1, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
declare var p: Promise<number>;
>p : Symbol(p, Decl(asyncAwait_es6.ts, 2, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
declare var mp: MyPromise<number>;
>mp : Symbol(mp, Decl(asyncAwait_es6.ts, 3, 11))
@@ -22,7 +22,7 @@ async function f0() { }
async function f1(): Promise<void> { }
>f1 : Symbol(f1, Decl(asyncAwait_es6.ts, 5, 23))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
async function f3(): MyPromise<void> { }
>f3 : Symbol(f3, Decl(asyncAwait_es6.ts, 6, 38))
@@ -33,7 +33,7 @@ let f4 = async function() { }
let f5 = async function(): Promise<void> { }
>f5 : Symbol(f5, Decl(asyncAwait_es6.ts, 10, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
let f6 = async function(): MyPromise<void> { }
>f6 : Symbol(f6, Decl(asyncAwait_es6.ts, 11, 3))
@@ -44,7 +44,7 @@ let f7 = async () => { };
let f8 = async (): Promise<void> => { };
>f8 : Symbol(f8, Decl(asyncAwait_es6.ts, 14, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
let f9 = async (): MyPromise<void> => { };
>f9 : Symbol(f9, Decl(asyncAwait_es6.ts, 15, 3))
@@ -60,7 +60,7 @@ let f11 = async () => mp;
let f12 = async (): Promise<number> => mp;
>f12 : Symbol(f12, Decl(asyncAwait_es6.ts, 18, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
>mp : Symbol(mp, Decl(asyncAwait_es6.ts, 3, 11))
let f13 = async (): MyPromise<number> => p;
@@ -76,7 +76,7 @@ let o = {
async m2(): Promise<void> { },
>m2 : Symbol(m2, Decl(asyncAwait_es6.ts, 22, 16))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
async m3(): MyPromise<void> { }
>m3 : Symbol(m3, Decl(asyncAwait_es6.ts, 23, 31))
@@ -92,7 +92,7 @@ class C {
async m2(): Promise<void> { }
>m2 : Symbol(m2, Decl(asyncAwait_es6.ts, 28, 15))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
async m3(): MyPromise<void> { }
>m3 : Symbol(m3, Decl(asyncAwait_es6.ts, 29, 30))
@@ -103,7 +103,7 @@ class C {
static async m5(): Promise<void> { }
>m5 : Symbol(C.m5, Decl(asyncAwait_es6.ts, 31, 22))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
static async m6(): MyPromise<void> { }
>m6 : Symbol(C.m6, Decl(asyncAwait_es6.ts, 32, 37))
@@ -1,5 +1,5 @@
=== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration11_es6.ts ===
async function await(): Promise<void> {
>await : Symbol(await, Decl(asyncFunctionDeclaration11_es6.ts, 0, 0))
>Promise : Symbol(Promise, Decl(lib.d.ts, 4772, 1), Decl(lib.d.ts, 4858, 11))
>Promise : Symbol(Promise, Decl(lib.d.ts, 5041, 1), Decl(lib.d.ts, 5127, 11))
}

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