Merge branch 'master' into ownJsonParsing

This commit is contained in:
Sheetal Nandi
2017-05-24 12:46:29 -07:00
433 changed files with 42717 additions and 20892 deletions
+9 -2
View File
@@ -131,6 +131,7 @@ const es2017LibrarySource = [
"es2017.object.d.ts",
"es2017.sharedmemory.d.ts",
"es2017.string.d.ts",
"es2017.intl.d.ts",
];
const es2017LibrarySourceMap = es2017LibrarySource.map(function(source) {
@@ -935,7 +936,7 @@ gulp.task(loggedIOJsPath, /*help*/ false, [], (done) => {
const temp = path.join(builtLocalDirectory, "temp");
mkdirP(temp, (err) => {
if (err) { console.error(err); done(err); process.exit(1); }
exec(host, [LKGCompiler, "--types --outdir", temp, loggedIOpath], () => {
exec(host, [LKGCompiler, "--types", "--target es5", "--lib es5", "--outdir", temp, loggedIOpath], () => {
fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath);
del(temp).then(() => done(), done);
}, done);
@@ -946,7 +947,13 @@ const instrumenterPath = path.join(harnessDirectory, "instrumenter.ts");
const instrumenterJsPath = path.join(builtLocalDirectory, "instrumenter.js");
gulp.task(instrumenterJsPath, /*help*/ false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: instrumenterJsPath
outFile: instrumenterJsPath,
target: "es5",
lib: [
"es6",
"dom",
"scripthost"
]
}, /*useBuiltCompiler*/ true);
return gulp.src(instrumenterPath)
.pipe(newer(instrumenterJsPath))
+2 -1
View File
@@ -172,7 +172,8 @@ var es2016LibrarySourceMap = es2016LibrarySource.map(function (source) {
var es2017LibrarySource = [
"es2017.object.d.ts",
"es2017.sharedmemory.d.ts",
"es2017.string.d.ts"
"es2017.string.d.ts",
"es2017.intl.d.ts"
];
var es2017LibrarySourceMap = es2017LibrarySource.map(function (source) {
+2
View File
@@ -69,3 +69,5 @@ function createCancellationToken(args) {
}
}
module.exports = createCancellationToken;
//# sourceMappingURL=cancellationToken.js.map
+28 -20
View File
@@ -1406,6 +1406,14 @@ interface ArrayBuffer {
slice(begin: number, end?: number): ArrayBuffer;
}
/**
* Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.
*/
interface ArrayBufferTypes {
ArrayBuffer: ArrayBuffer;
}
type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];
interface ArrayBufferConstructor {
readonly prototype: ArrayBuffer;
new (byteLength: number): ArrayBuffer;
@@ -1417,7 +1425,7 @@ interface ArrayBufferView {
/**
* The ArrayBuffer instance referenced by the array.
*/
buffer: ArrayBuffer;
buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -1559,7 +1567,7 @@ interface DataView {
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;
}
declare const DataView: DataViewConstructor;
@@ -1576,7 +1584,7 @@ interface Int8Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor {
readonly prototype: Int8Array;
new (length: number): Int8Array;
new (array: ArrayLike<number>): Int8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;
/**
* The size in bytes of each element in the array.
@@ -1860,7 +1868,7 @@ interface Uint8Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor {
readonly prototype: Uint8Array;
new (length: number): Uint8Array;
new (array: ArrayLike<number>): Uint8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;
/**
* The size in bytes of each element in the array.
@@ -2145,7 +2153,7 @@ interface Uint8ClampedArray {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor {
readonly prototype: Uint8ClampedArray;
new (length: number): Uint8ClampedArray;
new (array: ArrayLike<number>): Uint8ClampedArray;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray;
/**
* The size in bytes of each element in the array.
@@ -2429,7 +2437,7 @@ interface Int16Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor {
readonly prototype: Int16Array;
new (length: number): Int16Array;
new (array: ArrayLike<number>): Int16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array;
/**
* The size in bytes of each element in the array.
@@ -2714,7 +2722,7 @@ interface Uint16Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor {
readonly prototype: Uint16Array;
new (length: number): Uint16Array;
new (array: ArrayLike<number>): Uint16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array;
/**
* The size in bytes of each element in the array.
@@ -2998,7 +3006,7 @@ interface Int32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor {
readonly prototype: Int32Array;
new (length: number): Int32Array;
new (array: ArrayLike<number>): Int32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;
/**
* The size in bytes of each element in the array.
@@ -3282,7 +3290,7 @@ interface Uint32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor {
readonly prototype: Uint32Array;
new (length: number): Uint32Array;
new (array: ArrayLike<number>): Uint32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array;
/**
* The size in bytes of each element in the array.
@@ -3566,7 +3574,7 @@ interface Float32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor {
readonly prototype: Float32Array;
new (length: number): Float32Array;
new (array: ArrayLike<number>): Float32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array;
/**
* The size in bytes of each element in the array.
@@ -3851,7 +3859,7 @@ interface Float64Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor {
readonly prototype: Float64Array;
new (length: number): Float64Array;
new (array: ArrayLike<number>): Float64Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array;
/**
* The size in bytes of each element in the array.
+71 -7
View File
@@ -52,17 +52,17 @@ interface Array<T> {
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
* Returns an iterable of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
* Returns an iterable of values in the array
*/
values(): IterableIterator<T>;
}
@@ -86,21 +86,21 @@ interface ArrayConstructor {
}
interface ReadonlyArray<T> {
/** Iterator */
/** Iterator of values in the array. */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
* Returns an iterable of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
* Returns an iterable of values in the array
*/
values(): IterableIterator<T>;
}
@@ -111,9 +111,42 @@ interface IArguments {
}
interface Map<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): IterableIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): IterableIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): IterableIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): IterableIterator<V>;
}
interface ReadonlyMap<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): IterableIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): IterableIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): IterableIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): IterableIterator<V>;
}
@@ -128,9 +161,40 @@ interface WeakMapConstructor {
}
interface Set<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys(): IterableIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
}
interface ReadonlySet<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys(): IterableIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
}
+1 -1
View File
@@ -23,7 +23,7 @@ interface ProxyHandler<T extends object> {
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
+1824
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -21,4 +21,5 @@ and limitations under the License.
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
/// <reference path="lib.es2017.intl.d.ts" />
+1825
View File
File diff suppressed because it is too large Load Diff
+92 -1
View File
@@ -43,5 +43,96 @@ interface SharedArrayBufferConstructor {
readonly prototype: SharedArrayBuffer;
new (byteLength: number): SharedArrayBuffer;
}
declare var SharedArrayBuffer: SharedArrayBufferConstructor;
declare var SharedArrayBuffer: SharedArrayBufferConstructor;
interface ArrayBufferTypes {
SharedArrayBuffer: SharedArrayBuffer;
}
interface Atomics {
/**
* Adds a value to the value at the given position in the array, returning the original value.
* Until this atomic operation completes, any other read or write operation against the array
* will block.
*/
add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
/**
* Stores the bitwise AND of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or
* write operation against the array will block.
*/
and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
/**
* Replaces the value at the given position in the array if the original value equals the given
* expected value, returning the original value. Until this atomic operation completes, any
* other read or write operation against the array will block.
*/
compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number;
/**
* Replaces the value at the given position in the array, returning the original value. Until
* this atomic operation completes, any other read or write operation against the array will
* block.
*/
exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
/**
* Returns a value indicating whether high-performance algorithms can use atomic operations
* (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed
* array.
*/
isLockFree(size: number): boolean;
/**
* Returns the value at the given position in the array. Until this atomic operation completes,
* any other read or write operation against the array will block.
*/
load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number;
/**
* Stores the bitwise OR of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or write
* operation against the array will block.
*/
or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
/**
* Stores a value at the given position in the array, returning the new value. Until this
* atomic operation completes, any other read or write operation against the array will block.
*/
store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
/**
* Subtracts a value from the value at the given position in the array, returning the original
* value. Until this atomic operation completes, any other read or write operation against the
* array will block.
*/
sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
/**
* If the value at the given position in the array is equal to the provided value, the current
* agent is put to sleep causing execution to suspend until the timeout expires (returning
* `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns
* `"not-equal"`.
*/
wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out";
/**
* Wakes up sleeping agents that are waiting on the given index of the array, returning the
* number of agents that were awoken.
*/
wake(typedArray: Int32Array, index: number, count: number): number;
/**
* Stores the bitwise XOR of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or write
* operation against the array will block.
*/
xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;
readonly [Symbol.toStringTag]: "Atomics";
}
declare var Atomics: Atomics;
+28 -20
View File
@@ -1406,6 +1406,14 @@ interface ArrayBuffer {
slice(begin: number, end?: number): ArrayBuffer;
}
/**
* Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.
*/
interface ArrayBufferTypes {
ArrayBuffer: ArrayBuffer;
}
type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];
interface ArrayBufferConstructor {
readonly prototype: ArrayBuffer;
new (byteLength: number): ArrayBuffer;
@@ -1417,7 +1425,7 @@ interface ArrayBufferView {
/**
* The ArrayBuffer instance referenced by the array.
*/
buffer: ArrayBuffer;
buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -1559,7 +1567,7 @@ interface DataView {
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;
}
declare const DataView: DataViewConstructor;
@@ -1576,7 +1584,7 @@ interface Int8Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor {
readonly prototype: Int8Array;
new (length: number): Int8Array;
new (array: ArrayLike<number>): Int8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;
/**
* The size in bytes of each element in the array.
@@ -1860,7 +1868,7 @@ interface Uint8Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor {
readonly prototype: Uint8Array;
new (length: number): Uint8Array;
new (array: ArrayLike<number>): Uint8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;
/**
* The size in bytes of each element in the array.
@@ -2145,7 +2153,7 @@ interface Uint8ClampedArray {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor {
readonly prototype: Uint8ClampedArray;
new (length: number): Uint8ClampedArray;
new (array: ArrayLike<number>): Uint8ClampedArray;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray;
/**
* The size in bytes of each element in the array.
@@ -2429,7 +2437,7 @@ interface Int16Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor {
readonly prototype: Int16Array;
new (length: number): Int16Array;
new (array: ArrayLike<number>): Int16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array;
/**
* The size in bytes of each element in the array.
@@ -2714,7 +2722,7 @@ interface Uint16Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor {
readonly prototype: Uint16Array;
new (length: number): Uint16Array;
new (array: ArrayLike<number>): Uint16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array;
/**
* The size in bytes of each element in the array.
@@ -2998,7 +3006,7 @@ interface Int32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor {
readonly prototype: Int32Array;
new (length: number): Int32Array;
new (array: ArrayLike<number>): Int32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;
/**
* The size in bytes of each element in the array.
@@ -3282,7 +3290,7 @@ interface Uint32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor {
readonly prototype: Uint32Array;
new (length: number): Uint32Array;
new (array: ArrayLike<number>): Uint32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array;
/**
* The size in bytes of each element in the array.
@@ -3566,7 +3574,7 @@ interface Float32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor {
readonly prototype: Float32Array;
new (length: number): Float32Array;
new (array: ArrayLike<number>): Float32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array;
/**
* The size in bytes of each element in the array.
@@ -3851,7 +3859,7 @@ interface Float64Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor {
readonly prototype: Float64Array;
new (length: number): Float64Array;
new (array: ArrayLike<number>): Float64Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array;
/**
* The size in bytes of each element in the array.
+100 -28
View File
@@ -1406,6 +1406,14 @@ interface ArrayBuffer {
slice(begin: number, end?: number): ArrayBuffer;
}
/**
* Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.
*/
interface ArrayBufferTypes {
ArrayBuffer: ArrayBuffer;
}
type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];
interface ArrayBufferConstructor {
readonly prototype: ArrayBuffer;
new (byteLength: number): ArrayBuffer;
@@ -1417,7 +1425,7 @@ interface ArrayBufferView {
/**
* The ArrayBuffer instance referenced by the array.
*/
buffer: ArrayBuffer;
buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -1559,7 +1567,7 @@ interface DataView {
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;
}
declare const DataView: DataViewConstructor;
@@ -1576,7 +1584,7 @@ interface Int8Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -1819,7 +1827,7 @@ interface Int8ArrayConstructor {
readonly prototype: Int8Array;
new (length: number): Int8Array;
new (array: ArrayLike<number>): Int8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;
/**
* The size in bytes of each element in the array.
@@ -1860,7 +1868,7 @@ interface Uint8Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2104,7 +2112,7 @@ interface Uint8ArrayConstructor {
readonly prototype: Uint8Array;
new (length: number): Uint8Array;
new (array: ArrayLike<number>): Uint8Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;
/**
* The size in bytes of each element in the array.
@@ -2145,7 +2153,7 @@ interface Uint8ClampedArray {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2389,7 +2397,7 @@ interface Uint8ClampedArrayConstructor {
readonly prototype: Uint8ClampedArray;
new (length: number): Uint8ClampedArray;
new (array: ArrayLike<number>): Uint8ClampedArray;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray;
/**
* The size in bytes of each element in the array.
@@ -2429,7 +2437,7 @@ interface Int16Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2673,7 +2681,7 @@ interface Int16ArrayConstructor {
readonly prototype: Int16Array;
new (length: number): Int16Array;
new (array: ArrayLike<number>): Int16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array;
/**
* The size in bytes of each element in the array.
@@ -2714,7 +2722,7 @@ interface Uint16Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -2958,7 +2966,7 @@ interface Uint16ArrayConstructor {
readonly prototype: Uint16Array;
new (length: number): Uint16Array;
new (array: ArrayLike<number>): Uint16Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array;
/**
* The size in bytes of each element in the array.
@@ -2998,7 +3006,7 @@ interface Int32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3242,7 +3250,7 @@ interface Int32ArrayConstructor {
readonly prototype: Int32Array;
new (length: number): Int32Array;
new (array: ArrayLike<number>): Int32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;
/**
* The size in bytes of each element in the array.
@@ -3282,7 +3290,7 @@ interface Uint32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3526,7 +3534,7 @@ interface Uint32ArrayConstructor {
readonly prototype: Uint32Array;
new (length: number): Uint32Array;
new (array: ArrayLike<number>): Uint32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array;
/**
* The size in bytes of each element in the array.
@@ -3566,7 +3574,7 @@ interface Float32Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -3810,7 +3818,7 @@ interface Float32ArrayConstructor {
readonly prototype: Float32Array;
new (length: number): Float32Array;
new (array: ArrayLike<number>): Float32Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array;
/**
* The size in bytes of each element in the array.
@@ -3851,7 +3859,7 @@ interface Float64Array {
/**
* The ArrayBuffer instance referenced by the array.
*/
readonly buffer: ArrayBuffer;
readonly buffer: ArrayBufferLike;
/**
* The length in bytes of the array.
@@ -4095,7 +4103,7 @@ interface Float64ArrayConstructor {
readonly prototype: Float64Array;
new (length: number): Float64Array;
new (array: ArrayLike<number>): Float64Array;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array;
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array;
/**
* The size in bytes of each element in the array.
@@ -4977,17 +4985,17 @@ interface Array<T> {
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
* Returns an iterable of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
* Returns an iterable of values in the array
*/
values(): IterableIterator<T>;
}
@@ -5011,21 +5019,21 @@ interface ArrayConstructor {
}
interface ReadonlyArray<T> {
/** Iterator */
/** Iterator of values in the array. */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
* Returns an iterable of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
* Returns an iterable of values in the array
*/
values(): IterableIterator<T>;
}
@@ -5036,9 +5044,42 @@ interface IArguments {
}
interface Map<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): IterableIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): IterableIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): IterableIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): IterableIterator<V>;
}
interface ReadonlyMap<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): IterableIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): IterableIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): IterableIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): IterableIterator<V>;
}
@@ -5053,9 +5094,40 @@ interface WeakMapConstructor {
}
interface Set<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys(): IterableIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
}
interface ReadonlySet<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys(): IterableIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
}
@@ -5637,7 +5709,7 @@ interface ProxyHandler<T extends object> {
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
+1824
View File
File diff suppressed because it is too large Load Diff
+3816 -1680
View File
File diff suppressed because it is too large Load Diff
+3929 -2602
View File
File diff suppressed because it is too large Load Diff
+201 -119
View File
@@ -352,9 +352,10 @@ declare namespace ts {
SyntaxList = 294,
NotEmittedStatement = 295,
PartiallyEmittedExpression = 296,
MergeDeclarationMarker = 297,
EndOfDeclarationMarker = 298,
Count = 299,
CommaListExpression = 297,
MergeDeclarationMarker = 298,
EndOfDeclarationMarker = 299,
Count = 300,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -482,9 +483,11 @@ declare namespace ts {
type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
}
interface NamedDeclaration extends Declaration {
name?: DeclarationName;
}
interface DeclarationStatement extends Declaration, Statement {
interface DeclarationStatement extends NamedDeclaration, Statement {
name?: Identifier | StringLiteral | NumericLiteral;
}
interface ComputedPropertyName extends Node {
@@ -495,7 +498,7 @@ declare namespace ts {
kind: SyntaxKind.Decorator;
expression: LeftHandSideExpression;
}
interface TypeParameterDeclaration extends Declaration {
interface TypeParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.TypeParameter;
parent?: DeclarationWithTypeParameters;
name: Identifier;
@@ -503,7 +506,7 @@ declare namespace ts {
default?: TypeNode;
expression?: Expression;
}
interface SignatureDeclaration extends Declaration {
interface SignatureDeclaration extends NamedDeclaration {
name?: PropertyName;
typeParameters?: NodeArray<TypeParameterDeclaration>;
parameters: NodeArray<ParameterDeclaration>;
@@ -516,7 +519,7 @@ declare namespace ts {
kind: SyntaxKind.ConstructSignature;
}
type BindingName = Identifier | BindingPattern;
interface VariableDeclaration extends Declaration {
interface VariableDeclaration extends NamedDeclaration {
kind: SyntaxKind.VariableDeclaration;
parent?: VariableDeclarationList | CatchClause;
name: BindingName;
@@ -528,7 +531,7 @@ declare namespace ts {
parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement;
declarations: NodeArray<VariableDeclaration>;
}
interface ParameterDeclaration extends Declaration {
interface ParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.Parameter;
parent?: SignatureDeclaration;
dotDotDotToken?: DotDotDotToken;
@@ -537,7 +540,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface BindingElement extends Declaration {
interface BindingElement extends NamedDeclaration {
kind: SyntaxKind.BindingElement;
parent?: BindingPattern;
propertyName?: PropertyName;
@@ -559,7 +562,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface ObjectLiteralElement extends Declaration {
interface ObjectLiteralElement extends NamedDeclaration {
_objectLiteralBrandBrand: any;
name?: PropertyName;
}
@@ -581,7 +584,7 @@ declare namespace ts {
kind: SyntaxKind.SpreadAssignment;
expression: Expression;
}
interface VariableLikeDeclaration extends Declaration {
interface VariableLikeDeclaration extends NamedDeclaration {
propertyName?: PropertyName;
dotDotDotToken?: DotDotDotToken;
name: DeclarationName;
@@ -589,7 +592,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface PropertyLikeDeclaration extends Declaration {
interface PropertyLikeDeclaration extends NamedDeclaration {
name: PropertyName;
}
interface ObjectBindingPattern extends Node {
@@ -926,7 +929,7 @@ declare namespace ts {
}
type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression;
type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
interface PropertyAccessExpression extends MemberExpression, Declaration {
interface PropertyAccessExpression extends MemberExpression, NamedDeclaration {
kind: SyntaxKind.PropertyAccessExpression;
expression: LeftHandSideExpression;
name: Identifier;
@@ -991,7 +994,7 @@ declare namespace ts {
}
interface MetaProperty extends PrimaryExpression {
kind: SyntaxKind.MetaProperty;
keywordToken: SyntaxKind;
keywordToken: SyntaxKind.NewKeyword;
name: Identifier;
}
interface JsxElement extends PrimaryExpression {
@@ -1051,6 +1054,10 @@ declare namespace ts {
interface NotEmittedStatement extends Statement {
kind: SyntaxKind.NotEmittedStatement;
}
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
elements: NodeArray<Expression>;
}
interface EmptyStatement extends Statement {
kind: SyntaxKind.EmptyStatement;
}
@@ -1172,7 +1179,7 @@ declare namespace ts {
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
interface ClassLikeDeclaration extends NamedDeclaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
@@ -1185,11 +1192,11 @@ declare namespace ts {
interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
kind: SyntaxKind.ClassExpression;
}
interface ClassElement extends Declaration {
interface ClassElement extends NamedDeclaration {
_classElementBrand: any;
name?: PropertyName;
}
interface TypeElement extends Declaration {
interface TypeElement extends NamedDeclaration {
_typeElementBrand: any;
name?: PropertyName;
questionToken?: QuestionToken;
@@ -1213,7 +1220,7 @@ declare namespace ts {
typeParameters?: NodeArray<TypeParameterDeclaration>;
type: TypeNode;
}
interface EnumMember extends Declaration {
interface EnumMember extends NamedDeclaration {
kind: SyntaxKind.EnumMember;
parent?: EnumDeclaration;
name: PropertyName;
@@ -1266,13 +1273,13 @@ declare namespace ts {
moduleSpecifier: Expression;
}
type NamedImportBindings = NamespaceImport | NamedImports;
interface ImportClause extends Declaration {
interface ImportClause extends NamedDeclaration {
kind: SyntaxKind.ImportClause;
parent?: ImportDeclaration;
name?: Identifier;
namedBindings?: NamedImportBindings;
}
interface NamespaceImport extends Declaration {
interface NamespaceImport extends NamedDeclaration {
kind: SyntaxKind.NamespaceImport;
parent?: ImportClause;
name: Identifier;
@@ -1298,13 +1305,13 @@ declare namespace ts {
elements: NodeArray<ExportSpecifier>;
}
type NamedImportsOrExports = NamedImports | NamedExports;
interface ImportSpecifier extends Declaration {
interface ImportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ImportSpecifier;
parent?: NamedImports;
propertyName?: Identifier;
name: Identifier;
}
interface ExportSpecifier extends Declaration {
interface ExportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ExportSpecifier;
parent?: NamedExports;
propertyName?: Identifier;
@@ -1435,7 +1442,7 @@ declare namespace ts {
kind: SyntaxKind.JSDocTypeTag;
typeExpression: JSDocTypeExpression;
}
interface JSDocTypedefTag extends JSDocTag, Declaration {
interface JSDocTypedefTag extends JSDocTag, NamedDeclaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
@@ -1626,11 +1633,11 @@ declare namespace ts {
signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration;
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolAtLocation(node: Node): Symbol | undefined;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;
@@ -1640,37 +1647,47 @@ declare namespace ts {
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
getContextualType(node: Expression): Type;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
getContextualType(node: Expression): Type | undefined;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isUnknownSymbol(symbol: Symbol): boolean;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type;
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
}
enum NodeBuilderFlags {
None = 0,
allowThisInObjectLiteral = 1,
allowQualifedNameInPlaceOfIdentifier = 2,
allowTypeParameterInQualifiedName = 4,
allowAnonymousIdentifier = 8,
allowEmptyUnionOrIntersection = 16,
allowEmptyTuple = 32,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
SuppressAnyReturnType = 256,
WriteTypeParametersInQualifiedName = 512,
AllowThisInObjectLiteral = 1024,
AllowQualifedNameInPlaceOfIdentifier = 2048,
AllowAnonymousIdentifier = 8192,
AllowEmptyUnionOrIntersection = 16384,
AllowEmptyTuple = 32768,
IgnoreErrors = 60416,
InObjectTypeLiteral = 1048576,
InTypeAlias = 8388608,
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -1831,18 +1848,18 @@ declare namespace ts {
Index = 262144,
IndexedAccess = 524288,
NonPrimitive = 16777216,
Literal = 480,
Literal = 224,
StringOrNumberLiteral = 96,
PossiblyFalsy = 7406,
StringLike = 262178,
NumberLike = 340,
NumberLike = 84,
BooleanLike = 136,
EnumLike = 272,
UnionOrIntersection = 196608,
StructuredType = 229376,
StructuredOrTypeVariable = 1032192,
TypeVariable = 540672,
Narrowable = 17810431,
Narrowable = 17810175,
NotUnionOrUnit = 16810497,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
@@ -1854,15 +1871,17 @@ declare namespace ts {
aliasTypeArguments?: Type[];
}
interface LiteralType extends Type {
text: string;
value: string | number;
freshType?: LiteralType;
regularType?: LiteralType;
}
interface EnumType extends Type {
memberTypes: EnumLiteralType[];
interface StringLiteralType extends LiteralType {
value: string;
}
interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType;
interface NumberLiteralType extends LiteralType {
value: number;
}
interface EnumType extends Type {
}
const enum ObjectFlags {
Class = 1,
@@ -1896,7 +1915,7 @@ declare namespace ts {
}
interface TypeReference extends ObjectType {
target: GenericType;
typeArguments: Type[];
typeArguments?: Type[];
}
interface GenericType extends InterfaceType, TypeReference {
}
@@ -1932,7 +1951,7 @@ declare namespace ts {
}
interface Signature {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
const enum IndexKind {
@@ -1961,9 +1980,9 @@ declare namespace ts {
next?: DiagnosticMessageChain;
}
interface Diagnostic {
file: SourceFile;
start: number;
length: number;
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
messageText: string | DiagnosticMessageChain;
category: DiagnosticCategory;
code: number;
@@ -2204,6 +2223,7 @@ declare namespace ts {
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2362,13 +2382,13 @@ declare namespace ts {
function isWhiteSpaceSingleLine(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function couldStartTrivia(text: string, pos: number): boolean;
function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U;
function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U;
function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined;
function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined;
function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U;
function reduceEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
function getShebang(text: string): string;
function getShebang(text: string): string | undefined;
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;
@@ -2384,7 +2404,7 @@ declare namespace ts {
error?: Diagnostic;
};
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine;
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined;
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -2395,9 +2415,6 @@ declare namespace ts {
};
}
declare namespace ts {
interface Push<T> {
push(value: T): void;
}
function moduleHasNonRelativeName(moduleName: string): boolean;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
@@ -2466,6 +2483,7 @@ declare namespace ts {
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier, typeArguments: NodeArray<TypeNode> | undefined): Identifier;
function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier;
function createLoopVariable(): Identifier;
function createUniqueName(text: string): Identifier;
@@ -2480,58 +2498,19 @@ declare namespace ts {
function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName;
function createComputedPropertyName(expression: Expression): ComputedPropertyName;
function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName;
function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration;
function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode;
function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): FunctionTypeNode;
function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode;
function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructorTypeNode;
function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createLiteralTypeNode(literal: Expression): LiteralTypeNode;
function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode;
function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode;
function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode;
function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode;
function createTypeQueryNode(exprName: EntityName): TypeQueryNode;
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode;
function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray<TypeNode>): UnionOrIntersectionTypeNode;
function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode;
function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode;
function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode;
function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration;
function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration;
function createDecorator(expression: Expression): Decorator;
function updateDecorator(node: Decorator, expression: Expression): Decorator;
function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration;
function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration;
function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
@@ -2539,6 +2518,45 @@ declare namespace ts {
function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration;
function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode;
function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode;
function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode;
function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode;
function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode;
function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): FunctionTypeNode;
function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode;
function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructorTypeNode;
function createTypeQueryNode(exprName: EntityName): TypeQueryNode;
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode;
function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode;
function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode;
function createUnionTypeNode(types: TypeNode[]): UnionTypeNode;
function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray<TypeNode>): UnionTypeNode;
function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode;
function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray<TypeNode>): IntersectionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode;
function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function createLiteralTypeNode(literal: Expression): LiteralTypeNode;
function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode;
function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern;
function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern;
function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern;
@@ -2580,7 +2598,7 @@ declare namespace ts {
function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression;
function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression;
function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression;
function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression;
function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression;
function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression;
function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
@@ -2600,16 +2618,15 @@ declare namespace ts {
function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression;
function createNonNullExpression(expression: Expression): NonNullExpression;
function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression;
function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty;
function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty;
function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function createSemicolonClassElement(): SemicolonClassElement;
function createBlock(statements: Statement[], multiLine?: boolean): Block;
function updateBlock(node: Block, statements: Statement[]): Block;
function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement;
function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement;
function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList;
function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration;
function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
function createEmptyStatement(): EmptyStatement;
function createStatement(expression: Expression): ExpressionStatement;
function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement;
@@ -2641,10 +2658,19 @@ declare namespace ts {
function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement;
function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
function createDebuggerStatement(): DebuggerStatement;
function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration;
function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList;
function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration;
function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration;
function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration;
function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration;
function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration;
function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration;
function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration;
@@ -2653,6 +2679,8 @@ declare namespace ts {
function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock;
function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock;
function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock;
function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration;
function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration;
function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration;
@@ -2683,20 +2711,20 @@ declare namespace ts {
function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement;
function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes;
function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes;
function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes;
function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes;
function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute;
function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute;
function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression;
function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression;
function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause;
function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause;
function createCaseClause(expression: Expression, statements: Statement[]): CaseClause;
function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause;
function createDefaultClause(statements: Statement[]): DefaultClause;
function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause;
function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause;
function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause;
function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause;
function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause;
function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment;
@@ -2712,6 +2740,8 @@ declare namespace ts {
function createNotEmittedStatement(original: Node): NotEmittedStatement;
function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression;
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: Expression[]): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression;
function createBundle(sourceFiles: SourceFile[]): Bundle;
function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle;
function createComma(left: Expression, right: Expression): Expression;
@@ -2745,8 +2775,8 @@ declare namespace ts {
function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined;
function setSyntheticTrailingComments<T extends Node>(node: T, comments: SynthesizedComment[]): T;
function addSyntheticTrailingComment<T extends Node>(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T;
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number;
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression;
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number;
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression;
function addEmitHelper<T extends Node>(node: T, helper: EmitHelper): T;
function addEmitHelpers<T extends Node>(node: T, helpers: EmitHelper[] | undefined): T;
function removeEmitHelper(node: Node, helper: EmitHelper): boolean;
@@ -2756,7 +2786,7 @@ declare namespace ts {
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName;
function isExternalModule(file: SourceFile): boolean;
@@ -2789,6 +2819,7 @@ declare namespace ts {
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
@@ -2931,6 +2962,8 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[];
getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[];
getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -2981,6 +3014,10 @@ declare namespace ts {
description: string;
changes: FileTextChanges[];
}
interface ApplicableRefactorInfo {
name: string;
description: string;
}
interface TextInsertion {
newText: string;
caretOffset: number;
@@ -3367,6 +3404,7 @@ declare namespace ts {
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: MapLike<string>;
transformers?: CustomTransformers;
}
interface TranspileOutput {
outputText: string;
@@ -3610,6 +3648,9 @@ declare namespace ts.server.protocol {
type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
type GetCodeFixes = "getCodeFixes";
type GetSupportedCodeFixes = "getSupportedCodeFixes";
type GetApplicableRefactors = "getApplicableRefactors";
type GetRefactorCodeActions = "getRefactorCodeActions";
type GetRefactorCodeActionsFull = "getRefactorCodeActions-full";
}
interface Message {
seq: number;
@@ -3704,15 +3745,44 @@ declare namespace ts.server.protocol {
line: number;
offset: number;
}
type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs;
interface GetApplicableRefactorsRequest extends Request {
command: CommandTypes.GetApplicableRefactors;
arguments: GetApplicableRefactorsRequestArgs;
}
type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs;
interface ApplicableRefactorInfo {
name: string;
description: string;
}
interface GetApplicableRefactorsResponse extends Response {
body?: ApplicableRefactorInfo[];
}
interface GetRefactorCodeActionsRequest extends Request {
command: CommandTypes.GetRefactorCodeActions;
arguments: GetRefactorCodeActionsRequestArgs;
}
type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & {
refactorName: string;
};
type RefactorCodeActions = {
actions: protocol.CodeAction[];
renameLocation?: number;
};
interface GetRefactorCodeActionsResponse extends Response {
body: RefactorCodeActions;
}
interface CodeFixRequest extends Request {
command: CommandTypes.GetCodeFixes;
arguments: CodeFixRequestArgs;
}
interface CodeFixRequestArgs extends FileRequestArgs {
interface FileRangeRequestArgs extends FileRequestArgs {
startLine: number;
startOffset: number;
endLine: number;
endOffset: number;
}
interface CodeFixRequestArgs extends FileRangeRequestArgs {
errorCodes?: number[];
}
interface GetCodeFixesResponse extends Response {
@@ -4291,6 +4361,7 @@ declare namespace ts.server.protocol {
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean;
insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean;
insertSpaceAfterTypeAssertion?: boolean;
insertSpaceBeforeFunctionParenthesis?: boolean;
placeOpenBraceOnNewLineForFunctions?: boolean;
placeOpenBraceOnNewLineForControlBlocks?: boolean;
@@ -4408,7 +4479,7 @@ declare namespace ts.server {
project: Project;
}
interface EventSender {
event(payload: any, eventName: string): void;
event<T>(payload: T, eventName: string): void;
}
namespace CommandNames {
const Brace: protocol.CommandTypes.Brace;
@@ -4455,6 +4526,9 @@ declare namespace ts.server {
const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects;
const GetCodeFixes: protocol.CommandTypes.GetCodeFixes;
const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes;
const GetApplicableRefactors: protocol.CommandTypes.GetApplicableRefactors;
const GetRefactorCodeActions: protocol.CommandTypes.GetRefactorCodeActions;
const GetRefactorCodeActionsFull: protocol.CommandTypes.GetRefactorCodeActionsFull;
}
function formatMessage<T extends protocol.Message>(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string;
interface SessionOptions {
@@ -4470,6 +4544,7 @@ declare namespace ts.server {
throttleWaitMilliseconds?: number;
globalPlugins?: string[];
pluginProbeLocations?: string[];
allowLocalPluginLoads?: boolean;
}
class Session implements EventSender {
private readonly gcTimer;
@@ -4491,7 +4566,7 @@ declare namespace ts.server {
logError(err: Error, cmd: string): void;
send(msg: protocol.Message): void;
configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void;
event(info: any, eventName: string): void;
event<T>(info: T, eventName: string): void;
output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void;
private semanticCheck(file, project);
private syntacticCheck(file, project);
@@ -4554,7 +4629,12 @@ declare namespace ts.server {
private getNavigationTree(args, simplifiedResult);
private getNavigateToItems(args, simplifiedResult);
private getSupportedCodeFixes();
private isLocation(locationOrSpan);
private extractPositionAndRange(args, scriptInfo);
private getApplicableRefactors(args);
private getRefactorCodeActions(args, simplifiedResult);
private getCodeFixes(args, simplifiedResult);
private getStartAndEndPosition(args, scriptInfo);
private mapCodeAction(codeAction, scriptInfo);
private convertTextChangeToCodeEdit(change, scriptInfo);
private getBraceMatching(args, simplifiedResult);
@@ -5047,6 +5127,7 @@ declare namespace ts.server {
throttleWaitMilliseconds?: number;
globalPlugins?: string[];
pluginProbeLocations?: string[];
allowLocalPluginLoads?: boolean;
}
class ProjectService {
readonly typingsCache: TypingsCache;
@@ -5076,6 +5157,7 @@ declare namespace ts.server {
private readonly eventHandler?;
readonly globalPlugins: ReadonlyArray<string>;
readonly pluginProbeLocations: ReadonlyArray<string>;
readonly allowLocalPluginLoads: boolean;
constructor(opts: ProjectServiceOptions);
ensureInferredProjectsUpToDate_TestOnly(): void;
getCompilerOptionsForInferredProjects(): CompilerOptions;
+3921 -2596
View File
File diff suppressed because it is too large Load Diff
+162 -117
View File
@@ -359,9 +359,10 @@ declare namespace ts {
SyntaxList = 294,
NotEmittedStatement = 295,
PartiallyEmittedExpression = 296,
MergeDeclarationMarker = 297,
EndOfDeclarationMarker = 298,
Count = 299,
CommaListExpression = 297,
MergeDeclarationMarker = 298,
EndOfDeclarationMarker = 299,
Count = 300,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -474,6 +475,10 @@ declare namespace ts {
type ModifiersArray = NodeArray<Modifier>;
interface Identifier extends PrimaryExpression {
kind: SyntaxKind.Identifier;
/**
* Text of identifier (with escapes converted to characters).
* If the identifier begins with two underscores, this will begin with three.
*/
text: string;
originalKeywordKind?: SyntaxKind;
isInJSDocNamespace?: boolean;
@@ -491,9 +496,11 @@ declare namespace ts {
type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
}
interface NamedDeclaration extends Declaration {
name?: DeclarationName;
}
interface DeclarationStatement extends Declaration, Statement {
interface DeclarationStatement extends NamedDeclaration, Statement {
name?: Identifier | StringLiteral | NumericLiteral;
}
interface ComputedPropertyName extends Node {
@@ -504,7 +511,7 @@ declare namespace ts {
kind: SyntaxKind.Decorator;
expression: LeftHandSideExpression;
}
interface TypeParameterDeclaration extends Declaration {
interface TypeParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.TypeParameter;
parent?: DeclarationWithTypeParameters;
name: Identifier;
@@ -512,7 +519,7 @@ declare namespace ts {
default?: TypeNode;
expression?: Expression;
}
interface SignatureDeclaration extends Declaration {
interface SignatureDeclaration extends NamedDeclaration {
name?: PropertyName;
typeParameters?: NodeArray<TypeParameterDeclaration>;
parameters: NodeArray<ParameterDeclaration>;
@@ -525,7 +532,7 @@ declare namespace ts {
kind: SyntaxKind.ConstructSignature;
}
type BindingName = Identifier | BindingPattern;
interface VariableDeclaration extends Declaration {
interface VariableDeclaration extends NamedDeclaration {
kind: SyntaxKind.VariableDeclaration;
parent?: VariableDeclarationList | CatchClause;
name: BindingName;
@@ -537,7 +544,7 @@ declare namespace ts {
parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement;
declarations: NodeArray<VariableDeclaration>;
}
interface ParameterDeclaration extends Declaration {
interface ParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.Parameter;
parent?: SignatureDeclaration;
dotDotDotToken?: DotDotDotToken;
@@ -546,7 +553,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface BindingElement extends Declaration {
interface BindingElement extends NamedDeclaration {
kind: SyntaxKind.BindingElement;
parent?: BindingPattern;
propertyName?: PropertyName;
@@ -568,7 +575,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface ObjectLiteralElement extends Declaration {
interface ObjectLiteralElement extends NamedDeclaration {
_objectLiteralBrandBrand: any;
name?: PropertyName;
}
@@ -590,7 +597,7 @@ declare namespace ts {
kind: SyntaxKind.SpreadAssignment;
expression: Expression;
}
interface VariableLikeDeclaration extends Declaration {
interface VariableLikeDeclaration extends NamedDeclaration {
propertyName?: PropertyName;
dotDotDotToken?: DotDotDotToken;
name: DeclarationName;
@@ -598,7 +605,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface PropertyLikeDeclaration extends Declaration {
interface PropertyLikeDeclaration extends NamedDeclaration {
name: PropertyName;
}
interface ObjectBindingPattern extends Node {
@@ -950,7 +957,7 @@ declare namespace ts {
}
type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression;
type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
interface PropertyAccessExpression extends MemberExpression, Declaration {
interface PropertyAccessExpression extends MemberExpression, NamedDeclaration {
kind: SyntaxKind.PropertyAccessExpression;
expression: LeftHandSideExpression;
name: Identifier;
@@ -1016,7 +1023,7 @@ declare namespace ts {
}
interface MetaProperty extends PrimaryExpression {
kind: SyntaxKind.MetaProperty;
keywordToken: SyntaxKind;
keywordToken: SyntaxKind.NewKeyword;
name: Identifier;
}
interface JsxElement extends PrimaryExpression {
@@ -1076,6 +1083,13 @@ declare namespace ts {
interface NotEmittedStatement extends Statement {
kind: SyntaxKind.NotEmittedStatement;
}
/**
* A list of comma-seperated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
elements: NodeArray<Expression>;
}
interface EmptyStatement extends Statement {
kind: SyntaxKind.EmptyStatement;
}
@@ -1197,7 +1211,7 @@ declare namespace ts {
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
interface ClassLikeDeclaration extends NamedDeclaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
@@ -1210,11 +1224,11 @@ declare namespace ts {
interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
kind: SyntaxKind.ClassExpression;
}
interface ClassElement extends Declaration {
interface ClassElement extends NamedDeclaration {
_classElementBrand: any;
name?: PropertyName;
}
interface TypeElement extends Declaration {
interface TypeElement extends NamedDeclaration {
_typeElementBrand: any;
name?: PropertyName;
questionToken?: QuestionToken;
@@ -1238,7 +1252,7 @@ declare namespace ts {
typeParameters?: NodeArray<TypeParameterDeclaration>;
type: TypeNode;
}
interface EnumMember extends Declaration {
interface EnumMember extends NamedDeclaration {
kind: SyntaxKind.EnumMember;
parent?: EnumDeclaration;
name: PropertyName;
@@ -1297,13 +1311,13 @@ declare namespace ts {
moduleSpecifier: Expression;
}
type NamedImportBindings = NamespaceImport | NamedImports;
interface ImportClause extends Declaration {
interface ImportClause extends NamedDeclaration {
kind: SyntaxKind.ImportClause;
parent?: ImportDeclaration;
name?: Identifier;
namedBindings?: NamedImportBindings;
}
interface NamespaceImport extends Declaration {
interface NamespaceImport extends NamedDeclaration {
kind: SyntaxKind.NamespaceImport;
parent?: ImportClause;
name: Identifier;
@@ -1330,13 +1344,13 @@ declare namespace ts {
elements: NodeArray<ExportSpecifier>;
}
type NamedImportsOrExports = NamedImports | NamedExports;
interface ImportSpecifier extends Declaration {
interface ImportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ImportSpecifier;
parent?: NamedImports;
propertyName?: Identifier;
name: Identifier;
}
interface ExportSpecifier extends Declaration {
interface ExportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ExportSpecifier;
parent?: NamedExports;
propertyName?: Identifier;
@@ -1467,7 +1481,7 @@ declare namespace ts {
kind: SyntaxKind.JSDocTypeTag;
typeExpression: JSDocTypeExpression;
}
interface JSDocTypedefTag extends JSDocTag, Declaration {
interface JSDocTypedefTag extends JSDocTag, NamedDeclaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
@@ -1706,11 +1720,11 @@ declare namespace ts {
/** Note that the resulting nodes cannot be checked. */
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolAtLocation(node: Node): Symbol | undefined;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;
@@ -1720,38 +1734,48 @@ declare namespace ts {
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
getContextualType(node: Expression): Type;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
getContextualType(node: Expression): Type | undefined;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isUnknownSymbol(symbol: Symbol): boolean;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
/** Follow all aliases to get the original symbol. */
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type;
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
}
enum NodeBuilderFlags {
None = 0,
allowThisInObjectLiteral = 1,
allowQualifedNameInPlaceOfIdentifier = 2,
allowTypeParameterInQualifiedName = 4,
allowAnonymousIdentifier = 8,
allowEmptyUnionOrIntersection = 16,
allowEmptyTuple = 32,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
SuppressAnyReturnType = 256,
WriteTypeParametersInQualifiedName = 512,
AllowThisInObjectLiteral = 1024,
AllowQualifedNameInPlaceOfIdentifier = 2048,
AllowAnonymousIdentifier = 8192,
AllowEmptyUnionOrIntersection = 16384,
AllowEmptyTuple = 32768,
IgnoreErrors = 60416,
InObjectTypeLiteral = 1048576,
InTypeAlias = 8388608,
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -1912,18 +1936,18 @@ declare namespace ts {
Index = 262144,
IndexedAccess = 524288,
NonPrimitive = 16777216,
Literal = 480,
Literal = 224,
StringOrNumberLiteral = 96,
PossiblyFalsy = 7406,
StringLike = 262178,
NumberLike = 340,
NumberLike = 84,
BooleanLike = 136,
EnumLike = 272,
UnionOrIntersection = 196608,
StructuredType = 229376,
StructuredOrTypeVariable = 1032192,
TypeVariable = 540672,
Narrowable = 17810431,
Narrowable = 17810175,
NotUnionOrUnit = 16810497,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
@@ -1935,15 +1959,17 @@ declare namespace ts {
aliasTypeArguments?: Type[];
}
interface LiteralType extends Type {
text: string;
value: string | number;
freshType?: LiteralType;
regularType?: LiteralType;
}
interface EnumType extends Type {
memberTypes: EnumLiteralType[];
interface StringLiteralType extends LiteralType {
value: string;
}
interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType;
interface NumberLiteralType extends LiteralType {
value: number;
}
interface EnumType extends Type {
}
enum ObjectFlags {
Class = 1,
@@ -1988,7 +2014,7 @@ declare namespace ts {
*/
interface TypeReference extends ObjectType {
target: GenericType;
typeArguments: Type[];
typeArguments?: Type[];
}
interface GenericType extends InterfaceType, TypeReference {
}
@@ -2024,7 +2050,7 @@ declare namespace ts {
}
interface Signature {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
enum IndexKind {
@@ -2059,9 +2085,9 @@ declare namespace ts {
next?: DiagnosticMessageChain;
}
interface Diagnostic {
file: SourceFile;
start: number;
length: number;
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
messageText: string | DiagnosticMessageChain;
category: DiagnosticCategory;
code: number;
@@ -2329,6 +2355,7 @@ declare namespace ts {
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2611,14 +2638,14 @@ declare namespace ts {
function isWhiteSpaceSingleLine(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function couldStartTrivia(text: string, pos: number): boolean;
function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U;
function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U;
function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined;
function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined;
function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U;
function reduceEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
/** Optionally, get the shebang */
function getShebang(text: string): string;
function getShebang(text: string): string | undefined;
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;
@@ -2709,6 +2736,7 @@ declare namespace ts {
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier, typeArguments: NodeArray<TypeNode> | undefined): Identifier;
/** Create a unique temporary variable. */
function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier;
/** Create a unique temporary variable for use in a loop. */
@@ -2727,58 +2755,19 @@ declare namespace ts {
function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName;
function createComputedPropertyName(expression: Expression): ComputedPropertyName;
function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName;
function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration;
function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode;
function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): FunctionTypeNode;
function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode;
function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructorTypeNode;
function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createLiteralTypeNode(literal: Expression): LiteralTypeNode;
function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode;
function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode;
function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode;
function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode;
function createTypeQueryNode(exprName: EntityName): TypeQueryNode;
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode;
function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray<TypeNode>): UnionOrIntersectionTypeNode;
function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode;
function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode;
function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode;
function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration;
function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration;
function createDecorator(expression: Expression): Decorator;
function updateDecorator(node: Decorator, expression: Expression): Decorator;
function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration;
function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration;
function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
@@ -2786,6 +2775,45 @@ declare namespace ts {
function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration;
function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode;
function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode;
function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode;
function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode;
function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode;
function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): FunctionTypeNode;
function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode;
function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructorTypeNode;
function createTypeQueryNode(exprName: EntityName): TypeQueryNode;
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode;
function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode;
function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode;
function createUnionTypeNode(types: TypeNode[]): UnionTypeNode;
function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray<TypeNode>): UnionTypeNode;
function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode;
function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray<TypeNode>): IntersectionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode;
function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function createLiteralTypeNode(literal: Expression): LiteralTypeNode;
function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode;
function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern;
function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern;
function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern;
@@ -2827,7 +2855,7 @@ declare namespace ts {
function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression;
function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression;
function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression;
function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression;
function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression;
function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression;
function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
@@ -2847,16 +2875,15 @@ declare namespace ts {
function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression;
function createNonNullExpression(expression: Expression): NonNullExpression;
function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression;
function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty;
function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty;
function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function createSemicolonClassElement(): SemicolonClassElement;
function createBlock(statements: Statement[], multiLine?: boolean): Block;
function updateBlock(node: Block, statements: Statement[]): Block;
function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement;
function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement;
function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList;
function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration;
function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
function createEmptyStatement(): EmptyStatement;
function createStatement(expression: Expression): ExpressionStatement;
function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement;
@@ -2888,10 +2915,19 @@ declare namespace ts {
function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement;
function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
function createDebuggerStatement(): DebuggerStatement;
function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration;
function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList;
function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration;
function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration;
function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration;
function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration;
function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration;
function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration;
function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration;
@@ -2900,6 +2936,8 @@ declare namespace ts {
function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock;
function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock;
function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock;
function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration;
function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration;
function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration;
@@ -2930,20 +2968,20 @@ declare namespace ts {
function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement;
function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes;
function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes;
function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes;
function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes;
function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute;
function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute;
function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression;
function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression;
function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause;
function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause;
function createCaseClause(expression: Expression, statements: Statement[]): CaseClause;
function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause;
function createDefaultClause(statements: Statement[]): DefaultClause;
function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause;
function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause;
function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause;
function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause;
function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause;
function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment;
@@ -2976,6 +3014,8 @@ declare namespace ts {
*/
function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression;
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: Expression[]): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression;
function createBundle(sourceFiles: SourceFile[]): Bundle;
function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle;
function createComma(left: Expression, right: Expression): Expression;
@@ -3040,11 +3080,11 @@ declare namespace ts {
/**
* Gets the constant value to emit for an expression.
*/
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number;
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number;
/**
* Sets the constant value to emit for an expression.
*/
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression;
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression;
/**
* Adds an EmitHelper to a node.
*/
@@ -3069,17 +3109,13 @@ declare namespace ts {
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
/** Array that is only intended to be pushed to, never read. */
interface Push<T> {
push(value: T): void;
}
function moduleHasNonRelativeName(moduleName: string): boolean;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
@@ -3218,6 +3254,7 @@ declare namespace ts {
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
@@ -3246,9 +3283,10 @@ declare namespace ts {
* @param host Instance of ParseConfigHost used to enumerate files in folder.
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
* @param resolutionStack Only present for backwards-compatibility. Should be empty.
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine;
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined;
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -3422,6 +3460,8 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[];
getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[];
getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -3492,6 +3532,10 @@ declare namespace ts {
/** Text changes to apply to each file as part of the code action */
changes: FileTextChanges[];
}
interface ApplicableRefactorInfo {
name: string;
description: string;
}
interface TextInsertion {
newText: string;
/** The position in newText the caret should point to after the insertion. */
@@ -4006,6 +4050,7 @@ declare namespace ts {
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: MapLike<string>;
transformers?: CustomTransformers;
}
interface TranspileOutput {
outputText: string;
+4208 -2942
View File
File diff suppressed because it is too large Load Diff
+162 -117
View File
@@ -359,9 +359,10 @@ declare namespace ts {
SyntaxList = 294,
NotEmittedStatement = 295,
PartiallyEmittedExpression = 296,
MergeDeclarationMarker = 297,
EndOfDeclarationMarker = 298,
Count = 299,
CommaListExpression = 297,
MergeDeclarationMarker = 298,
EndOfDeclarationMarker = 299,
Count = 300,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -474,6 +475,10 @@ declare namespace ts {
type ModifiersArray = NodeArray<Modifier>;
interface Identifier extends PrimaryExpression {
kind: SyntaxKind.Identifier;
/**
* Text of identifier (with escapes converted to characters).
* If the identifier begins with two underscores, this will begin with three.
*/
text: string;
originalKeywordKind?: SyntaxKind;
isInJSDocNamespace?: boolean;
@@ -491,9 +496,11 @@ declare namespace ts {
type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
}
interface NamedDeclaration extends Declaration {
name?: DeclarationName;
}
interface DeclarationStatement extends Declaration, Statement {
interface DeclarationStatement extends NamedDeclaration, Statement {
name?: Identifier | StringLiteral | NumericLiteral;
}
interface ComputedPropertyName extends Node {
@@ -504,7 +511,7 @@ declare namespace ts {
kind: SyntaxKind.Decorator;
expression: LeftHandSideExpression;
}
interface TypeParameterDeclaration extends Declaration {
interface TypeParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.TypeParameter;
parent?: DeclarationWithTypeParameters;
name: Identifier;
@@ -512,7 +519,7 @@ declare namespace ts {
default?: TypeNode;
expression?: Expression;
}
interface SignatureDeclaration extends Declaration {
interface SignatureDeclaration extends NamedDeclaration {
name?: PropertyName;
typeParameters?: NodeArray<TypeParameterDeclaration>;
parameters: NodeArray<ParameterDeclaration>;
@@ -525,7 +532,7 @@ declare namespace ts {
kind: SyntaxKind.ConstructSignature;
}
type BindingName = Identifier | BindingPattern;
interface VariableDeclaration extends Declaration {
interface VariableDeclaration extends NamedDeclaration {
kind: SyntaxKind.VariableDeclaration;
parent?: VariableDeclarationList | CatchClause;
name: BindingName;
@@ -537,7 +544,7 @@ declare namespace ts {
parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement;
declarations: NodeArray<VariableDeclaration>;
}
interface ParameterDeclaration extends Declaration {
interface ParameterDeclaration extends NamedDeclaration {
kind: SyntaxKind.Parameter;
parent?: SignatureDeclaration;
dotDotDotToken?: DotDotDotToken;
@@ -546,7 +553,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface BindingElement extends Declaration {
interface BindingElement extends NamedDeclaration {
kind: SyntaxKind.BindingElement;
parent?: BindingPattern;
propertyName?: PropertyName;
@@ -568,7 +575,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface ObjectLiteralElement extends Declaration {
interface ObjectLiteralElement extends NamedDeclaration {
_objectLiteralBrandBrand: any;
name?: PropertyName;
}
@@ -590,7 +597,7 @@ declare namespace ts {
kind: SyntaxKind.SpreadAssignment;
expression: Expression;
}
interface VariableLikeDeclaration extends Declaration {
interface VariableLikeDeclaration extends NamedDeclaration {
propertyName?: PropertyName;
dotDotDotToken?: DotDotDotToken;
name: DeclarationName;
@@ -598,7 +605,7 @@ declare namespace ts {
type?: TypeNode;
initializer?: Expression;
}
interface PropertyLikeDeclaration extends Declaration {
interface PropertyLikeDeclaration extends NamedDeclaration {
name: PropertyName;
}
interface ObjectBindingPattern extends Node {
@@ -950,7 +957,7 @@ declare namespace ts {
}
type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression;
type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
interface PropertyAccessExpression extends MemberExpression, Declaration {
interface PropertyAccessExpression extends MemberExpression, NamedDeclaration {
kind: SyntaxKind.PropertyAccessExpression;
expression: LeftHandSideExpression;
name: Identifier;
@@ -1016,7 +1023,7 @@ declare namespace ts {
}
interface MetaProperty extends PrimaryExpression {
kind: SyntaxKind.MetaProperty;
keywordToken: SyntaxKind;
keywordToken: SyntaxKind.NewKeyword;
name: Identifier;
}
interface JsxElement extends PrimaryExpression {
@@ -1076,6 +1083,13 @@ declare namespace ts {
interface NotEmittedStatement extends Statement {
kind: SyntaxKind.NotEmittedStatement;
}
/**
* A list of comma-seperated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
elements: NodeArray<Expression>;
}
interface EmptyStatement extends Statement {
kind: SyntaxKind.EmptyStatement;
}
@@ -1197,7 +1211,7 @@ declare namespace ts {
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
interface ClassLikeDeclaration extends NamedDeclaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
heritageClauses?: NodeArray<HeritageClause>;
@@ -1210,11 +1224,11 @@ declare namespace ts {
interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression {
kind: SyntaxKind.ClassExpression;
}
interface ClassElement extends Declaration {
interface ClassElement extends NamedDeclaration {
_classElementBrand: any;
name?: PropertyName;
}
interface TypeElement extends Declaration {
interface TypeElement extends NamedDeclaration {
_typeElementBrand: any;
name?: PropertyName;
questionToken?: QuestionToken;
@@ -1238,7 +1252,7 @@ declare namespace ts {
typeParameters?: NodeArray<TypeParameterDeclaration>;
type: TypeNode;
}
interface EnumMember extends Declaration {
interface EnumMember extends NamedDeclaration {
kind: SyntaxKind.EnumMember;
parent?: EnumDeclaration;
name: PropertyName;
@@ -1297,13 +1311,13 @@ declare namespace ts {
moduleSpecifier: Expression;
}
type NamedImportBindings = NamespaceImport | NamedImports;
interface ImportClause extends Declaration {
interface ImportClause extends NamedDeclaration {
kind: SyntaxKind.ImportClause;
parent?: ImportDeclaration;
name?: Identifier;
namedBindings?: NamedImportBindings;
}
interface NamespaceImport extends Declaration {
interface NamespaceImport extends NamedDeclaration {
kind: SyntaxKind.NamespaceImport;
parent?: ImportClause;
name: Identifier;
@@ -1330,13 +1344,13 @@ declare namespace ts {
elements: NodeArray<ExportSpecifier>;
}
type NamedImportsOrExports = NamedImports | NamedExports;
interface ImportSpecifier extends Declaration {
interface ImportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ImportSpecifier;
parent?: NamedImports;
propertyName?: Identifier;
name: Identifier;
}
interface ExportSpecifier extends Declaration {
interface ExportSpecifier extends NamedDeclaration {
kind: SyntaxKind.ExportSpecifier;
parent?: NamedExports;
propertyName?: Identifier;
@@ -1467,7 +1481,7 @@ declare namespace ts {
kind: SyntaxKind.JSDocTypeTag;
typeExpression: JSDocTypeExpression;
}
interface JSDocTypedefTag extends JSDocTag, Declaration {
interface JSDocTypedefTag extends JSDocTag, NamedDeclaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
@@ -1706,11 +1720,11 @@ declare namespace ts {
/** Note that the resulting nodes cannot be checked. */
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolAtLocation(node: Node): Symbol | undefined;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;
@@ -1720,38 +1734,48 @@ declare namespace ts {
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
getContextualType(node: Expression): Type;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
getContextualType(node: Expression): Type | undefined;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isUnknownSymbol(symbol: Symbol): boolean;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
/** Follow all aliases to get the original symbol. */
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type;
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
}
enum NodeBuilderFlags {
None = 0,
allowThisInObjectLiteral = 1,
allowQualifedNameInPlaceOfIdentifier = 2,
allowTypeParameterInQualifiedName = 4,
allowAnonymousIdentifier = 8,
allowEmptyUnionOrIntersection = 16,
allowEmptyTuple = 32,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
SuppressAnyReturnType = 256,
WriteTypeParametersInQualifiedName = 512,
AllowThisInObjectLiteral = 1024,
AllowQualifedNameInPlaceOfIdentifier = 2048,
AllowAnonymousIdentifier = 8192,
AllowEmptyUnionOrIntersection = 16384,
AllowEmptyTuple = 32768,
IgnoreErrors = 60416,
InObjectTypeLiteral = 1048576,
InTypeAlias = 8388608,
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -1912,18 +1936,18 @@ declare namespace ts {
Index = 262144,
IndexedAccess = 524288,
NonPrimitive = 16777216,
Literal = 480,
Literal = 224,
StringOrNumberLiteral = 96,
PossiblyFalsy = 7406,
StringLike = 262178,
NumberLike = 340,
NumberLike = 84,
BooleanLike = 136,
EnumLike = 272,
UnionOrIntersection = 196608,
StructuredType = 229376,
StructuredOrTypeVariable = 1032192,
TypeVariable = 540672,
Narrowable = 17810431,
Narrowable = 17810175,
NotUnionOrUnit = 16810497,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
@@ -1935,15 +1959,17 @@ declare namespace ts {
aliasTypeArguments?: Type[];
}
interface LiteralType extends Type {
text: string;
value: string | number;
freshType?: LiteralType;
regularType?: LiteralType;
}
interface EnumType extends Type {
memberTypes: EnumLiteralType[];
interface StringLiteralType extends LiteralType {
value: string;
}
interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType;
interface NumberLiteralType extends LiteralType {
value: number;
}
interface EnumType extends Type {
}
enum ObjectFlags {
Class = 1,
@@ -1988,7 +2014,7 @@ declare namespace ts {
*/
interface TypeReference extends ObjectType {
target: GenericType;
typeArguments: Type[];
typeArguments?: Type[];
}
interface GenericType extends InterfaceType, TypeReference {
}
@@ -2024,7 +2050,7 @@ declare namespace ts {
}
interface Signature {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
typeParameters?: TypeParameter[];
parameters: Symbol[];
}
enum IndexKind {
@@ -2059,9 +2085,9 @@ declare namespace ts {
next?: DiagnosticMessageChain;
}
interface Diagnostic {
file: SourceFile;
start: number;
length: number;
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
messageText: string | DiagnosticMessageChain;
category: DiagnosticCategory;
code: number;
@@ -2329,6 +2355,7 @@ declare namespace ts {
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2611,14 +2638,14 @@ declare namespace ts {
function isWhiteSpaceSingleLine(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function couldStartTrivia(text: string, pos: number): boolean;
function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U;
function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U;
function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined;
function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined;
function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U;
function reduceEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
/** Optionally, get the shebang */
function getShebang(text: string): string;
function getShebang(text: string): string | undefined;
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;
@@ -2709,6 +2736,7 @@ declare namespace ts {
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier, typeArguments: NodeArray<TypeNode> | undefined): Identifier;
/** Create a unique temporary variable. */
function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier;
/** Create a unique temporary variable for use in a loop. */
@@ -2727,58 +2755,19 @@ declare namespace ts {
function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName;
function createComputedPropertyName(expression: Expression): ComputedPropertyName;
function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName;
function createSignatureDeclaration(kind: SyntaxKind, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): SignatureDeclaration;
function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode;
function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): FunctionTypeNode;
function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode;
function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructorTypeNode;
function createCallSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
function updateCallSignatureDeclaration(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
function createConstructSignatureDeclaration(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
function updateConstructSignatureDeclaration(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createLiteralTypeNode(literal: Expression): LiteralTypeNode;
function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode;
function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode;
function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode;
function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode;
function createTypeQueryNode(exprName: EntityName): TypeQueryNode;
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType, types: TypeNode[]): UnionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.IntersectionType, types: TypeNode[]): IntersectionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionOrIntersectionTypeNode;
function updateUnionOrIntersectionTypeNode(node: UnionOrIntersectionTypeNode, types: NodeArray<TypeNode>): UnionOrIntersectionTypeNode;
function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode;
function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode;
function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode;
function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function createIndexSignatureDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function updateIndexSignatureDeclaration(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function createParameter(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration;
function updateParameter(node: ParameterDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration;
function createDecorator(expression: Expression): Decorator;
function updateDecorator(node: Decorator, expression: Expression): Decorator;
function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature;
function createProperty(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration;
function updateProperty(node: PropertyDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, type: TypeNode | undefined, initializer: Expression): PropertyDeclaration;
function createMethodDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function updateMethodSignature(node: MethodSignature, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined, name: PropertyName, questionToken: QuestionToken | undefined): MethodSignature;
function createMethod(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function updateMethod(node: MethodDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
function createConstructor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
@@ -2786,6 +2775,45 @@ declare namespace ts {
function updateGetAccessor(node: GetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration;
function createSetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
function updateSetAccessor(node: SetAccessorDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: PropertyName, parameters: ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
function createIndexSignature(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function updateIndexSignature(node: IndexSignatureDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, parameters: ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
function createKeywordTypeNode(kind: KeywordTypeNode["kind"]): KeywordTypeNode;
function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode): TypePredicateNode;
function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode;
function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined): TypeReferenceNode;
function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode;
function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): FunctionTypeNode;
function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode;
function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructorTypeNode;
function createTypeQueryNode(exprName: EntityName): TypeQueryNode;
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
function createTypeLiteralNode(members: TypeElement[]): TypeLiteralNode;
function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
function createTupleTypeNode(elementTypes: TypeNode[]): TupleTypeNode;
function updateTypleTypeNode(node: TupleTypeNode, elementTypes: TypeNode[]): TupleTypeNode;
function createUnionTypeNode(types: TypeNode[]): UnionTypeNode;
function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray<TypeNode>): UnionTypeNode;
function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode;
function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray<TypeNode>): IntersectionTypeNode;
function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]): UnionTypeNode | IntersectionTypeNode;
function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
function createThisTypeNode(): ThisTypeNode;
function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
function createMappedTypeNode(readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyToken | undefined, typeParameter: TypeParameterDeclaration, questionToken: QuestionToken | undefined, type: TypeNode | undefined): MappedTypeNode;
function createLiteralTypeNode(literal: Expression): LiteralTypeNode;
function updateLiteralTypeNode(node: LiteralTypeNode, literal: Expression): LiteralTypeNode;
function createObjectBindingPattern(elements: BindingElement[]): ObjectBindingPattern;
function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern;
function createArrayBindingPattern(elements: ArrayBindingElement[]): ArrayBindingPattern;
@@ -2827,7 +2855,7 @@ declare namespace ts {
function createPostfix(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression;
function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression;
function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression;
function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression;
function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression;
function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression;
function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression;
@@ -2847,16 +2875,15 @@ declare namespace ts {
function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression;
function createNonNullExpression(expression: Expression): NonNullExpression;
function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression;
function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty;
function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty;
function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
function createSemicolonClassElement(): SemicolonClassElement;
function createBlock(statements: Statement[], multiLine?: boolean): Block;
function updateBlock(node: Block, statements: Statement[]): Block;
function createVariableStatement(modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList | VariableDeclaration[]): VariableStatement;
function updateVariableStatement(node: VariableStatement, modifiers: Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement;
function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList;
function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration;
function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
function createEmptyStatement(): EmptyStatement;
function createStatement(expression: Expression): ExpressionStatement;
function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement;
@@ -2888,10 +2915,19 @@ declare namespace ts {
function updateThrow(node: ThrowStatement, expression: Expression): ThrowStatement;
function createTry(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
function createDebuggerStatement(): DebuggerStatement;
function createVariableDeclaration(name: string | BindingName, type?: TypeNode, initializer?: Expression): VariableDeclaration;
function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
function createVariableDeclarationList(declarations: VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
function updateVariableDeclarationList(node: VariableDeclarationList, declarations: VariableDeclaration[]): VariableDeclarationList;
function createFunctionDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
function createClassDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration;
function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration;
function createInterfaceDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration;
function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[] | undefined, members: TypeElement[]): InterfaceDeclaration;
function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
function createEnumDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, members: EnumMember[]): EnumDeclaration;
function updateEnumDeclaration(node: EnumDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, members: EnumMember[]): EnumDeclaration;
function createModuleDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration;
@@ -2900,6 +2936,8 @@ declare namespace ts {
function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock;
function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock;
function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock;
function createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration;
function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration;
function createImportEqualsDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
function createImportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration;
@@ -2930,20 +2968,20 @@ declare namespace ts {
function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement;
function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes;
function updateJsxAttributes(jsxAttributes: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes;
function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute;
function createJsxAttributes(properties: JsxAttributeLike[]): JsxAttributes;
function updateJsxAttributes(node: JsxAttributes, properties: JsxAttributeLike[]): JsxAttributes;
function createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute;
function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute;
function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression;
function updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression;
function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause;
function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause;
function createCaseClause(expression: Expression, statements: Statement[]): CaseClause;
function updateCaseClause(node: CaseClause, expression: Expression, statements: Statement[]): CaseClause;
function createDefaultClause(statements: Statement[]): DefaultClause;
function updateDefaultClause(node: DefaultClause, statements: Statement[]): DefaultClause;
function createHeritageClause(token: HeritageClause["token"], types: ExpressionWithTypeArguments[]): HeritageClause;
function updateHeritageClause(node: HeritageClause, types: ExpressionWithTypeArguments[]): HeritageClause;
function createCatchClause(variableDeclaration: string | VariableDeclaration, block: Block): CatchClause;
function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration, block: Block): CatchClause;
function createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment;
@@ -2976,6 +3014,8 @@ declare namespace ts {
*/
function createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression;
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: Expression[]): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: Expression[]): CommaListExpression;
function createBundle(sourceFiles: SourceFile[]): Bundle;
function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle;
function createComma(left: Expression, right: Expression): Expression;
@@ -3040,11 +3080,11 @@ declare namespace ts {
/**
* Gets the constant value to emit for an expression.
*/
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number;
function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number;
/**
* Sets the constant value to emit for an expression.
*/
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression;
function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number): PropertyAccessExpression | ElementAccessExpression;
/**
* Adds an EmitHelper to a node.
*/
@@ -3069,17 +3109,13 @@ declare namespace ts {
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T | undefined;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
/** Array that is only intended to be pushed to, never read. */
interface Push<T> {
push(value: T): void;
}
function moduleHasNonRelativeName(moduleName: string): boolean;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
@@ -3218,6 +3254,7 @@ declare namespace ts {
getNewLine(): string;
}
function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string;
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
@@ -3246,9 +3283,10 @@ declare namespace ts {
* @param host Instance of ParseConfigHost used to enumerate files in folder.
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
* @param resolutionStack Only present for backwards-compatibility. Should be empty.
*/
function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine;
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined;
function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -3422,6 +3460,8 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: FormatCodeSettings): CodeAction[];
getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[];
getRefactorCodeActions(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string): CodeAction[] | undefined;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getProgram(): Program;
dispose(): void;
@@ -3492,6 +3532,10 @@ declare namespace ts {
/** Text changes to apply to each file as part of the code action */
changes: FileTextChanges[];
}
interface ApplicableRefactorInfo {
name: string;
description: string;
}
interface TextInsertion {
newText: string;
/** The position in newText the caret should point to after the insertion. */
@@ -4006,6 +4050,7 @@ declare namespace ts {
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: MapLike<string>;
transformers?: CustomTransformers;
}
interface TranspileOutput {
outputText: string;
+4208 -2942
View File
File diff suppressed because it is too large Load Diff
+1155 -91
View File
File diff suppressed because it is too large Load Diff
+48 -44
View File
@@ -149,7 +149,7 @@ namespace ts {
inStrictMode = bindInStrictMode(file, opts);
classifiableNames = createMap<string>();
symbolCount = 0;
skipTransformFlagAggregation = isDeclarationFile(file);
skipTransformFlagAggregation = file.isDeclarationFile;
Symbol = objectAllocator.getSymbolConstructor();
@@ -182,7 +182,7 @@ namespace ts {
return bindSourceFile;
function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean {
if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !isDeclarationFile(file)) {
if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) {
// bind in strict mode source files with alwaysStrict option
return true;
}
@@ -260,18 +260,9 @@ namespace ts {
case SyntaxKind.ExportAssignment:
return (<ExportAssignment>node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
switch (getSpecialPropertyAssignmentKind(node as BinaryExpression)) {
case SpecialPropertyAssignmentKind.ModuleExports:
// module.exports = ...
return "export=";
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
// exports.x = ... or this.y = ...
return ((node as BinaryExpression).left as PropertyAccessExpression).name.text;
case SpecialPropertyAssignmentKind.PrototypeProperty:
// className.prototype.methodName = ...
return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text;
if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) {
// module.exports = ...
return "export=";
}
Debug.fail("Unknown binary declaration kind");
break;
@@ -439,6 +430,7 @@ namespace ts {
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
if (node.kind === SyntaxKind.JSDocTypedefTag) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag &&
(node as JSDocTypedefTag).name &&
(node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier &&
@@ -603,9 +595,7 @@ namespace ts {
// Binding of JsDocComment should be done before the current block scope container changes.
// because the scope of JsDocComment should not be affected by whether the current node is a
// container or not.
if (isInJavaScriptFile(node) && node.jsDoc) {
forEach(node.jsDoc, bind);
}
forEach(node.jsDoc, bind);
if (checkUnreachable(node)) {
bindEachChild(node);
return;
@@ -1913,9 +1903,7 @@ namespace ts {
// Here the current node is "foo", which is a container, but the scope of "MyType" should
// not be inside "foo". Therefore we always bind @typedef before bind the parent node,
// and skip binding this tag later when binding all the other jsdoc tags.
if (isInJavaScriptFile(node)) {
bindJSDocTypedefTagIfAny(node);
}
bindJSDocTypedefTagIfAny(node);
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
@@ -2003,7 +1991,7 @@ namespace ts {
// for typedef type names with namespaces, bind the new jsdoc type symbol here
// because it requires all containing namespaces to be in effect, namely the
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if ((<Identifier>node).isInJSDocNamespace) {
if (isInJavaScriptFile(node) && (<Identifier>node).isInJSDocNamespace) {
let parentNode = node.parent;
while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) {
parentNode = parentNode.parent;
@@ -2073,10 +2061,7 @@ namespace ts {
return bindVariableDeclarationOrBindingElement(<VariableDeclaration | BindingElement>node);
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.JSDocRecordMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property | ((<PropertyDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
case SyntaxKind.JSDocPropertyTag:
return bindJSDocProperty(<JSDocPropertyTag>node);
return bindPropertyWorker(node as PropertyDeclaration | PropertySignature);
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
@@ -2121,13 +2106,10 @@ namespace ts {
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.JSDocFunctionType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
case SyntaxKind.TypeLiteral:
case SyntaxKind.MappedType:
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.JSDocRecordType:
return bindAnonymousDeclaration(<Declaration>node, SymbolFlags.TypeLiteral, "__type");
return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode);
case SyntaxKind.ObjectLiteralExpression:
return bindObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.FunctionExpression:
@@ -2148,11 +2130,6 @@ namespace ts {
return bindClassLikeDeclaration(<ClassLikeDeclaration>node);
case SyntaxKind.InterfaceDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes);
case SyntaxKind.JSDocTypedefTag:
if (!(<JSDocTypedefTag>node).fullName || (<JSDocTypedefTag>node).fullName.kind === SyntaxKind.Identifier) {
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
}
break;
case SyntaxKind.TypeAliasDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
case SyntaxKind.EnumDeclaration:
@@ -2190,9 +2167,41 @@ namespace ts {
// falls through
case SyntaxKind.ModuleBlock:
return updateStrictModeStatementList((<Block | ModuleBlock>node).statements);
default:
if (isInJavaScriptFile(node)) return bindJSDocWorker(node);
}
}
function bindJSDocWorker(node: Node) {
switch (node.kind) {
case SyntaxKind.JSDocRecordMember:
return bindPropertyWorker(node as JSDocRecordMember);
case SyntaxKind.JSDocPropertyTag:
return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
case SyntaxKind.JSDocFunctionType:
return bindFunctionOrConstructorType(<SignatureDeclaration>node);
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.JSDocRecordType:
return bindAnonymousTypeWorker(node as JSDocTypeLiteral | JSDocRecordType);
case SyntaxKind.JSDocTypedefTag: {
const { fullName } = node as JSDocTypedefTag;
if (!fullName || fullName.kind === SyntaxKind.Identifier) {
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
}
break;
}
}
}
function bindPropertyWorker(node: PropertyDeclaration | PropertySignature) {
return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes);
}
function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral | JSDocRecordType) {
return bindAnonymousDeclaration(<Declaration>node, SymbolFlags.TypeLiteral, "__type");
}
function checkTypePredicate(node: TypePredicateNode) {
const { parameterName, type } = node;
if (parameterName && parameterName.kind === SyntaxKind.Identifier) {
@@ -2527,7 +2536,7 @@ namespace ts {
}
function bindFunctionDeclaration(node: FunctionDeclaration) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (!file.isDeclarationFile && !isInAmbientContext(node)) {
if (isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
@@ -2544,7 +2553,7 @@ namespace ts {
}
function bindFunctionExpression(node: FunctionExpression) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (!file.isDeclarationFile && !isInAmbientContext(node)) {
if (isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
@@ -2558,10 +2567,8 @@ namespace ts {
}
function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
if (!isDeclarationFile(file) && !isInAmbientContext(node)) {
if (isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
if (!file.isDeclarationFile && !isInAmbientContext(node) && isAsyncFunction(node)) {
emitFlags |= NodeFlags.HasAsyncFunctions;
}
if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) {
@@ -2573,10 +2580,6 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}
function bindJSDocProperty(node: JSDocPropertyTag) {
return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
// reachability checks
function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean {
@@ -3395,6 +3398,7 @@ namespace ts {
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.LiteralType:
case SyntaxKind.NamespaceExportDeclaration:
// Types and signatures are TypeScript syntax, and exclude all other facts.
transformFlags = TransformFlags.AssertTypeScript;
excludeFlags = TransformFlags.TypeExcludes;
+751 -607
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -139,6 +139,7 @@ namespace ts {
"es2017.object": "lib.es2017.object.d.ts",
"es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts",
"es2017.string": "lib.es2017.string.d.ts",
"es2017.intl": "lib.es2017.intl.d.ts",
"esnext.asynciterable": "lib.esnext.asynciterable.d.ts",
}),
},
+4 -2
View File
@@ -58,8 +58,10 @@ namespace ts {
}
const isEmittedNode = node.kind !== SyntaxKind.NotEmittedStatement;
const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0;
const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
const skipLeadingComments = pos < 0 || (emitFlags & EmitFlags.NoLeadingComments) !== 0 || node.kind === SyntaxKind.JsxText;
const skipTrailingComments = end < 0 || (emitFlags & EmitFlags.NoTrailingComments) !== 0 || node.kind === SyntaxKind.JsxText;
// Emit leading comments if the position is not synthesized and the node
// has not opted out from emitting leading comments.
+10 -2
View File
@@ -230,6 +230,8 @@ namespace ts {
* If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit"
* At that point findAncestor returns undefined.
*/
export function findAncestor<T extends Node>(node: Node, callback: (element: Node) => element is T): T | undefined;
export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node | undefined;
export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node {
while (node) {
const result = callback(node);
@@ -1762,6 +1764,11 @@ namespace ts {
return str.lastIndexOf(prefix, 0) === 0;
}
/* @internal */
export function removePrefix(str: string, prefix: string): string {
return startsWith(str, prefix) ? str.substr(prefix.length) : str;
}
/* @internal */
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
@@ -1776,7 +1783,8 @@ namespace ts {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsAny(path: string, extensions: string[]): boolean {
/* @internal */
export function fileExtensionIsOneOf(path: string, extensions: string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
@@ -1976,7 +1984,7 @@ namespace ts {
for (const current of files) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsAny(name, extensions)) continue;
if (extensions && !fileExtensionIsOneOf(name, extensions)) continue;
if (excludeRegex && excludeRegex.test(absoluteName)) continue;
if (!includeFileRegexes) {
results[0].push(name);
+19 -9
View File
@@ -190,7 +190,7 @@ namespace ts {
const writer = <EmitTextWriterWithSymbolWriter>createTextWriter(newLine);
writer.trackSymbol = trackSymbol;
writer.reportInaccessibleThisError = reportInaccessibleThisError;
writer.reportIllegalExtends = reportIllegalExtends;
writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression;
writer.writeKeyword = writer.write;
writer.writeOperator = writer.write;
writer.writePunctuation = writer.write;
@@ -314,11 +314,11 @@ namespace ts {
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
function reportIllegalExtends() {
function reportPrivateInBaseOfClassExpression(propertyName: string) {
if (errorNameNode) {
reportedDeclarationError = true;
emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced,
declarationNameToString(errorNameNode)));
emitterDiagnostics.add(
createDiagnosticForNode(errorNameNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
}
}
@@ -344,7 +344,9 @@ namespace ts {
}
else {
errorNameNode = declaration.name;
const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue |
const format = TypeFormatFlags.UseTypeOfFunction |
TypeFormatFlags.WriteClassExpressionAsTypeLiteral |
TypeFormatFlags.UseTypeAliasValue |
(shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0);
resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer);
errorNameNode = undefined;
@@ -360,7 +362,11 @@ namespace ts {
}
else {
errorNameNode = signature.name;
resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
resolver.writeReturnTypeOfSignatureDeclaration(
signature,
enclosingDeclaration,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral,
writer);
errorNameNode = undefined;
}
}
@@ -621,7 +627,11 @@ namespace ts {
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = () => diagnostic;
resolver.writeTypeOfExpression(expr, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer);
resolver.writeTypeOfExpression(
expr,
enclosingDeclaration,
TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue | TypeFormatFlags.WriteClassExpressionAsTypeLiteral,
writer);
write(";");
writeLine();
return tempVarName;
@@ -984,7 +994,7 @@ namespace ts {
const enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
write(enumMemberValue.toString());
write(getTextOfConstantValue(enumMemberValue));
}
write(",");
writeLine();
@@ -1840,7 +1850,7 @@ namespace ts {
function writeReferencePath(referencedFile: SourceFile, addBundledFileReference: boolean, emitOnlyDtsFiles: boolean): boolean {
let declFileName: string;
let addedBundledEmitReference = false;
if (isDeclarationFile(referencedFile)) {
if (referencedFile.isDeclarationFile) {
// Declaration file, use declaration file name
declFileName = referencedFile.fileName;
}
+40 -3
View File
@@ -1075,7 +1075,7 @@
"category": "Error",
"code": 2345
},
"Supplied parameters do not match any signature of call target.": {
"Call target does not contain any signatures.": {
"category": "Error",
"code": 2346
},
@@ -1863,6 +1863,30 @@
"category": "Error",
"code": 2552
},
"Computed values are not permitted in an enum with string valued members.": {
"category": "Error",
"code": 2553
},
"Expected {0} arguments, but got {1}.": {
"category": "Error",
"code": 2554
},
"Expected at least {0} arguments, but got {1}.": {
"category": "Error",
"code": 2555
},
"Expected {0} arguments, but got a minimum of {1}.": {
"category": "Error",
"code": 2556
},
"Expected at least {0} arguments, but got a minimum of {1}.": {
"category": "Error",
"code": 2557
},
"Expected {0} type arguments, but got {1}.": {
"category": "Error",
"code": 2558
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -2440,9 +2464,9 @@
"category": "Error",
"code": 4092
},
"'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced.": {
"Property '{0}' of exported class expression may not be private or protected.": {
"category": "Error",
"code": 4093
"code": 4094
},
"The current host does not support the '{0}' option.": {
@@ -3045,6 +3069,10 @@
"category": "Message",
"code": 6136
},
"Cannot import type declaration files. Consider importing '{0}' instead of '{1}'.": {
"category": "Error",
"code": 6137
},
"Property '{0}' is declared but never used.": {
"category": "Error",
"code": 6138
@@ -3564,6 +3592,15 @@
"code": 90022
},
"Convert function to an ES2015 class": {
"category": "Message",
"code": 95001
},
"Convert function '{0}' to class": {
"category": "Message",
"code": 95002
},
"Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": {
"category": "Error",
"code": 8017
+87 -22
View File
@@ -153,7 +153,7 @@ namespace ts {
for (let i = 0; i < numNodes; i++) {
const currentNode = bundle ? bundle.sourceFiles[i] : node;
const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile;
const shouldSkip = compilerOptions.noEmitHelpers || (sourceFile && getExternalHelpersModuleName(sourceFile) !== undefined);
const shouldSkip = compilerOptions.noEmitHelpers || getExternalHelpersModuleName(sourceFile) !== undefined;
const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit;
const helpers = getEmitHelpers(currentNode);
if (helpers) {
@@ -200,7 +200,9 @@ namespace ts {
onSetSourceFile,
substituteNode,
onBeforeEmitNodeArray,
onAfterEmitNodeArray
onAfterEmitNodeArray,
onBeforeEmitToken,
onAfterEmitToken
} = handlers;
const newLine = getNewLineCharacter(printerOptions);
@@ -212,7 +214,7 @@ namespace ts {
emitLeadingCommentsOfPosition,
} = comments;
let currentSourceFile: SourceFile;
let currentSourceFile: SourceFile | undefined;
let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
let autoGeneratedIdToGeneratedName: string[]; // Map of generated names for temp and loop variables.
let generatedNames: Map<string>; // Set of names generated by the NameGenerator.
@@ -264,7 +266,12 @@ namespace ts {
return endPrint();
}
function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter) {
/**
* If `sourceFile` is `undefined`, `node` must be a synthesized `TypeNode`.
*/
function writeNode(hint: EmitHint, node: TypeNode, sourceFile: undefined, output: EmitTextWriter): void;
function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, output: EmitTextWriter): void;
function writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, output: EmitTextWriter) {
const previousWriter = writer;
setWriter(output);
print(hint, node, sourceFile);
@@ -305,8 +312,10 @@ namespace ts {
return text;
}
function print(hint: EmitHint, node: Node, sourceFile: SourceFile) {
setSourceFile(sourceFile);
function print(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined) {
if (sourceFile) {
setSourceFile(sourceFile);
}
pipelineEmitWithNotification(hint, node);
}
@@ -399,7 +408,7 @@ namespace ts {
// Strict mode reserved words
// Contextual keywords
if (isKeyword(kind)) {
writeTokenText(kind);
writeTokenNode(node);
return;
}
@@ -562,6 +571,8 @@ namespace ts {
return emitModuleBlock(<ModuleBlock>node);
case SyntaxKind.CaseBlock:
return emitCaseBlock(<CaseBlock>node);
case SyntaxKind.NamespaceExportDeclaration:
return emitNamespaceExportDeclaration(<NamespaceExportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return emitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ImportDeclaration:
@@ -638,7 +649,7 @@ namespace ts {
}
if (isToken(node)) {
writeTokenText(kind);
writeTokenNode(node);
return;
}
}
@@ -665,7 +676,7 @@ namespace ts {
case SyntaxKind.SuperKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.ThisKeyword:
writeTokenText(kind);
writeTokenNode(node);
return;
// Expressions
@@ -781,6 +792,7 @@ namespace ts {
function emitIdentifier(node: Identifier) {
write(getTextOfNode(node, /*includeTrivia*/ false));
emitTypeArguments(node, node.typeArguments);
}
//
@@ -815,6 +827,7 @@ namespace ts {
function emitTypeParameter(node: TypeParameterDeclaration) {
emit(node.name);
emitWithPrefix(" extends ", node.constraint);
emitWithPrefix(" = ", node.default);
}
function emitParameter(node: ParameterDeclaration) {
@@ -849,6 +862,7 @@ namespace ts {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitWithPrefix(": ", node.type);
emitExpressionWithPrefix(" = ", node.initializer);
write(";");
@@ -870,6 +884,7 @@ namespace ts {
emitModifiers(node, node.modifiers);
writeIfPresent(node.asteriskToken, "*");
emit(node.name);
writeIfPresent(node.questionToken, "?");
emitSignatureAndBody(node, emitSignatureHead);
}
@@ -955,7 +970,10 @@ namespace ts {
function emitTypeLiteral(node: TypeLiteralNode) {
write("{");
emitList(node, node.members, ListFormat.TypeLiteralMembers);
// If the literal is empty, do not add spaces between braces.
if (node.members.length > 0) {
emitList(node, node.members, getEmitFlags(node) & EmitFlags.SingleLine ? ListFormat.SingleLineTypeLiteralMembers : ListFormat.MultiLineTypeLiteralMembers);
}
write("}");
}
@@ -1002,9 +1020,15 @@ namespace ts {
}
function emitMappedType(node: MappedTypeNode) {
const emitFlags = getEmitFlags(node);
write("{");
writeLine();
increaseIndent();
if (emitFlags & EmitFlags.SingleLine) {
write(" ");
}
else {
writeLine();
increaseIndent();
}
writeIfPresent(node.readonlyToken, "readonly ");
write("[");
emit(node.typeParameter.name);
@@ -1015,8 +1039,13 @@ namespace ts {
write(": ");
emit(node.type);
write(";");
writeLine();
decreaseIndent();
if (emitFlags & EmitFlags.SingleLine) {
write(" ");
}
else {
writeLine();
decreaseIndent();
}
write("}");
}
@@ -1131,7 +1160,7 @@ namespace ts {
// check if constant enum value is integer
const constantValue = getConstantValue(expression);
// isFinite handles cases when constantValue is undefined
return isFinite(constantValue)
return typeof constantValue === "number" && isFinite(constantValue)
&& Math.floor(constantValue) === constantValue
&& printerOptions.removeComments;
}
@@ -1237,7 +1266,7 @@ namespace ts {
const operand = node.operand;
return operand.kind === SyntaxKind.PrefixUnaryExpression
&& ((node.operator === SyntaxKind.PlusToken && ((<PrefixUnaryExpression>operand).operator === SyntaxKind.PlusToken || (<PrefixUnaryExpression>operand).operator === SyntaxKind.PlusPlusToken))
|| (node.operator === SyntaxKind.MinusToken && ((<PrefixUnaryExpression>operand).operator === SyntaxKind.MinusToken || (<PrefixUnaryExpression>operand).operator === SyntaxKind.MinusMinusToken)));
|| (node.operator === SyntaxKind.MinusToken && ((<PrefixUnaryExpression>operand).operator === SyntaxKind.MinusToken || (<PrefixUnaryExpression>operand).operator === SyntaxKind.MinusMinusToken)));
}
function emitPostfixUnaryExpression(node: PostfixUnaryExpression) {
@@ -1252,7 +1281,7 @@ namespace ts {
emitExpression(node.left);
increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined);
writeTokenText(node.operatorToken.kind);
writeTokenNode(node.operatorToken);
increaseIndentIf(indentAfterOperator, " ");
emitExpression(node.right);
decreaseIndentIf(indentBeforeOperator, indentAfterOperator);
@@ -1859,6 +1888,12 @@ namespace ts {
write(";");
}
function emitNamespaceExportDeclaration(node: NamespaceExportDeclaration) {
write("export as namespace ");
emit(node.name);
write(";");
}
function emitNamedExports(node: NamedExports) {
emitNamedImportsOrExports(node);
}
@@ -1996,6 +2031,22 @@ namespace ts {
rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)
);
// e.g:
// case 0: // Zero
// case 1: // One
// case 2: // two
// return "hi";
// If there is no statements, emitNodeWithComments of the parentNode which is caseClause will take care of trailing comment.
// So in example above, comment "// Zero" and "// One" will be emit in emitTrailingComments in emitNodeWithComments.
// However, for "case 2", because parentNode which is caseClause has an "end" property to be end of the statements (in this case return statement)
// comment "// two" will not be emitted in emitNodeWithComments.
// Therefore, we have to do the check here to emit such comment.
if (statements.length > 0) {
// We use emitTrailingCommentsOfPosition instead of emitLeadingCommentsOfPosition because leading comments is defined as comments before the node after newline character separating it from previous line
// Note: we can't use parentNode.end as such position includes statements.
emitTrailingCommentsOfPosition(statements.pos);
}
if (emitAsSingleStatement) {
write(" ");
emit(statements[0]);
@@ -2432,6 +2483,16 @@ namespace ts {
: writeTokenText(token, pos);
}
function writeTokenNode(node: Node) {
if (onBeforeEmitToken) {
onBeforeEmitToken(node);
}
writeTokenText(node.kind);
if (onAfterEmitToken) {
onAfterEmitToken(node);
}
}
function writeTokenText(token: SyntaxKind, pos?: number) {
const tokenString = tokenToString(token);
write(tokenString);
@@ -2637,7 +2698,9 @@ namespace ts {
if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
const textSourceNode = (<StringLiteral>node).textSourceNode;
if (isIdentifier(textSourceNode)) {
return "\"" + escapeNonAsciiCharacters(escapeString(getTextOfNode(textSourceNode))) + "\"";
return getEmitFlags(node) & EmitFlags.NoAsciiEscaping ?
`"${escapeString(getTextOfNode(textSourceNode))}"` :
`"${escapeNonAsciiString(getTextOfNode(textSourceNode))}"`;
}
else {
return getLiteralTextOfNode(textSourceNode);
@@ -2903,9 +2966,9 @@ namespace ts {
// Flags enum to track count of temp variables and a few dedicated names
const enum TempFlags {
Auto = 0x00000000, // No preferred name
Auto = 0x00000000, // No preferred name
CountMask = 0x0FFFFFFF, // Temp variable counter
_i = 0x10000000, // Use/preference flag for '_i'
_i = 0x10000000, // Use/preference flag for '_i'
}
const enum ListFormat {
@@ -2948,9 +3011,11 @@ namespace ts {
NoInterveningComments = 1 << 17, // Do not emit comments between each node
// Precomputed Formats
Modifiers = SingleLine | SpaceBetweenSiblings,
Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments,
HeritageClauses = SingleLine | SpaceBetweenSiblings,
TypeLiteralMembers = MultiLine | Indented,
SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented,
MultiLineTypeLiteralMembers = MultiLine | Indented,
TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented,
UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine,
IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine,
+86 -30
View File
@@ -107,15 +107,27 @@ namespace ts {
// Identifiers
export function createIdentifier(text: string): Identifier {
export function createIdentifier(text: string): Identifier;
/* @internal */
export function createIdentifier(text: string, typeArguments: TypeNode[]): Identifier;
export function createIdentifier(text: string, typeArguments?: TypeNode[]): Identifier {
const node = <Identifier>createSynthesizedNode(SyntaxKind.Identifier);
node.text = escapeIdentifier(text);
node.originalKeywordKind = text ? stringToToken(text) : SyntaxKind.Unknown;
node.autoGenerateKind = GeneratedIdentifierKind.None;
node.autoGenerateId = 0;
if (typeArguments) {
node.typeArguments = createNodeArray(typeArguments);
}
return node;
}
export function updateIdentifier(node: Identifier, typeArguments: NodeArray<TypeNode> | undefined): Identifier {
return node.typeArguments !== typeArguments
? updateNode(createIdentifier(node.text, typeArguments), node)
: node;
}
let nextAutoGenerateId = 0;
/** Create a unique temporary variable. */
@@ -271,8 +283,9 @@ namespace ts {
// Type Elements
export function createPropertySignature(name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature {
export function createPropertySignature(modifiers: Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature {
const node = createSynthesizedNode(SyntaxKind.PropertySignature) as PropertySignature;
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.questionToken = questionToken;
node.type = type;
@@ -280,12 +293,13 @@ namespace ts {
return node;
}
export function updatePropertySignature(node: PropertySignature, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.name !== name
export function updatePropertySignature(node: PropertySignature, modifiers: Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) {
return node.modifiers !== modifiers
|| node.name !== name
|| node.questionToken !== questionToken
|| node.type !== type
|| node.initializer !== initializer
? updateNode(createPropertySignature(name, questionToken, type, initializer), node)
? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
: node;
}
@@ -492,7 +506,7 @@ namespace ts {
export function createTypeReferenceNode(typeName: string | EntityName, typeArguments: TypeNode[] | undefined) {
const node = createSynthesizedNode(SyntaxKind.TypeReference) as TypeReferenceNode;
node.typeName = asName(typeName);
node.typeArguments = asNodeArray(typeArguments);
node.typeArguments = typeArguments && parenthesizeTypeParameters(typeArguments);
return node;
}
@@ -545,7 +559,7 @@ namespace ts {
export function createArrayTypeNode(elementType: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.ArrayType) as ArrayTypeNode;
node.elementType = elementType;
node.elementType = parenthesizeElementTypeMember(elementType);
return node;
}
@@ -585,7 +599,7 @@ namespace ts {
export function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: TypeNode[]) {
const node = createSynthesizedNode(kind) as UnionTypeNode | IntersectionTypeNode;
node.types = createNodeArray(types);
node.types = parenthesizeElementTypeMembers(types);
return node;
}
@@ -614,7 +628,7 @@ namespace ts {
export function createTypeOperatorNode(type: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode;
node.operator = SyntaxKind.KeyOfKeyword;
node.type = type;
node.type = parenthesizeElementTypeMember(type);
return node;
}
@@ -624,7 +638,7 @@ namespace ts {
export function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.IndexedAccessType) as IndexedAccessTypeNode;
node.objectType = objectType;
node.objectType = parenthesizeElementTypeMember(objectType);
node.indexType = indexType;
return node;
}
@@ -970,10 +984,10 @@ namespace ts {
return node;
}
export function updateBinary(node: BinaryExpression, left: Expression, right: Expression) {
export function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken) {
return node.left !== left
|| node.right !== right
? updateNode(createBinary(left, node.operatorToken, right), node)
? updateNode(createBinary(left, operator || node.operatorToken, right), node)
: node;
}
@@ -1488,19 +1502,23 @@ namespace ts {
: node;
}
export function createTypeAliasDeclaration(name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) {
export function createTypeAliasDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) {
const node = <TypeAliasDeclaration>createSynthesizedNode(SyntaxKind.TypeAliasDeclaration);
node.decorators = asNodeArray(decorators);
node.modifiers = asNodeArray(modifiers);
node.name = asName(name);
node.typeParameters = asNodeArray(typeParameters);
node.type = type;
return node;
}
export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) {
return node.name !== name
export function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: Identifier, typeParameters: TypeParameterDeclaration[] | undefined, type: TypeNode) {
return node.decorators !== decorators
|| node.modifiers !== modifiers
|| node.name !== name
|| node.typeParameters !== typeParameters
|| node.type !== type
? updateNode(createTypeAliasDeclaration(name, typeParameters, type), node)
? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
: node;
}
@@ -1613,14 +1631,14 @@ namespace ts {
: node;
}
export function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause {
export function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause {
const node = <ImportClause>createSynthesizedNode(SyntaxKind.ImportClause);
node.name = name;
node.namedBindings = namedBindings;
return node;
}
export function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings) {
export function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) {
return node.name !== name
|| node.namedBindings !== namedBindings
? updateNode(createImportClause(name, namedBindings), node)
@@ -2344,7 +2362,7 @@ namespace ts {
/**
* Sets the constant value to emit for an expression.
*/
export function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number) {
export function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: string | number) {
const emitNode = getOrCreateEmitNode(node);
emitNode.constantValue = value;
return node;
@@ -2476,6 +2494,25 @@ namespace ts {
/* @internal */
namespace ts {
export const nullTransformationContext: TransformationContext = {
enableEmitNotification: noop,
enableSubstitution: noop,
endLexicalEnvironment: () => undefined,
getCompilerOptions: notImplemented,
getEmitHost: notImplemented,
getEmitResolver: notImplemented,
hoistFunctionDeclaration: noop,
hoistVariableDeclaration: noop,
isEmitNotificationEnabled: notImplemented,
isSubstitutionEnabled: notImplemented,
onEmitNode: noop,
onSubstituteNode: notImplemented,
readEmitHelpers: notImplemented,
requestEmitHelper: noop,
resumeLexicalEnvironment: noop,
startLexicalEnvironment: noop,
suspendLexicalEnvironment: noop
};
// Compound nodes
@@ -3276,16 +3313,6 @@ namespace ts {
return statements;
}
export function parenthesizeConditionalHead(condition: Expression) {
const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken);
const emittedCondition = skipPartiallyEmittedExpressions(condition);
const conditionPrecedence = getExpressionPrecedence(emittedCondition);
if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) {
return createParen(condition);
}
return condition;
}
/**
* Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
* order of operations.
@@ -3587,6 +3614,35 @@ namespace ts {
return expression;
}
export function parenthesizeElementTypeMember(member: TypeNode) {
switch (member.kind) {
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return createParenthesizedType(member);
}
return member;
}
export function parenthesizeElementTypeMembers(members: TypeNode[]) {
return createNodeArray(sameMap(members, parenthesizeElementTypeMember));
}
export function parenthesizeTypeParameters(typeParameters: TypeNode[]) {
if (some(typeParameters)) {
const nodeArray = createNodeArray() as NodeArray<TypeNode>;
for (let i = 0; i < typeParameters.length; ++i) {
const entry = typeParameters[i];
nodeArray.push(i === 0 && isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
createParenthesizedType(entry) :
entry);
}
return nodeArray;
}
}
/**
* Clones a series of not-emitted expressions with a new inner expression.
*
@@ -3783,7 +3839,7 @@ namespace ts {
if (file.moduleName) {
return createLiteral(file.moduleName);
}
if (!isDeclarationFile(file) && (options.out || options.outFile)) {
if (!file.isDeclarationFile && (options.out || options.outFile)) {
return createLiteral(getExternalModuleNameFromPath(host, file.fileName));
}
return undefined;
+21 -5
View File
@@ -653,11 +653,13 @@ namespace ts {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
// A path mapping may have a ".ts" extension; in contrast to an import, which should omit it.
const tsExtension = tryGetExtensionFromPath(candidate);
if (tsExtension !== undefined) {
// A path mapping may have an extension, in contrast to an import, which should omit it.
const extension = tryGetExtensionFromPath(candidate);
if (extension !== undefined) {
const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
return path && { path, extension: tsExtension };
if (path !== undefined) {
return { path, extension };
}
}
return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
@@ -971,10 +973,13 @@ namespace ts {
}
}
/** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
const mangledScopedPackageSeparator = "__";
/** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
function mangleScopedPackage(moduleName: string, state: ModuleResolutionState): string {
if (startsWith(moduleName, "@")) {
const replaceSlash = moduleName.replace(ts.directorySeparator, "__");
const replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
if (replaceSlash !== moduleName) {
const mangled = replaceSlash.slice(1); // Take off the "@"
if (state.traceEnabled) {
@@ -986,6 +991,17 @@ namespace ts {
return moduleName;
}
/* @internal */
export function getPackageNameFromAtTypesDirectory(mangledName: string): string {
const withoutAtTypePrefix = removePrefix(mangledName, "@types/");
if (withoutAtTypePrefix !== mangledName) {
return withoutAtTypePrefix.indexOf("__") !== -1 ?
"@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
withoutAtTypePrefix;
}
return mangledName;
}
function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost): SearchResult<Resolved> {
const result = cache && cache.get(containingDirectory);
if (result) {
+9 -8
View File
@@ -22,19 +22,19 @@ namespace ts {
}
}
function visitNode<T>(cbNode: (node: Node) => T, node: Node): T {
function visitNode<T>(cbNode: (node: Node) => T, node?: Node): T | undefined {
if (node) {
return cbNode(node);
}
}
function visitNodeArray<T>(cbNodes: (nodes: Node[]) => T, nodes: Node[]) {
function visitNodeArray<T>(cbNodes: (nodes: Node[]) => T, nodes?: Node[]): T | undefined {
if (nodes) {
return cbNodes(nodes);
}
}
function visitEachNode<T>(cbNode: (node: Node) => T, nodes: Node[]) {
function visitEachNode<T>(cbNode: (node: Node) => T, nodes?: Node[]): T | undefined {
if (nodes) {
for (const node of nodes) {
const result = cbNode(node);
@@ -49,14 +49,14 @@ namespace ts {
// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T {
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
if (!node) {
return;
}
// The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray
// callback parameters, but that causes a closure allocation for each invocation with noticeable effects
// on performance.
const visitNodes: (cb: ((node: Node) => T) | ((node: Node[]) => T), nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode;
const visitNodes: (cb: ((node?: Node) => T | undefined) | ((node?: Node[]) => T | undefined), nodes?: Node[]) => T | undefined = cbNodeArray ? visitNodeArray : visitEachNode;
const cbNodes = cbNodeArray || cbNode;
switch (node.kind) {
case SyntaxKind.QualifiedName:
@@ -1273,12 +1273,12 @@ namespace ts {
if (token() === SyntaxKind.ExportKeyword) {
nextToken();
if (token() === SyntaxKind.DefaultKeyword) {
return lookAhead(nextTokenIsClassOrFunctionOrAsync);
return lookAhead(nextTokenCanFollowDefaultKeyword);
}
return token() !== SyntaxKind.AsteriskToken && token() !== SyntaxKind.AsKeyword && token() !== SyntaxKind.OpenBraceToken && canFollowModifier();
}
if (token() === SyntaxKind.DefaultKeyword) {
return nextTokenIsClassOrFunctionOrAsync();
return nextTokenCanFollowDefaultKeyword();
}
if (token() === SyntaxKind.StaticKeyword) {
nextToken();
@@ -1300,9 +1300,10 @@ namespace ts {
|| isLiteralPropertyName();
}
function nextTokenIsClassOrFunctionOrAsync(): boolean {
function nextTokenCanFollowDefaultKeyword(): boolean {
nextToken();
return token() === SyntaxKind.ClassKeyword || token() === SyntaxKind.FunctionKeyword ||
token() === SyntaxKind.InterfaceKeyword ||
(token() === SyntaxKind.AbstractKeyword && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
(token() === SyntaxKind.AsyncKeyword && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
}
+66 -41
View File
@@ -386,6 +386,19 @@ namespace ts {
allDiagnostics?: Diagnostic[];
}
/**
* Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
* that represent a compilation unit.
*
* Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
* triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
*
* @param rootNames - A set of root files.
* @param options - The compiler options which should be used.
* @param host - The host interacts with the underlying file system.
* @param oldProgram - Reuses an old program structure.
* @returns A 'Program' object.
*/
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
@@ -530,7 +543,8 @@ namespace ts {
getFileProcessingDiagnostics: () => fileProcessingDiagnostics,
getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives,
isSourceFileFromExternalLibrary,
dropDiagnosticsProducingTypeChecker
dropDiagnosticsProducingTypeChecker,
getSourceFileFromReference,
};
verifyCompilerOptions();
@@ -1310,7 +1324,7 @@ namespace ts {
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
}
function getOptionsDiagnostics(): Diagnostic[] {
@@ -1352,7 +1366,6 @@ namespace ts {
const isJavaScriptFile = isSourceFileJavaScript(file);
const isExternalModuleFile = isExternalModule(file);
const isDtsFile = isDeclarationFile(file);
let imports: LiteralExpression[];
let moduleAugmentations: LiteralExpression[];
@@ -1405,7 +1418,7 @@ namespace ts {
}
break;
case SyntaxKind.ModuleDeclaration:
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || isDeclarationFile(file))) {
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || file.isDeclarationFile)) {
const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name;
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
// This will happen in two cases:
@@ -1416,7 +1429,7 @@ namespace ts {
(moduleAugmentations || (moduleAugmentations = [])).push(moduleName);
}
else if (!inAmbientModule) {
if (isDtsFile) {
if (file.isDeclarationFile) {
// for global .d.ts files record name of ambient module
(ambientModules || (ambientModules = [])).push(moduleName.text);
}
@@ -1447,48 +1460,60 @@ namespace ts {
}
}
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
let diagnosticArgument: string[];
let diagnostic: DiagnosticMessage;
/** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
function getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined {
return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), fileName => filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName)));
}
function getSourceFileFromReferenceWorker(
fileName: string,
getSourceFile: (fileName: string) => SourceFile | undefined,
fail?: (diagnostic: DiagnosticMessage, ...argument: string[]) => void,
refFile?: SourceFile): SourceFile | undefined {
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) {
diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1;
diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"];
if (fail) fail(Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
return undefined;
}
else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself;
diagnosticArgument = [fileName];
}
}
else {
const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) {
diagnostic = Diagnostics.File_0_not_found;
fileName += ".ts";
diagnosticArgument = [fileName];
}
}
}
if (diagnostic) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
const sourceFile = getSourceFile(fileName);
if (fail) {
if (!sourceFile) {
fail(Diagnostics.File_0_not_found, fileName);
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
fail(Diagnostics.A_file_cannot_have_a_reference_to_itself, fileName);
}
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
return sourceFile;
} else {
const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
if (sourceFileNoExtension) return sourceFileNoExtension;
if (fail && options.allowNonTsExtensions) {
fail(Diagnostics.File_0_not_found, fileName);
return undefined;
}
const sourceFileWithAddedExtension = forEach(supportedExtensions, extension => getSourceFile(fileName + extension));
if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.File_0_not_found, fileName + ".ts");
return sourceFileWithAddedExtension;
}
}
/** This has side effects through `findSourceFile`. */
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): void {
getSourceFileFromReferenceWorker(fileName,
fileName => findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd),
(diagnostic, ...args) => {
fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined
? createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...args)
: createCompilerDiagnostic(diagnostic, ...args));
},
refFile);
}
function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
@@ -1734,7 +1759,7 @@ namespace ts {
const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory));
for (const sourceFile of sourceFiles) {
if (!isDeclarationFile(sourceFile)) {
if (!sourceFile.isDeclarationFile) {
const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
@@ -1849,13 +1874,13 @@ namespace ts {
const languageVersion = options.target || ScriptTarget.ES3;
const outFile = options.outFile || options.out;
const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !f.isDeclarationFile ? f : undefined);
if (options.isolatedModules) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) {
createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
}
const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !f.isDeclarationFile ? f : undefined);
if (firstNonExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
+7 -6
View File
@@ -712,11 +712,11 @@ namespace ts {
return accumulator;
}
export function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) {
export function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined {
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
}
export function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T) {
export function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined {
return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
}
@@ -746,10 +746,11 @@ namespace ts {
}
/** Optionally, get the shebang */
export function getShebang(text: string): string {
return shebangTriviaRegex.test(text)
? shebangTriviaRegex.exec(text)[0]
: undefined;
export function getShebang(text: string): string | undefined {
const match = shebangTriviaRegex.exec(text);
if (match) {
return match[0];
}
}
export function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean {
+1 -1
View File
@@ -166,7 +166,7 @@ namespace ts {
};
function transformRoot(node: T) {
return node && (!isSourceFile(node) || !isDeclarationFile(node)) ? transformation(node) : node;
return node && (!isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
}
/**
+1 -1
View File
@@ -295,7 +295,7 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
+1 -1
View File
@@ -9,7 +9,7 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
+1 -1
View File
@@ -47,7 +47,7 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
+3 -3
View File
@@ -33,7 +33,7 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
@@ -929,8 +929,8 @@ namespace ts {
text: `
var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
var i, p;
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : v; }; }
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; }
};
`
};
+1 -2
View File
@@ -293,8 +293,7 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)
|| (node.transformFlags & TransformFlags.ContainsGenerator) === 0) {
if (node.isDeclarationFile || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) {
return node;
}
+1 -1
View File
@@ -15,7 +15,7 @@ namespace ts {
* @param node A SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
+1 -1
View File
@@ -16,7 +16,7 @@ namespace ts {
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
+1 -1
View File
@@ -55,7 +55,7 @@ namespace ts {
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node) || !(isExternalModule(node) || compilerOptions.isolatedModules)) {
if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules)) {
return node;
}
+1 -3
View File
@@ -50,9 +50,7 @@ namespace ts {
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)
|| !(isExternalModule(node)
|| compilerOptions.isolatedModules)) {
if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules)) {
return node;
}
+23 -15
View File
@@ -76,7 +76,7 @@ namespace ts {
* @param node A SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)) {
if (node.isDeclarationFile) {
return node;
}
@@ -345,6 +345,9 @@ namespace ts {
case SyntaxKind.PropertyDeclaration:
// TypeScript property declarations are elided.
case SyntaxKind.NamespaceExportDeclaration:
// TypeScript namespace export declarations are elided.
return undefined;
case SyntaxKind.Constructor:
@@ -2494,22 +2497,27 @@ namespace ts {
// we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
// old emitter always generate 'expression' part of the name as-is.
const name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
const valueExpression = transformEnumMemberDeclarationValue(member);
const innerAssignment = createAssignment(
createElementAccess(
currentNamespaceContainerName,
name
),
valueExpression
);
const outerAssignment = valueExpression.kind === SyntaxKind.StringLiteral ?
innerAssignment :
createAssignment(
createElementAccess(
currentNamespaceContainerName,
innerAssignment
),
name
);
return setTextRange(
createStatement(
setTextRange(
createAssignment(
createElementAccess(
currentNamespaceContainerName,
createAssignment(
createElementAccess(
currentNamespaceContainerName,
name
),
transformEnumMemberDeclarationValue(member)
)
),
name
),
outerAssignment,
member
)
),
@@ -3349,7 +3357,7 @@ namespace ts {
return node;
}
function tryGetConstEnumValue(node: Node): number {
function tryGetConstEnumValue(node: Node): string | number {
if (compilerOptions.isolatedModules) {
return undefined;
}
+93 -60
View File
@@ -577,10 +577,11 @@ namespace ts {
* If the identifier begins with two underscores, this will begin with three.
*/
text: string;
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace
/*@internal*/ typeArguments?: NodeArray<TypeNode>; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics.
}
// Transient identifier node (marked by id === -1)
@@ -891,6 +892,8 @@ namespace ts {
kind: SyntaxKind.ConstructorType;
}
export type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments | JSDocTypeReference;
export interface TypeReferenceNode extends TypeNode {
kind: SyntaxKind.TypeReference;
typeName: EntityName;
@@ -2429,6 +2432,8 @@ namespace ts {
/* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean;
// For testing purposes only.
/* @internal */ structureIsReused?: StructureIsReused;
/* @internal */ getSourceFileFromReference(referencingFile: SourceFile, ref: FileReference): SourceFile | undefined;
}
/* @internal */
@@ -2508,10 +2513,10 @@ namespace ts {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
getPropertyOfType(type: Type, propertyName: string): Symbol;
getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo;
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined;
getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
getIndexTypeOfType(type: Type, kind: IndexKind): Type;
getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined;
getBaseTypes(type: InterfaceType): BaseType[];
getBaseTypeOfLiteralType(type: Type): Type;
getWidenedType(type: Type): Type;
@@ -2532,11 +2537,11 @@ namespace ts {
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol;
getSymbolAtLocation(node: Node): Symbol | undefined;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;
@@ -2547,15 +2552,15 @@ namespace ts {
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): Symbol[];
getContextualType(node: Expression): Type | undefined;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isUnknownSymbol(symbol: Symbol): boolean;
/* @internal */ getMergedSymbol(symbol: Symbol): Symbol;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
/** Follow all aliases to get the original symbol. */
getAliasedSymbol(symbol: Symbol): Symbol;
@@ -2565,7 +2570,7 @@ namespace ts {
/** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */
/* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[];
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type;
getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined;
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
@@ -2573,10 +2578,10 @@ namespace ts {
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string;
/* @internal */ getBaseConstraintOfType(type: Type): Type;
getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
/* @internal */ getBaseConstraintOfType(type: Type): Type | undefined;
/* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol;
/* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined;
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
@@ -2591,24 +2596,39 @@ namespace ts {
/**
* For a union, will include a property if it's defined in *any* of the member types.
* So for `{ a } | { b }`, this will include both `a` and `b`.
* Does not include properties of primitive types.
*/
/* @internal */ getAllPossiblePropertiesOfType(type: Type): Symbol[];
}
export enum NodeBuilderFlags {
None = 0,
allowThisInObjectLiteral = 1 << 0,
allowQualifedNameInPlaceOfIdentifier = 1 << 1,
allowTypeParameterInQualifiedName = 1 << 2,
allowAnonymousIdentifier = 1 << 3,
allowEmptyUnionOrIntersection = 1 << 4,
allowEmptyTuple = 1 << 5
// Options
NoTruncation = 1 << 0, // Don't truncate result
WriteArrayAsGenericType = 1 << 1, // Write Array<T> instead T[]
WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature
UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type.
WriteTypeParametersInQualifiedName = 1 << 9,
// Error handling
AllowThisInObjectLiteral = 1 << 10,
AllowQualifedNameInPlaceOfIdentifier = 1 << 11,
AllowAnonymousIdentifier = 1 << 13,
AllowEmptyUnionOrIntersection = 1 << 14,
AllowEmptyTuple = 1 << 15,
IgnoreErrors = AllowThisInObjectLiteral | AllowQualifedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple,
// State
InObjectTypeLiteral = 1 << 20,
InTypeAlias = 1 << 23, // Writing type in type alias declaration
}
export interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void;
buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void;
buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void;
buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@@ -2638,24 +2658,25 @@ namespace ts {
// with import statements it previously saw (but chose not to emit).
trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
reportInaccessibleThisError(): void;
reportIllegalExtends(): void;
reportPrivateInBaseOfClassExpression(propertyName: string): void;
}
export const enum TypeFormatFlags {
None = 0x00000000,
WriteArrayAsGenericType = 0x00000001, // Write Array<T> instead T[]
UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal
NoTruncation = 0x00000004, // Don't truncate typeToString result
WriteArrowStyleSignature = 0x00000008, // Write arrow style signature
WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc)
WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature
InElementType = 0x00000040, // Writing an array or union element type
UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
InTypeAlias = 0x00000200, // Writing type in type alias declaration
UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type.
AddUndefined = 0x00001000, // Add undefined to types of initialized, non-optional parameters
None = 0,
WriteArrayAsGenericType = 1 << 0, // Write Array<T> instead T[]
UseTypeOfFunction = 1 << 2, // Write typeof instead of function type literal
NoTruncation = 1 << 3, // Don't truncate typeToString result
WriteArrowStyleSignature = 1 << 4, // Write arrow style signature
WriteOwnNameForAnyLike = 1 << 5, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc)
WriteTypeArgumentsOfSignature = 1 << 6, // Write the type arguments instead of type parameters of the signature
InElementType = 1 << 7, // Writing an array or union element type
UseFullyQualifiedType = 1 << 8, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 1 << 9, // Writing first type argument of the instantiated type
InTypeAlias = 1 << 10, // Writing type in type alias declaration
UseTypeAliasValue = 1 << 11, // Serialize the type instead of using type-alias. This is needed when we emit declaration file.
SuppressAnyReturnType = 1 << 12, // If the return type is any-like, don't offer a return type.
AddUndefined = 1 << 13, // Add undefined to types of initialized, non-optional parameters
WriteClassExpressionAsTypeLiteral = 1 << 14, // Write a type literal instead of (Anonymous class)
}
export const enum SymbolFormatFlags {
@@ -2758,7 +2779,7 @@ namespace ts {
getNodeCheckFlags(node: Node): NodeCheckFlags;
isDeclarationVisible(node: Declaration): boolean;
collectLinkedAliases(node: Identifier): Node[];
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined;
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
@@ -2766,7 +2787,7 @@ namespace ts {
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number;
getReferencedValueDeclaration(reference: Identifier): Declaration;
getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
@@ -2904,6 +2925,13 @@ namespace ts {
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // True if module exports some value (not just types)
enumKind?: EnumKind; // Enum declaration classification
}
/* @internal */
export const enum EnumKind {
Numeric, // Numeric enum (each member has a TypeFlags.Enum type)
Literal // Literal enum (each member has a TypeFlags.EnumLiteral type)
}
/* @internal */
@@ -2976,7 +3004,7 @@ namespace ts {
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate
enumMemberValue?: number; // Constant value of enum member
enumMemberValue?: string | number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
@@ -2996,7 +3024,7 @@ namespace ts {
StringLiteral = 1 << 5,
NumberLiteral = 1 << 6,
BooleanLiteral = 1 << 7,
EnumLiteral = 1 << 8,
EnumLiteral = 1 << 8, // Always combined with StringLiteral, NumberLiteral, or Union
ESSymbol = 1 << 9, // Type of symbol primitive introduced in ES6
Void = 1 << 10,
Undefined = 1 << 11,
@@ -3022,7 +3050,7 @@ namespace ts {
/* @internal */
Nullable = Undefined | Null,
Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral,
Literal = StringLiteral | NumberLiteral | BooleanLiteral,
StringOrNumberLiteral = StringLiteral | NumberLiteral,
/* @internal */
DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null,
@@ -3030,9 +3058,9 @@ namespace ts {
/* @internal */
Intrinsic = Any | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive,
/* @internal */
Primitive = String | Number | Boolean | Enum | ESSymbol | Void | Undefined | Null | Literal,
Primitive = String | Number | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal,
StringLike = String | StringLiteral | Index,
NumberLike = Number | NumberLiteral | Enum | EnumLiteral,
NumberLike = Number | NumberLiteral | Enum,
BooleanLike = Boolean | BooleanLiteral,
EnumLike = Enum | EnumLiteral,
UnionOrIntersection = Union | Intersection,
@@ -3071,19 +3099,21 @@ namespace ts {
// String literal types (TypeFlags.StringLiteral)
// Numeric literal types (TypeFlags.NumberLiteral)
export interface LiteralType extends Type {
text: string; // Text of literal
value: string | number; // Value of literal
freshType?: LiteralType; // Fresh version of type
regularType?: LiteralType; // Regular version of type
}
// Enum types (TypeFlags.Enum)
export interface EnumType extends Type {
memberTypes: EnumLiteralType[];
export interface StringLiteralType extends LiteralType {
value: string;
}
// Enum types (TypeFlags.EnumLiteral)
export interface EnumLiteralType extends LiteralType {
baseType: EnumType & UnionType; // Base enum type
export interface NumberLiteralType extends LiteralType {
value: number;
}
// Enum types (TypeFlags.Enum)
export interface EnumType extends Type {
}
export const enum ObjectFlags {
@@ -3140,7 +3170,7 @@ namespace ts {
*/
export interface TypeReference extends ObjectType {
target: GenericType; // Type reference target
typeArguments: Type[]; // Type reference type arguments (undefined if none)
typeArguments?: Type[]; // Type reference type arguments (undefined if none)
}
// Generic class and interface types
@@ -3270,7 +3300,7 @@ namespace ts {
export interface Signature {
declaration: SignatureDeclaration; // Originating declaration
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
typeParameters?: TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: Symbol[]; // Parameters
/* @internal */
thisParameter?: Symbol; // symbol of this-type parameter
@@ -3393,7 +3423,7 @@ namespace ts {
export enum DiagnosticCategory {
Warning,
Error,
Message,
Message
}
export enum ModuleResolutionKind {
@@ -3533,7 +3563,7 @@ namespace ts {
export const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
LineFeed = 1
}
export interface LineAndCharacter {
@@ -3955,7 +3985,7 @@ namespace ts {
commentRange?: TextRange; // The text range to use when emitting leading or trailing comments
sourceMapRange?: TextRange; // The text range to use when emitting leading or trailing source mappings
tokenSourceMapRanges?: TextRange[]; // The text range to use when emitting source mappings for tokens
constantValue?: number; // The constant value of an expression
constantValue?: string | number; // The constant value of an expression
externalHelpersModuleName?: Identifier; // The local name for an imported helpers module
helpers?: EmitHelper[]; // Emit helpers for the node
}
@@ -3988,6 +4018,7 @@ namespace ts {
NoHoisting = 1 << 21, // Do not hoist this declaration in --module system
HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable.
NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions.
}
export interface EmitHelper {
@@ -4200,7 +4231,7 @@ namespace ts {
* Prints a bundle of source files as-is, without any emit transformations.
*/
printBundle(bundle: Bundle): string;
/*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile, writer: EmitTextWriter): void;
/*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
/*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter): void;
/*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter): void;
}
@@ -4254,6 +4285,8 @@ namespace ts {
/*@internal*/ onSetSourceFile?: (node: SourceFile) => void;
/*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray<any>) => void;
/*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray<any>) => void;
/*@internal*/ onBeforeEmitToken?: (node: Node) => void;
/*@internal*/ onAfterEmitToken?: (node: Node) => void;
}
export interface PrinterOptions {
+98 -70
View File
@@ -11,12 +11,12 @@ namespace ts {
isTypeReferenceDirective?: boolean;
}
export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration {
export function getDeclarationOfKind<T extends Declaration>(symbol: Symbol, kind: T["kind"]): T {
const declarations = symbol.declarations;
if (declarations) {
for (const declaration of declarations) {
if (declaration.kind === kind) {
return declaration;
return declaration as T;
}
}
}
@@ -68,7 +68,7 @@ namespace ts {
clear: () => str = "",
trackSymbol: noop,
reportInaccessibleThisError: noop,
reportIllegalExtends: noop
reportPrivateInBaseOfClassExpression: noop,
};
}
@@ -328,19 +328,21 @@ namespace ts {
return getSourceTextOfNodeFromSourceFile(sourceFile, node);
}
const escapeText = getEmitFlags(node) & EmitFlags.NoAsciiEscaping ? escapeString : escapeNonAsciiString;
// If we can't reach the original source text, use the canonical form if it's a number,
// or an escaped quoted form of the original text if it's string-like.
// or a (possibly escaped) quoted form of the original text if it's string-like.
switch (node.kind) {
case SyntaxKind.StringLiteral:
return getQuotedEscapedLiteralText('"', node.text, '"');
return '"' + escapeText(node.text) + '"';
case SyntaxKind.NoSubstitutionTemplateLiteral:
return getQuotedEscapedLiteralText("`", node.text, "`");
return "`" + escapeText(node.text) + "`";
case SyntaxKind.TemplateHead:
return getQuotedEscapedLiteralText("`", node.text, "${");
return "`" + escapeText(node.text) + "${";
case SyntaxKind.TemplateMiddle:
return getQuotedEscapedLiteralText("}", node.text, "${");
return "}" + escapeText(node.text) + "${";
case SyntaxKind.TemplateTail:
return getQuotedEscapedLiteralText("}", node.text, "`");
return "}" + escapeText(node.text) + "`";
case SyntaxKind.NumericLiteral:
return node.text;
}
@@ -348,8 +350,8 @@ namespace ts {
Debug.fail(`Literal kind '${node.kind}' not accounted for.`);
}
function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) {
return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote;
export function getTextOfConstantValue(value: string | number) {
return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
}
// Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__'
@@ -465,7 +467,7 @@ namespace ts {
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}
export function getNameFromIndexInfo(info: IndexInfo) {
export function getNameFromIndexInfo(info: IndexInfo): string | undefined {
return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
}
@@ -589,10 +591,6 @@ namespace ts {
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
export function isDeclarationFile(file: SourceFile): boolean {
return file.isDeclarationFile;
}
export function isConstEnumDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.EnumDeclaration && isConst(node);
}
@@ -881,6 +879,16 @@ namespace ts {
return false;
}
export function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode {
switch (node.kind) {
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return true;
}
return false;
}
export function introducesArgumentsExoticObject(node: Node) {
switch (node.kind) {
case SyntaxKind.MethodDeclaration:
@@ -1594,7 +1602,7 @@ namespace ts {
// Pull parameter comments from declaring function as well
if (node.kind === SyntaxKind.Parameter) {
cache = concatenate(cache, getJSDocParameterTags(node));
cache = concatenate(cache, getJSDocParameterTags(node as ParameterDeclaration));
}
if (isVariableLike(node) && node.initializer) {
@@ -1605,11 +1613,8 @@ namespace ts {
}
}
export function getJSDocParameterTags(param: Node): JSDocParameterTag[] {
if (!isParameter(param)) {
return undefined;
}
const func = param.parent as FunctionLikeDeclaration;
export function getJSDocParameterTags(param: ParameterDeclaration): JSDocParameterTag[] {
const func = param.parent;
const tags = getJSDocTags(func, SyntaxKind.JSDocParameterTag) as JSDocParameterTag[];
if (!param.name) {
// this is an anonymous jsdoc param from a `function(type1, type2): type3` specification
@@ -1630,10 +1635,22 @@ namespace ts {
}
}
/** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
export function getParameterFromJSDoc(node: JSDocParameterTag): ParameterDeclaration | undefined {
const name = node.parameterName.text;
const grandParent = node.parent!.parent!;
Debug.assert(node.parent!.kind === SyntaxKind.JSDocComment);
if (!isFunctionLike(grandParent)) {
return undefined;
}
return find(grandParent.parameters, p =>
p.name.kind === SyntaxKind.Identifier && p.name.text === name);
}
export function getJSDocType(node: Node): JSDocType {
let tag: JSDocTypeTag | JSDocParameterTag = getFirstJSDocTag(node, SyntaxKind.JSDocTypeTag) as JSDocTypeTag;
if (!tag && node.kind === SyntaxKind.Parameter) {
const paramTags = getJSDocParameterTags(node);
const paramTags = getJSDocParameterTags(node as ParameterDeclaration);
if (paramTags) {
tag = find(paramTags, tag => !!tag.typeExpression);
}
@@ -1771,33 +1788,20 @@ namespace ts {
}
}
export function getNameOfDeclaration(declaration: Declaration): DeclarationName {
if (!declaration) {
return undefined;
}
if (declaration.kind === SyntaxKind.BinaryExpression) {
const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression);
const lhs = (declaration as BinaryExpression).left;
switch (kind) {
case SpecialPropertyAssignmentKind.None:
case SpecialPropertyAssignmentKind.ModuleExports:
return undefined;
case SpecialPropertyAssignmentKind.ExportsProperty:
if (lhs.kind === SyntaxKind.Identifier) {
return (lhs as PropertyAccessExpression).name;
}
else {
return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name;
}
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
return (lhs as PropertyAccessExpression).name;
case SpecialPropertyAssignmentKind.PrototypeProperty:
return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name;
}
}
else {
return (declaration as NamedDeclaration).name;
/* @internal */
// See GH#16030
export function isAnyDeclarationName(name: Node): boolean {
switch (name.kind) {
case SyntaxKind.Identifier:
case SyntaxKind.StringLiteral:
case SyntaxKind.NumericLiteral:
if (isDeclaration(name.parent)) {
return name.parent.name === name;
}
const binExp = name.parent.parent;
return isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && getNameOfDeclaration(binExp) === name;
default:
return false;
}
}
@@ -1913,21 +1917,19 @@ namespace ts {
const isNoDefaultLibRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/gim;
if (simpleReferenceRegEx.test(comment)) {
if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
return { isNoDefaultLib: true };
}
else {
const refMatchResult = fullTripleSlashReferencePathRegEx.exec(comment);
const refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment);
if (refMatchResult || refLibResult) {
const start = commentRange.pos;
const end = commentRange.end;
const match = refMatchResult || refLibResult;
if (match) {
const pos = commentRange.pos + match[1].length + match[2].length;
return {
fileReference: {
pos: start,
end: end,
fileName: (refMatchResult || refLibResult)[3]
pos,
end: pos + match[3].length,
fileName: match[3]
},
isNoDefaultLib: false,
isTypeReferenceDirective: !!refLibResult
@@ -2473,7 +2475,8 @@ namespace ts {
}
const nonAsciiCharacters = /[^\u0000-\u007F]/g;
export function escapeNonAsciiCharacters(s: string): string {
export function escapeNonAsciiString(s: string): string {
s = escapeString(s);
// Replace non-ASCII characters with '\uNNNN' escapes if any exist.
// Otherwise just return the original string.
return nonAsciiCharacters.test(s) ?
@@ -2577,7 +2580,7 @@ namespace ts {
export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string {
const file = resolver.getExternalModuleFileFromDeclaration(declaration);
if (!file || isDeclarationFile(file)) {
if (!file || file.isDeclarationFile) {
return undefined;
}
return getResolvedExternalModuleName(host, file);
@@ -2650,7 +2653,7 @@ namespace ts {
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) {
return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !isDeclarationFile(sourceFile) && !isSourceFileFromExternalLibrary(sourceFile);
return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
}
/**
@@ -3176,11 +3179,11 @@ namespace ts {
}
export function getLocalSymbolForExportDefault(symbol: Symbol) {
return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined;
return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
}
function isExportDefaultSymbol(symbol: Symbol): boolean {
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, ModifierFlags.Default);
return symbol && length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], ModifierFlags.Default);
}
/** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
@@ -3266,13 +3269,13 @@ namespace ts {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export function getNewLineCharacter(options: CompilerOptions | PrinterOptions): string {
if (options.newLine === NewLineKind.CarriageReturnLineFeed) {
return carriageReturnLineFeed;
switch (options.newLine) {
case NewLineKind.CarriageReturnLineFeed:
return carriageReturnLineFeed;
case NewLineKind.LineFeed:
return lineFeed;
}
else if (options.newLine === NewLineKind.LineFeed) {
return lineFeed;
}
else if (sys) {
if (sys) {
return sys.newLine;
}
return carriageReturnLineFeed;
@@ -4031,6 +4034,10 @@ namespace ts {
return node.kind === SyntaxKind.ImportEqualsDeclaration;
}
export function isImportDeclaration(node: Node): node is ImportDeclaration {
return node.kind === SyntaxKind.ImportDeclaration;
}
export function isImportClause(node: Node): node is ImportClause {
return node.kind === SyntaxKind.ImportClause;
}
@@ -4739,4 +4746,25 @@ namespace ts {
export function unescapeIdentifier(identifier: string): string {
return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier;
}
export function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined {
if (!declaration) {
return undefined;
}
if (declaration.kind === SyntaxKind.BinaryExpression) {
const expr = declaration as BinaryExpression;
switch (getSpecialPropertyAssignmentKind(expr)) {
case SpecialPropertyAssignmentKind.ExportsProperty:
case SpecialPropertyAssignmentKind.ThisProperty:
case SpecialPropertyAssignmentKind.Property:
case SpecialPropertyAssignmentKind.PrototypeProperty:
return (expr.left as PropertyAccessExpression).name;
default:
return undefined;
}
}
else {
return (declaration as NamedDeclaration).name;
}
}
}
+18 -1
View File
@@ -220,6 +220,10 @@ namespace ts {
switch (kind) {
// Names
case SyntaxKind.Identifier:
return updateIdentifier(<Identifier>node, nodesVisitor((<Identifier>node).typeArguments, visitor, isTypeNode));
case SyntaxKind.QualifiedName:
return updateQualifiedName(<QualifiedName>node,
visitNode((<QualifiedName>node).left, visitor, isEntityName),
@@ -255,6 +259,7 @@ namespace ts {
case SyntaxKind.PropertySignature:
return updatePropertySignature((<PropertySignature>node),
nodesVisitor((<PropertySignature>node).modifiers, visitor, isToken),
visitNode((<PropertySignature>node).name, visitor, isPropertyName),
visitNode((<PropertySignature>node).questionToken, tokenVisitor, isToken),
visitNode((<PropertySignature>node).type, visitor, isTypeNode),
@@ -511,7 +516,8 @@ namespace ts {
case SyntaxKind.BinaryExpression:
return updateBinary(<BinaryExpression>node,
visitNode((<BinaryExpression>node).left, visitor, isExpression),
visitNode((<BinaryExpression>node).right, visitor, isExpression));
visitNode((<BinaryExpression>node).right, visitor, isExpression),
visitNode((<BinaryExpression>node).operatorToken, visitor, isToken));
case SyntaxKind.ConditionalExpression:
return updateConditional(<ConditionalExpression>node,
@@ -695,6 +701,8 @@ namespace ts {
case SyntaxKind.TypeAliasDeclaration:
return updateTypeAliasDeclaration(<TypeAliasDeclaration>node,
nodesVisitor((<TypeAliasDeclaration>node).decorators, visitor, isDecorator),
nodesVisitor((<TypeAliasDeclaration>node).modifiers, visitor, isModifier),
visitNode((<TypeAliasDeclaration>node).name, visitor, isIdentifier),
nodesVisitor((<TypeAliasDeclaration>node).typeParameters, visitor, isTypeParameter),
visitNode((<TypeAliasDeclaration>node).type, visitor, isTypeNode));
@@ -970,6 +978,15 @@ namespace ts {
break;
// Type member
case SyntaxKind.PropertySignature:
result = reduceNodes((<PropertySignature>node).modifiers, cbNodes, result);
result = reduceNode((<PropertySignature>node).name, cbNode, result);
result = reduceNode((<PropertySignature>node).questionToken, cbNode, result);
result = reduceNode((<PropertySignature>node).type, cbNode, result);
result = reduceNode((<PropertySignature>node).initializer, cbNode, result);
break;
case SyntaxKind.PropertyDeclaration:
result = reduceNodes((<PropertyDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<PropertyDeclaration>node).modifiers, cbNodes, result);
+139 -57
View File
@@ -916,7 +916,7 @@ namespace FourSlash {
}
private getNode(): ts.Node {
return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition);
return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition, /*includeJsDocComment*/ false);
}
private goToAndGetNode(range: Range): ts.Node {
@@ -994,17 +994,15 @@ namespace FourSlash {
}
public verifyReferenceGroups(startRanges: Range | Range[], parts: Array<{ definition: string, ranges: Range[] }>): void {
interface ReferenceJson { definition: string; ranges: ts.ReferenceEntry[]; }
type ReferencesJson = ReferenceJson[];
const fullExpected = parts.map<ReferenceJson>(({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) }));
const fullExpected = ts.map(parts, ({ definition, ranges }) => ({ definition, ranges: ranges.map(rangeToReferenceEntry) }));
for (const startRange of toArray(startRanges)) {
this.goToRangeStart(startRange);
const fullActual = ts.map<ts.ReferencedSymbol, ReferenceJson>(this.findReferencesAtCaret(), ({ definition, references }) => ({
const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }) => ({
definition: definition.displayParts.map(d => d.text).join(""),
ranges: references
}));
this.assertObjectsEqual<ReferencesJson>(fullActual, fullExpected);
this.assertObjectsEqual(fullActual, fullExpected);
}
function rangeToReferenceEntry(r: Range): ts.ReferenceEntry {
@@ -1047,6 +1045,10 @@ namespace FourSlash {
this.raiseError(`${msgPrefix}At ${path}: ${msg}`);
};
if ((actual === undefined) !== (expected === undefined)) {
fail(`Expected ${expected}, got ${actual}`);
}
for (const key in actual) if (ts.hasProperty(actual as any, key)) {
const ak = actual[key], ek = expected[key];
if (typeof ak === "object" && typeof ek === "object") {
@@ -1062,6 +1064,14 @@ namespace FourSlash {
}
}
};
if (fullActual === undefined || fullExpected === undefined) {
if (fullActual === fullExpected) {
return;
}
console.log("Expected:", stringify(fullExpected));
console.log("Actual: ", stringify(fullActual));
this.raiseError(msgPrefix);
}
recur(fullActual, fullExpected, "");
}
@@ -2167,7 +2177,7 @@ namespace FourSlash {
}
ts.zipWith(expected, actual, (expectedClassification, actualClassification) => {
const expectedType: string = (<any>ts.ClassificationTypeNames)[expectedClassification.classificationType];
const expectedType = expectedClassification.classificationType;
if (expectedType !== actualClassification.classificationType) {
this.raiseError("verifyClassifications failed - expected classifications type to be " +
expectedType + ", but was " +
@@ -2347,7 +2357,8 @@ namespace FourSlash {
private applyCodeAction(fileName: string, actions: ts.CodeAction[], index?: number): void {
if (index === undefined) {
if (!(actions && actions.length === 1)) {
this.raiseError(`Should find exactly one codefix, but ${actions ? actions.length : "none"} found.`);
const actionText = (actions && actions.length) ? JSON.stringify(actions) : "none";
this.raiseError(`Should find exactly one codefix, but found ${actionText}`);
}
index = 0;
}
@@ -2701,6 +2712,60 @@ namespace FourSlash {
}
}
public verifyApplicableRefactorAvailableAtMarker(negative: boolean, markerName: string) {
const marker = this.getMarkerByName(markerName);
const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, marker.position);
const isAvailable = applicableRefactors && applicableRefactors.length > 0;
if (negative && isAvailable) {
this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected no refactor at marker ${markerName} but found some.`);
}
if (!negative && !isAvailable) {
this.raiseError(`verifyApplicableRefactorAvailableAtMarker failed - expected a refactor at marker ${markerName} but found none.`);
}
}
public verifyApplicableRefactorAvailableForRange(negative: boolean) {
const ranges = this.getRanges();
if (!(ranges && ranges.length === 1)) {
throw new Error("Exactly one refactor range is allowed per test.");
}
const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, { pos: ranges[0].start, end: ranges[0].end });
const isAvailable = applicableRefactors && applicableRefactors.length > 0;
if (negative && isAvailable) {
this.raiseError(`verifyApplicableRefactorAvailableForRange failed - expected no refactor but found some.`);
}
if (!negative && !isAvailable) {
this.raiseError(`verifyApplicableRefactorAvailableForRange failed - expected a refactor but found none.`);
}
}
public verifyFileAfterApplyingRefactorAtMarker(
markerName: string,
expectedContent: string,
refactorNameToApply: string,
formattingOptions?: ts.FormatCodeSettings) {
formattingOptions = formattingOptions || this.formatCodeSettings;
const markerPos = this.getMarkerByName(markerName).position;
const applicableRefactors = this.languageService.getApplicableRefactors(this.activeFile.fileName, markerPos);
const applicableRefactorToApply = ts.find(applicableRefactors, refactor => refactor.name === refactorNameToApply);
if (!applicableRefactorToApply) {
this.raiseError(`The expected refactor: ${refactorNameToApply} is not available at the marker location.`);
}
const codeActions = this.languageService.getRefactorCodeActions(this.activeFile.fileName, formattingOptions, markerPos, refactorNameToApply);
this.applyCodeAction(this.activeFile.fileName, codeActions);
const actualContent = this.getFileContent(this.activeFile.fileName);
if (this.normalizeNewlines(actualContent) !== this.normalizeNewlines(expectedContent)) {
this.raiseError(`verifyFileAfterApplyingRefactors failed: expected:\n${expectedContent}\nactual:\n${actualContent}`);
}
}
public printAvailableCodeFixes() {
const codeFixes = this.getCodeFixActions(this.activeFile.fileName);
Harness.IO.log(stringify(codeFixes));
@@ -3514,6 +3579,14 @@ namespace FourSlashInterface {
public codeFixAvailable() {
this.state.verifyCodeFixAvailable(this.negative);
}
public applicableRefactorAvailableAtMarker(markerName: string) {
this.state.verifyApplicableRefactorAvailableAtMarker(this.negative, markerName);
}
public applicableRefactorAvailableForRange() {
this.state.verifyApplicableRefactorAvailableForRange(this.negative);
}
}
export class Verify extends VerifyNegatable {
@@ -3728,6 +3801,10 @@ namespace FourSlashInterface {
this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index);
}
public fileAfterApplyingRefactorAtMarker(markerName: string, expectedContent: string, refactorNameToApply: string, formattingOptions?: ts.FormatCodeSettings): void {
this.state.verifyFileAfterApplyingRefactorAtMarker(markerName, expectedContent, refactorNameToApply, formattingOptions);
}
public importFixAtPosition(expectedTextArray: string[], errorCode?: number): void {
this.state.verifyImportFixAtPosition(expectedTextArray, errorCode);
}
@@ -3802,7 +3879,7 @@ namespace FourSlashInterface {
/**
* This method *requires* an ordered stream of classifications for a file, and spans are highly recommended.
*/
public semanticClassificationsAre(...classifications: { classificationType: string; text: string; textSpan?: FourSlash.TextSpan }[]) {
public semanticClassificationsAre(...classifications: Classification[]) {
this.state.verifySemanticClassifications(classifications);
}
@@ -3997,102 +4074,107 @@ namespace FourSlashInterface {
}
}
interface Classification {
classificationType: ts.ClassificationTypeNames;
text: string;
textSpan?: FourSlash.TextSpan;
}
export namespace Classification {
export function comment(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("comment", text, position);
export function comment(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.comment, text, position);
}
export function identifier(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("identifier", text, position);
export function identifier(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.identifier, text, position);
}
export function keyword(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("keyword", text, position);
export function keyword(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.keyword, text, position);
}
export function numericLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("numericLiteral", text, position);
export function numericLiteral(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.numericLiteral, text, position);
}
export function operator(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("operator", text, position);
export function operator(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.operator, text, position);
}
export function stringLiteral(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("stringLiteral", text, position);
export function stringLiteral(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.stringLiteral, text, position);
}
export function whiteSpace(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("whiteSpace", text, position);
export function whiteSpace(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.whiteSpace, text, position);
}
export function text(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("text", text, position);
export function text(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.text, text, position);
}
export function punctuation(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("punctuation", text, position);
export function punctuation(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.punctuation, text, position);
}
export function docCommentTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("docCommentTagName", text, position);
export function docCommentTagName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.docCommentTagName, text, position);
}
export function className(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("className", text, position);
export function className(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.className, text, position);
}
export function enumName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("enumName", text, position);
export function enumName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.enumName, text, position);
}
export function interfaceName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("interfaceName", text, position);
export function interfaceName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.interfaceName, text, position);
}
export function moduleName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("moduleName", text, position);
export function moduleName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.moduleName, text, position);
}
export function typeParameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("typeParameterName", text, position);
export function typeParameterName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.typeParameterName, text, position);
}
export function parameterName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("parameterName", text, position);
export function parameterName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.parameterName, text, position);
}
export function typeAliasName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("typeAliasName", text, position);
export function typeAliasName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.typeAliasName, text, position);
}
export function jsxOpenTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("jsxOpenTagName", text, position);
export function jsxOpenTagName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.jsxOpenTagName, text, position);
}
export function jsxCloseTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("jsxCloseTagName", text, position);
export function jsxCloseTagName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.jsxCloseTagName, text, position);
}
export function jsxSelfClosingTagName(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("jsxSelfClosingTagName", text, position);
export function jsxSelfClosingTagName(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.jsxSelfClosingTagName, text, position);
}
export function jsxAttribute(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("jsxAttribute", text, position);
export function jsxAttribute(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.jsxAttribute, text, position);
}
export function jsxText(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("jsxText", text, position);
export function jsxText(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.jsxText, text, position);
}
export function jsxAttributeStringLiteralValue(text: string, position?: number): { classificationType: string; text: string; textSpan?: FourSlash.TextSpan } {
return getClassification("jsxAttributeStringLiteralValue", text, position);
export function jsxAttributeStringLiteralValue(text: string, position?: number): Classification {
return getClassification(ts.ClassificationTypeNames.jsxAttributeStringLiteralValue, text, position);
}
function getClassification(type: string, text: string, position?: number) {
function getClassification(classificationType: ts.ClassificationTypeNames, text: string, position?: number): Classification {
return {
classificationType: type,
classificationType,
text: text,
textSpan: position === undefined ? undefined : { start: position, end: position + text.length }
};
+3 -3
View File
@@ -172,7 +172,7 @@ namespace Utils {
assert.isFalse(child.pos < currentPos, "child.pos < currentPos");
currentPos = child.end;
},
(array: ts.NodeArray<ts.Node>) => {
array => {
assert.isFalse(array.pos < node.pos, "array.pos < node.pos");
assert.isFalse(array.end > node.end, "array.end > node.end");
assert.isFalse(array.pos < currentPos, "array.pos < currentPos");
@@ -383,7 +383,7 @@ namespace Utils {
assertStructuralEquals(child1, child2);
},
(array1: ts.NodeArray<ts.Node>) => {
array1 => {
const childName = findChildName(node1, array1);
const array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];
@@ -1990,5 +1990,5 @@ namespace Harness {
return { unitName: libFile, content: io.readFile(libFile) };
}
if (Error) (<any>Error).stackTraceLimit = 1;
if (Error) (<any>Error).stackTraceLimit = 100;
}
+9
View File
@@ -489,6 +489,15 @@ namespace Harness.LanguageService {
getCodeFixesAtPosition(): ts.CodeAction[] {
throw new Error("Not supported on the shim.");
}
getCodeFixDiagnostics(): ts.Diagnostic[] {
throw new Error("Not supported on the shim.");
}
getRefactorCodeActions(): ts.CodeAction[] {
throw new Error("Not supported on the shim.");
}
getApplicableRefactors(): ts.ApplicableRefactorInfo[] {
throw new Error("Not supported on the shim.");
}
getEmitOutput(fileName: string): ts.EmitOutput {
return unwrapJSONCallResult(this.shim.getEmitOutput(fileName));
}
+1 -1
View File
@@ -373,7 +373,7 @@ class ProjectRunner extends RunnerBase {
const compilerOptions = compilerResult.program.getCompilerOptions();
ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => {
if (ts.isDeclarationFile(sourceFile)) {
if (sourceFile.isDeclarationFile) {
allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text });
}
else if (!(compilerOptions.outFile || compilerOptions.out)) {
+3 -3
View File
@@ -60,7 +60,7 @@ namespace ts {
assertParseResult(["--lib", "es5,invalidOption", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -263,7 +263,7 @@ namespace ts {
assertParseResult(["--lib", "es5,", "es7", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -283,7 +283,7 @@ namespace ts {
assertParseResult(["--lib", "es5, ", "es7", "0.ts"],
{
errors: [{
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -266,7 +266,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -297,7 +297,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -328,7 +328,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -359,7 +359,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'esnext.asynciterable'.",
messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'esnext.asynciterable'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
+35
View File
@@ -98,8 +98,43 @@ namespace ts {
)
])
);
// https://github.com/Microsoft/TypeScript/issues/15971
const classWithOptionalMethodAndProperty = createClassDeclaration(
undefined,
/* modifiers */ createNodeArray([createToken(SyntaxKind.DeclareKeyword)]),
/* name */ createIdentifier("X"),
undefined,
undefined,
createNodeArray([
createMethod(
undefined,
undefined,
undefined,
/* name */ createIdentifier("method"),
/* questionToken */ createToken(SyntaxKind.QuestionToken),
undefined,
undefined,
/* type */ createKeywordTypeNode(SyntaxKind.VoidKeyword),
undefined
),
createProperty(
undefined,
undefined,
/* name */ createIdentifier("property"),
/* questionToken */ createToken(SyntaxKind.QuestionToken),
/* type */ createKeywordTypeNode(SyntaxKind.StringKeyword),
undefined
),
])
);
// tslint:enable boolean-trivia
printsCorrectly("class", {}, printer => printer.printNode(EmitHint.Unspecified, syntheticNode, sourceFile));
printsCorrectly("namespaceExportDeclaration", {}, printer => printer.printNode(EmitHint.Unspecified, createNamespaceExportDeclaration("B"), sourceFile));
printsCorrectly("classWithOptionalMethodAndProperty", {}, printer => printer.printNode(EmitHint.Unspecified, classWithOptionalMethodAndProperty, sourceFile));
});
});
}
@@ -37,8 +37,8 @@ describe("PreProcessFile:", function () {
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 37 }, { fileName: "refFile2.ts", pos: 38, end: 73 },
{ fileName: "refFile3.ts", pos: 74, end: 109 }, { fileName: "..\\refFile4d.ts", pos: 110, end: 150 }],
referencedFiles: [{ fileName: "refFile1.ts", pos: 22, end: 33 }, { fileName: "refFile2.ts", pos: 59, end: 70 },
{ fileName: "refFile3.ts", pos: 94, end: 105 }, { fileName: "..\\refFile4d.ts", pos: 131, end: 146 }],
importedFiles: <ts.FileReference[]>[],
typeReferenceDirectives: [],
ambientExternalModules: undefined,
@@ -104,7 +104,7 @@ describe("PreProcessFile:", function () {
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }, { fileName: "refFile2.ts", pos: 36, end: 71 }],
referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }, { fileName: "refFile2.ts", pos: 57, end: 68 }],
typeReferenceDirectives: [],
importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }],
ambientExternalModules: undefined,
@@ -117,7 +117,7 @@ describe("PreProcessFile:", function () {
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }],
referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }],
typeReferenceDirectives: [],
importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }],
ambientExternalModules: undefined,
@@ -442,12 +442,12 @@ describe("PreProcessFile:", function () {
/*detectJavaScriptImports*/ false,
{
referencedFiles: [
{ "pos": 13, "end": 38, "fileName": "a" },
{ "pos": 91, "end": 117, "fileName": "a2" }
{ "pos": 34, "end": 35, "fileName": "a" },
{ "pos": 112, "end": 114, "fileName": "a2" }
],
typeReferenceDirectives: [
{ "pos": 51, "end": 78, "fileName": "a1" },
{ "pos": 130, "end": 157, "fileName": "a3" }
{ "pos": 73, "end": 75, "fileName": "a1" },
{ "pos": 152, "end": 154, "fileName": "a3" }
],
importedFiles: [],
ambientExternalModules: undefined,
+79 -10
View File
@@ -134,7 +134,7 @@ namespace ts.server {
type: "request",
arguments: {
formatOptions: {
indentStyle: "Block"
indentStyle: protocol.IndentStyle.Block,
}
}
};
@@ -149,11 +149,11 @@ namespace ts.server {
type: "request",
arguments: {
options: {
module: "System",
target: "ES5",
jsx: "React",
newLine: "Lf",
moduleResolution: "Node"
module: protocol.ModuleKind.System,
target: protocol.ScriptTarget.ES5,
jsx: protocol.JsxEmit.React,
newLine: protocol.NewLineKind.Lf,
moduleResolution: protocol.ModuleResolutionKind.Node,
}
}
};
@@ -172,12 +172,81 @@ namespace ts.server {
});
describe("onMessage", () => {
const allCommandNames: CommandNames[] = [
CommandNames.Brace,
CommandNames.BraceFull,
CommandNames.BraceCompletion,
CommandNames.Change,
CommandNames.Close,
CommandNames.Completions,
CommandNames.CompletionsFull,
CommandNames.CompletionDetails,
CommandNames.CompileOnSaveAffectedFileList,
CommandNames.Configure,
CommandNames.Definition,
CommandNames.DefinitionFull,
CommandNames.Implementation,
CommandNames.ImplementationFull,
CommandNames.Exit,
CommandNames.Format,
CommandNames.Formatonkey,
CommandNames.FormatFull,
CommandNames.FormatonkeyFull,
CommandNames.FormatRangeFull,
CommandNames.Geterr,
CommandNames.GeterrForProject,
CommandNames.SemanticDiagnosticsSync,
CommandNames.SyntacticDiagnosticsSync,
CommandNames.NavBar,
CommandNames.NavBarFull,
CommandNames.Navto,
CommandNames.NavtoFull,
CommandNames.NavTree,
CommandNames.NavTreeFull,
CommandNames.Occurrences,
CommandNames.DocumentHighlights,
CommandNames.DocumentHighlightsFull,
CommandNames.Open,
CommandNames.Quickinfo,
CommandNames.QuickinfoFull,
CommandNames.References,
CommandNames.ReferencesFull,
CommandNames.Reload,
CommandNames.Rename,
CommandNames.RenameInfoFull,
CommandNames.RenameLocationsFull,
CommandNames.Saveto,
CommandNames.SignatureHelp,
CommandNames.SignatureHelpFull,
CommandNames.TypeDefinition,
CommandNames.ProjectInfo,
CommandNames.ReloadProjects,
CommandNames.Unknown,
CommandNames.OpenExternalProject,
CommandNames.CloseExternalProject,
CommandNames.SynchronizeProjectList,
CommandNames.ApplyChangedToOpenFiles,
CommandNames.EncodedSemanticClassificationsFull,
CommandNames.Cleanup,
CommandNames.OutliningSpans,
CommandNames.TodoComments,
CommandNames.Indentation,
CommandNames.DocCommentTemplate,
CommandNames.CompilerOptionsDiagnosticsFull,
CommandNames.NameOrDottedNameSpan,
CommandNames.BreakpointStatement,
CommandNames.CompilerOptionsForInferredProjects,
CommandNames.GetCodeFixes,
CommandNames.GetCodeFixesFull,
CommandNames.GetSupportedCodeFixes,
CommandNames.GetApplicableRefactors,
CommandNames.GetRefactorCodeActions,
CommandNames.GetRefactorCodeActionsFull,
];
it("should not throw when commands are executed with invalid arguments", () => {
let i = 0;
for (const name in CommandNames) {
if (!Object.prototype.hasOwnProperty.call(CommandNames, name)) {
continue;
}
for (const name of allCommandNames) {
const req: protocol.Request = {
command: name,
seq: i,
@@ -337,6 +337,7 @@ namespace ts.projectSystem {
this.map[timeoutId] = cb.bind(/*this*/ undefined, ...args);
return timeoutId;
}
unregister(id: any) {
if (typeof id === "number") {
delete this.map[id];
@@ -352,10 +353,13 @@ namespace ts.projectSystem {
}
invoke() {
// Note: invoking a callback may result in new callbacks been queued,
// so do not clear the entire callback list regardless. Only remove the
// ones we have invoked.
for (const key in this.map) {
this.map[key]();
delete this.map[key];
}
this.map = [];
}
}
@@ -3743,7 +3747,7 @@ namespace ts.projectSystem {
// run first step
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 messages");
assert.equal(host.getOutput().length, 1, "expect 1 message");
const e1 = <protocol.Event>getMessage(0);
assert.equal(e1.event, "syntaxDiag");
host.clearOutput();
@@ -3765,11 +3769,12 @@ namespace ts.projectSystem {
// run first step
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 messages");
assert.equal(host.getOutput().length, 1, "expect 1 message");
const e1 = <protocol.Event>getMessage(0);
assert.equal(e1.event, "syntaxDiag");
host.clearOutput();
// the semanticDiag message
host.runQueuedImmediateCallbacks();
assert.equal(host.getOutput().length, 2, "expect 2 messages");
const e2 = <protocol.Event>getMessage(0);
@@ -3787,7 +3792,7 @@ namespace ts.projectSystem {
assert.equal(host.getOutput().length, 0, "expect 0 messages");
// run first step
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 messages");
assert.equal(host.getOutput().length, 1, "expect 1 message");
const e1 = <protocol.Event>getMessage(0);
assert.equal(e1.event, "syntaxDiag");
host.clearOutput();
+4198 -4451
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1,4 +1,5 @@
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
/// <reference path="lib.es2017.intl.d.ts" />
+10
View File
@@ -0,0 +1,10 @@
type DateTimeFormatPartTypes = "day" | "dayPeriod" | "era" | "hour" | "literal" | "minute" | "month" | "second" | "timeZoneName" | "weekday" | "year";
interface DateTimeFormatPart {
type: DateTimeFormatPartTypes;
value: string;
}
interface DateTimeFormat {
formatToParts(date?: Date | number): DateTimeFormatPart[];
}
+145 -134
View File
@@ -1,6 +1,6 @@
/////////////////////////////
/// IE Worker APIs
/// Worker APIs
/////////////////////////////
interface Algorithm {
@@ -8,16 +8,16 @@ interface Algorithm {
}
interface CacheQueryOptions {
ignoreSearch?: boolean;
ignoreMethod?: boolean;
ignoreVary?: boolean;
cacheName?: string;
ignoreMethod?: boolean;
ignoreSearch?: boolean;
ignoreVary?: boolean;
}
interface CloseEventInit extends EventInit {
wasClean?: boolean;
code?: number;
reason?: string;
wasClean?: boolean;
}
interface EventInit {
@@ -49,16 +49,16 @@ interface MessageEventInit extends EventInit {
channel?: string;
data?: any;
origin?: string;
source?: any;
ports?: MessagePort[];
source?: any;
}
interface NotificationOptions {
dir?: NotificationDirection;
lang?: string;
body?: string;
tag?: string;
dir?: NotificationDirection;
icon?: string;
lang?: string;
tag?: string;
}
interface ObjectURLOptions {
@@ -66,29 +66,29 @@ interface ObjectURLOptions {
}
interface PushSubscriptionOptionsInit {
userVisibleOnly?: boolean;
applicationServerKey?: any;
userVisibleOnly?: boolean;
}
interface RequestInit {
method?: string;
headers?: any;
body?: any;
referrer?: string;
referrerPolicy?: ReferrerPolicy;
mode?: RequestMode;
credentials?: RequestCredentials;
cache?: RequestCache;
redirect?: RequestRedirect;
credentials?: RequestCredentials;
headers?: any;
integrity?: string;
keepalive?: boolean;
method?: string;
mode?: RequestMode;
redirect?: RequestRedirect;
referrer?: string;
referrerPolicy?: ReferrerPolicy;
window?: any;
}
interface ResponseInit {
headers?: any;
status?: number;
statusText?: string;
headers?: any;
}
interface ClientQueryOptions {
@@ -156,7 +156,7 @@ interface AudioBuffer {
declare var AudioBuffer: {
prototype: AudioBuffer;
new(): AudioBuffer;
}
};
interface Blob {
readonly size: number;
@@ -169,7 +169,7 @@ interface Blob {
declare var Blob: {
prototype: Blob;
new (blobParts?: any[], options?: BlobPropertyBag): Blob;
}
};
interface Cache {
add(request: RequestInfo): Promise<void>;
@@ -184,7 +184,7 @@ interface Cache {
declare var Cache: {
prototype: Cache;
new(): Cache;
}
};
interface CacheStorage {
delete(cacheName: string): Promise<boolean>;
@@ -197,7 +197,7 @@ interface CacheStorage {
declare var CacheStorage: {
prototype: CacheStorage;
new(): CacheStorage;
}
};
interface CloseEvent extends Event {
readonly code: number;
@@ -209,7 +209,7 @@ interface CloseEvent extends Event {
declare var CloseEvent: {
prototype: CloseEvent;
new(typeArg: string, eventInitDict?: CloseEventInit): CloseEvent;
}
};
interface Console {
assert(test?: boolean, message?: string, ...optionalParams: any[]): void;
@@ -220,8 +220,8 @@ interface Console {
dirxml(value: any): void;
error(message?: any, ...optionalParams: any[]): void;
exception(message?: string, ...optionalParams: any[]): void;
group(groupTitle?: string): void;
groupCollapsed(groupTitle?: string): void;
group(groupTitle?: string, ...optionalParams: any[]): void;
groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void;
groupEnd(): void;
info(message?: any, ...optionalParams: any[]): void;
log(message?: any, ...optionalParams: any[]): void;
@@ -239,7 +239,7 @@ interface Console {
declare var Console: {
prototype: Console;
new(): Console;
}
};
interface Coordinates {
readonly accuracy: number;
@@ -254,7 +254,7 @@ interface Coordinates {
declare var Coordinates: {
prototype: Coordinates;
new(): Coordinates;
}
};
interface CryptoKey {
readonly algorithm: KeyAlgorithm;
@@ -266,7 +266,7 @@ interface CryptoKey {
declare var CryptoKey: {
prototype: CryptoKey;
new(): CryptoKey;
}
};
interface DOMError {
readonly name: string;
@@ -276,7 +276,7 @@ interface DOMError {
declare var DOMError: {
prototype: DOMError;
new(): DOMError;
}
};
interface DOMException {
readonly code: number;
@@ -296,10 +296,10 @@ interface DOMException {
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
@@ -328,10 +328,10 @@ declare var DOMException: {
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
@@ -342,7 +342,7 @@ declare var DOMException: {
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
};
interface DOMStringList {
readonly length: number;
@@ -354,7 +354,7 @@ interface DOMStringList {
declare var DOMStringList: {
prototype: DOMStringList;
new(): DOMStringList;
}
};
interface ErrorEvent extends Event {
readonly colno: number;
@@ -368,12 +368,12 @@ interface ErrorEvent extends Event {
declare var ErrorEvent: {
prototype: ErrorEvent;
new(type: string, errorEventInitDict?: ErrorEventInit): ErrorEvent;
}
};
interface Event {
readonly bubbles: boolean;
cancelBubble: boolean;
readonly cancelable: boolean;
cancelBubble: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
@@ -400,7 +400,7 @@ declare var Event: {
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
};
interface EventTarget {
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
@@ -411,7 +411,7 @@ interface EventTarget {
declare var EventTarget: {
prototype: EventTarget;
new(): EventTarget;
}
};
interface File extends Blob {
readonly lastModifiedDate: any;
@@ -422,7 +422,7 @@ interface File extends Blob {
declare var File: {
prototype: File;
new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;
}
};
interface FileList {
readonly length: number;
@@ -433,7 +433,7 @@ interface FileList {
declare var FileList: {
prototype: FileList;
new(): FileList;
}
};
interface FileReader extends EventTarget, MSBaseReader {
readonly error: DOMError;
@@ -448,8 +448,17 @@ interface FileReader extends EventTarget, MSBaseReader {
declare var FileReader: {
prototype: FileReader;
new(): FileReader;
};
interface FormData {
append(name: string, value: string | Blob, fileName?: string): void;
}
declare var FormData: {
prototype: FormData;
new(): FormData;
};
interface Headers {
append(name: string, value: string): void;
delete(name: string): void;
@@ -462,7 +471,7 @@ interface Headers {
declare var Headers: {
prototype: Headers;
new(init?: any): Headers;
}
};
interface IDBCursor {
readonly direction: IDBCursorDirection;
@@ -486,7 +495,7 @@ declare var IDBCursor: {
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
};
interface IDBCursorWithValue extends IDBCursor {
readonly value: any;
@@ -495,7 +504,7 @@ interface IDBCursorWithValue extends IDBCursor {
declare var IDBCursorWithValue: {
prototype: IDBCursorWithValue;
new(): IDBCursorWithValue;
}
};
interface IDBDatabaseEventMap {
"abort": Event;
@@ -512,7 +521,7 @@ interface IDBDatabase extends EventTarget {
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
addEventListener<K extends keyof IDBDatabaseEventMap>(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -521,7 +530,7 @@ interface IDBDatabase extends EventTarget {
declare var IDBDatabase: {
prototype: IDBDatabase;
new(): IDBDatabase;
}
};
interface IDBFactory {
cmp(first: any, second: any): number;
@@ -532,7 +541,7 @@ interface IDBFactory {
declare var IDBFactory: {
prototype: IDBFactory;
new(): IDBFactory;
}
};
interface IDBIndex {
keyPath: string | string[];
@@ -543,14 +552,14 @@ interface IDBIndex {
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
get(key: IDBKeyRange | IDBValidKey): IDBRequest;
getKey(key: IDBKeyRange | IDBValidKey): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest;
}
declare var IDBIndex: {
prototype: IDBIndex;
new(): IDBIndex;
}
};
interface IDBKeyRange {
readonly lower: any;
@@ -566,7 +575,7 @@ declare var IDBKeyRange: {
lowerBound(lower: any, open?: boolean): IDBKeyRange;
only(value: any): IDBKeyRange;
upperBound(upper: any, open?: boolean): IDBKeyRange;
}
};
interface IDBObjectStore {
readonly indexNames: DOMStringList;
@@ -582,14 +591,14 @@ interface IDBObjectStore {
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
index(name: string): IDBIndex;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: IDBCursorDirection): IDBRequest;
put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
}
declare var IDBObjectStore: {
prototype: IDBObjectStore;
new(): IDBObjectStore;
}
};
interface IDBOpenDBRequestEventMap extends IDBRequestEventMap {
"blocked": Event;
@@ -606,7 +615,7 @@ interface IDBOpenDBRequest extends IDBRequest {
declare var IDBOpenDBRequest: {
prototype: IDBOpenDBRequest;
new(): IDBOpenDBRequest;
}
};
interface IDBRequestEventMap {
"error": Event;
@@ -614,7 +623,7 @@ interface IDBRequestEventMap {
}
interface IDBRequest extends EventTarget {
readonly error: DOMError;
readonly error: DOMException;
onerror: (this: IDBRequest, ev: Event) => any;
onsuccess: (this: IDBRequest, ev: Event) => any;
readonly readyState: IDBRequestReadyState;
@@ -628,7 +637,7 @@ interface IDBRequest extends EventTarget {
declare var IDBRequest: {
prototype: IDBRequest;
new(): IDBRequest;
}
};
interface IDBTransactionEventMap {
"abort": Event;
@@ -638,7 +647,7 @@ interface IDBTransactionEventMap {
interface IDBTransaction extends EventTarget {
readonly db: IDBDatabase;
readonly error: DOMError;
readonly error: DOMException;
readonly mode: IDBTransactionMode;
onabort: (this: IDBTransaction, ev: Event) => any;
oncomplete: (this: IDBTransaction, ev: Event) => any;
@@ -658,7 +667,7 @@ declare var IDBTransaction: {
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
}
};
interface IDBVersionChangeEvent extends Event {
readonly newVersion: number | null;
@@ -668,7 +677,7 @@ interface IDBVersionChangeEvent extends Event {
declare var IDBVersionChangeEvent: {
prototype: IDBVersionChangeEvent;
new(): IDBVersionChangeEvent;
}
};
interface ImageData {
data: Uint8ClampedArray;
@@ -680,7 +689,7 @@ declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
}
};
interface MessageChannel {
readonly port1: MessagePort;
@@ -690,7 +699,7 @@ interface MessageChannel {
declare var MessageChannel: {
prototype: MessageChannel;
new(): MessageChannel;
}
};
interface MessageEvent extends Event {
readonly data: any;
@@ -703,7 +712,7 @@ interface MessageEvent extends Event {
declare var MessageEvent: {
prototype: MessageEvent;
new(type: string, eventInitDict?: MessageEventInit): MessageEvent;
}
};
interface MessagePortEventMap {
"message": MessageEvent;
@@ -721,7 +730,7 @@ interface MessagePort extends EventTarget {
declare var MessagePort: {
prototype: MessagePort;
new(): MessagePort;
}
};
interface NotificationEventMap {
"click": Event;
@@ -751,7 +760,7 @@ declare var Notification: {
prototype: Notification;
new(title: string, options?: NotificationOptions): Notification;
requestPermission(callback?: NotificationPermissionCallback): Promise<NotificationPermission>;
}
};
interface Performance {
readonly navigation: PerformanceNavigation;
@@ -774,7 +783,7 @@ interface Performance {
declare var Performance: {
prototype: Performance;
new(): Performance;
}
};
interface PerformanceNavigation {
readonly redirectCount: number;
@@ -793,18 +802,18 @@ declare var PerformanceNavigation: {
readonly TYPE_NAVIGATE: number;
readonly TYPE_RELOAD: number;
readonly TYPE_RESERVED: number;
}
};
interface PerformanceTiming {
readonly connectEnd: number;
readonly connectStart: number;
readonly domainLookupEnd: number;
readonly domainLookupStart: number;
readonly domComplete: number;
readonly domContentLoadedEventEnd: number;
readonly domContentLoadedEventStart: number;
readonly domInteractive: number;
readonly domLoading: number;
readonly domainLookupEnd: number;
readonly domainLookupStart: number;
readonly fetchStart: number;
readonly loadEventEnd: number;
readonly loadEventStart: number;
@@ -824,7 +833,7 @@ interface PerformanceTiming {
declare var PerformanceTiming: {
prototype: PerformanceTiming;
new(): PerformanceTiming;
}
};
interface Position {
readonly coords: Coordinates;
@@ -834,7 +843,7 @@ interface Position {
declare var Position: {
prototype: Position;
new(): Position;
}
};
interface PositionError {
readonly code: number;
@@ -851,7 +860,7 @@ declare var PositionError: {
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
};
interface ProgressEvent extends Event {
readonly lengthComputable: boolean;
@@ -863,7 +872,7 @@ interface ProgressEvent extends Event {
declare var ProgressEvent: {
prototype: ProgressEvent;
new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;
}
};
interface PushManager {
getSubscription(): Promise<PushSubscription>;
@@ -874,7 +883,7 @@ interface PushManager {
declare var PushManager: {
prototype: PushManager;
new(): PushManager;
}
};
interface PushSubscription {
readonly endpoint: USVString;
@@ -887,7 +896,7 @@ interface PushSubscription {
declare var PushSubscription: {
prototype: PushSubscription;
new(): PushSubscription;
}
};
interface PushSubscriptionOptions {
readonly applicationServerKey: ArrayBuffer | null;
@@ -897,7 +906,7 @@ interface PushSubscriptionOptions {
declare var PushSubscriptionOptions: {
prototype: PushSubscriptionOptions;
new(): PushSubscriptionOptions;
}
};
interface ReadableStream {
readonly locked: boolean;
@@ -908,7 +917,7 @@ interface ReadableStream {
declare var ReadableStream: {
prototype: ReadableStream;
new(): ReadableStream;
}
};
interface ReadableStreamReader {
cancel(): Promise<void>;
@@ -919,7 +928,7 @@ interface ReadableStreamReader {
declare var ReadableStreamReader: {
prototype: ReadableStreamReader;
new(): ReadableStreamReader;
}
};
interface Request extends Object, Body {
readonly cache: RequestCache;
@@ -941,7 +950,7 @@ interface Request extends Object, Body {
declare var Request: {
prototype: Request;
new(input: Request | string, init?: RequestInit): Request;
}
};
interface Response extends Object, Body {
readonly body: ReadableStream | null;
@@ -957,7 +966,9 @@ interface Response extends Object, Body {
declare var Response: {
prototype: Response;
new(body?: any, init?: ResponseInit): Response;
}
error: () => Response;
redirect: (url: string, status?: number) => Response;
};
interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
"statechange": Event;
@@ -975,7 +986,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker {
declare var ServiceWorker: {
prototype: ServiceWorker;
new(): ServiceWorker;
}
};
interface ServiceWorkerRegistrationEventMap {
"updatefound": Event;
@@ -1000,7 +1011,7 @@ interface ServiceWorkerRegistration extends EventTarget {
declare var ServiceWorkerRegistration: {
prototype: ServiceWorkerRegistration;
new(): ServiceWorkerRegistration;
}
};
interface SyncManager {
getTags(): any;
@@ -1010,7 +1021,7 @@ interface SyncManager {
declare var SyncManager: {
prototype: SyncManager;
new(): SyncManager;
}
};
interface URL {
hash: string;
@@ -1033,7 +1044,7 @@ declare var URL: {
new(url: string, base?: string): URL;
createObjectURL(object: any, options?: ObjectURLOptions): string;
revokeObjectURL(url: string): void;
}
};
interface WebSocketEventMap {
"close": CloseEvent;
@@ -1070,7 +1081,7 @@ declare var WebSocket: {
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
}
};
interface WorkerEventMap extends AbstractWorkerEventMap {
"message": MessageEvent;
@@ -1087,7 +1098,7 @@ interface Worker extends EventTarget, AbstractWorker {
declare var Worker: {
prototype: Worker;
new(stringUrl: string): Worker;
}
};
interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {
"readystatechange": Event;
@@ -1133,7 +1144,7 @@ declare var XMLHttpRequest: {
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
}
};
interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, useCapture?: boolean): void;
@@ -1143,7 +1154,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
declare var XMLHttpRequestUpload: {
prototype: XMLHttpRequestUpload;
new(): XMLHttpRequestUpload;
}
};
interface AbstractWorkerEventMap {
"error": ErrorEvent;
@@ -1258,7 +1269,7 @@ interface Client {
declare var Client: {
prototype: Client;
new(): Client;
}
};
interface Clients {
claim(): Promise<void>;
@@ -1270,7 +1281,7 @@ interface Clients {
declare var Clients: {
prototype: Clients;
new(): Clients;
}
};
interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
"message": MessageEvent;
@@ -1287,7 +1298,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope {
declare var DedicatedWorkerGlobalScope: {
prototype: DedicatedWorkerGlobalScope;
new(): DedicatedWorkerGlobalScope;
}
};
interface ExtendableEvent extends Event {
waitUntil(f: Promise<any>): void;
@@ -1296,7 +1307,7 @@ interface ExtendableEvent extends Event {
declare var ExtendableEvent: {
prototype: ExtendableEvent;
new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent;
}
};
interface ExtendableMessageEvent extends ExtendableEvent {
readonly data: any;
@@ -1309,7 +1320,7 @@ interface ExtendableMessageEvent extends ExtendableEvent {
declare var ExtendableMessageEvent: {
prototype: ExtendableMessageEvent;
new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent;
}
};
interface FetchEvent extends ExtendableEvent {
readonly clientId: string | null;
@@ -1321,7 +1332,7 @@ interface FetchEvent extends ExtendableEvent {
declare var FetchEvent: {
prototype: FetchEvent;
new(type: string, eventInitDict: FetchEventInit): FetchEvent;
}
};
interface FileReaderSync {
readAsArrayBuffer(blob: Blob): any;
@@ -1333,7 +1344,7 @@ interface FileReaderSync {
declare var FileReaderSync: {
prototype: FileReaderSync;
new(): FileReaderSync;
}
};
interface NotificationEvent extends ExtendableEvent {
readonly action: string;
@@ -1343,7 +1354,7 @@ interface NotificationEvent extends ExtendableEvent {
declare var NotificationEvent: {
prototype: NotificationEvent;
new(type: string, eventInitDict: NotificationEventInit): NotificationEvent;
}
};
interface PushEvent extends ExtendableEvent {
readonly data: PushMessageData | null;
@@ -1352,7 +1363,7 @@ interface PushEvent extends ExtendableEvent {
declare var PushEvent: {
prototype: PushEvent;
new(type: string, eventInitDict?: PushEventInit): PushEvent;
}
};
interface PushMessageData {
arrayBuffer(): ArrayBuffer;
@@ -1364,7 +1375,7 @@ interface PushMessageData {
declare var PushMessageData: {
prototype: PushMessageData;
new(): PushMessageData;
}
};
interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
"activate": ExtendableEvent;
@@ -1398,7 +1409,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
declare var ServiceWorkerGlobalScope: {
prototype: ServiceWorkerGlobalScope;
new(): ServiceWorkerGlobalScope;
}
};
interface SyncEvent extends ExtendableEvent {
readonly lastChance: boolean;
@@ -1408,7 +1419,7 @@ interface SyncEvent extends ExtendableEvent {
declare var SyncEvent: {
prototype: SyncEvent;
new(type: string, init: SyncEventInit): SyncEvent;
}
};
interface WindowClient extends Client {
readonly focused: boolean;
@@ -1420,7 +1431,7 @@ interface WindowClient extends Client {
declare var WindowClient: {
prototype: WindowClient;
new(): WindowClient;
}
};
interface WorkerGlobalScopeEventMap {
"error": ErrorEvent;
@@ -1443,7 +1454,7 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo
declare var WorkerGlobalScope: {
prototype: WorkerGlobalScope;
new(): WorkerGlobalScope;
}
};
interface WorkerLocation {
readonly hash: string;
@@ -1461,7 +1472,7 @@ interface WorkerLocation {
declare var WorkerLocation: {
prototype: WorkerLocation;
new(): WorkerLocation;
}
};
interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware {
readonly hardwareConcurrency: number;
@@ -1470,7 +1481,7 @@ interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, Navigato
declare var WorkerNavigator: {
prototype: WorkerNavigator;
new(): WorkerNavigator;
}
};
interface WorkerUtils extends Object, WindowBase64 {
readonly indexedDB: IDBFactory;
@@ -1513,38 +1524,38 @@ interface ImageBitmap {
interface URLSearchParams {
/**
* Appends a specified key/value pair as a new search parameter.
*/
* Appends a specified key/value pair as a new search parameter.
*/
append(name: string, value: string): void;
/**
* Deletes the given search parameter, and its associated value, from the list of all search parameters.
*/
* Deletes the given search parameter, and its associated value, from the list of all search parameters.
*/
delete(name: string): void;
/**
* Returns the first value associated to the given search parameter.
*/
* Returns the first value associated to the given search parameter.
*/
get(name: string): string | null;
/**
* Returns all the values association with a given search parameter.
*/
* Returns all the values association with a given search parameter.
*/
getAll(name: string): string[];
/**
* Returns a Boolean indicating if such a search parameter exists.
*/
* Returns a Boolean indicating if such a search parameter exists.
*/
has(name: string): boolean;
/**
* Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
*/
* Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
*/
set(name: string, value: string): void;
}
declare var URLSearchParams: {
prototype: URLSearchParams;
/**
* Constructor returning a URLSearchParams object.
*/
* Constructor returning a URLSearchParams object.
*/
new (init?: string | URLSearchParams): URLSearchParams;
}
};
interface BlobPropertyBag {
type?: string;
@@ -1751,8 +1762,23 @@ interface AddEventListenerOptions extends EventListenerOptions {
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface DecodeErrorCallback {
(error: DOMException): void;
}
interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface ErrorEventHandler {
(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
(message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void;
}
interface ForEachCallback {
(keyId: any, status: MediaKeyStatus): void;
}
interface FunctionStringCallback {
(data: string): void;
}
interface NotificationPermissionCallback {
(permission: NotificationPermission): void;
}
interface PositionCallback {
(position: Position): void;
@@ -1760,21 +1786,6 @@ interface PositionCallback {
interface PositionErrorCallback {
(error: PositionError): void;
}
interface DecodeSuccessCallback {
(decodedData: AudioBuffer): void;
}
interface DecodeErrorCallback {
(error: DOMException): void;
}
interface FunctionStringCallback {
(data: string): void;
}
interface ForEachCallback {
(keyId: any, status: MediaKeyStatus): void;
}
interface NotificationPermissionCallback {
(permission: NotificationPermission): void;
}
declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any;
declare function close(): void;
declare function postMessage(message: any, transfer?: any[]): void;
+46 -6
View File
@@ -224,7 +224,7 @@ namespace ts.server {
return { name, kind, kindModifiers, sortText, replacementSpan: convertedSpan };
}
return entry as { name: string, kind: string, kindModifiers: string, sortText: string };
return entry as { name: string, kind: ScriptElementKind, kindModifiers: string, sortText: string };
})
};
}
@@ -265,7 +265,7 @@ namespace ts.server {
return {
name: entry.name,
containerName: entry.containerName || "",
containerKind: entry.containerKind || "",
containerKind: entry.containerKind || ScriptElementKind.unknown,
kind: entry.kind,
kindModifiers: entry.kindModifiers,
matchKind: entry.matchKind,
@@ -330,11 +330,11 @@ namespace ts.server {
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerKind: ScriptElementKind.unknown,
containerName: "",
fileName: fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
kind: "",
kind: ScriptElementKind.unknown,
name: ""
};
});
@@ -356,11 +356,11 @@ namespace ts.server {
const start = this.lineOffsetToPosition(fileName, entry.start);
const end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerKind: ScriptElementKind.unknown,
containerName: "",
fileName: fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
kind: "",
kind: ScriptElementKind.unknown,
name: ""
};
});
@@ -695,6 +695,46 @@ namespace ts.server {
return response.body.map(entry => this.convertCodeActions(entry, fileName));
}
private createFileLocationOrRangeRequestArgs(positionOrRange: number | TextRange, fileName: string): protocol.FileLocationOrRangeRequestArgs {
if (typeof positionOrRange === "number") {
const { line, offset } = this.positionToOneBasedLineOffset(fileName, positionOrRange);
return <protocol.FileLocationRequestArgs>{ file: fileName, line, offset };
}
const { line: startLine, offset: startOffset } = this.positionToOneBasedLineOffset(fileName, positionOrRange.pos);
const { line: endLine, offset: endOffset } = this.positionToOneBasedLineOffset(fileName, positionOrRange.end);
return <protocol.FileRangeRequestArgs>{
file: fileName,
startLine,
startOffset,
endLine,
endOffset
};
}
getApplicableRefactors(fileName: string, positionOrRange: number | TextRange): ApplicableRefactorInfo[] {
const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName);
const request = this.processRequest<protocol.GetApplicableRefactorsRequest>(CommandNames.GetApplicableRefactors, args);
const response = this.processResponse<protocol.GetApplicableRefactorsResponse>(request);
return response.body;
}
getRefactorCodeActions(
fileName: string,
_formatOptions: FormatCodeSettings,
positionOrRange: number | TextRange,
refactorName: string) {
const args = this.createFileLocationOrRangeRequestArgs(positionOrRange, fileName) as protocol.GetRefactorCodeActionsRequestArgs;
args.refactorName = refactorName;
const request = this.processRequest<protocol.GetRefactorCodeActionsRequest>(CommandNames.GetRefactorCodeActions, args);
const response = this.processResponse<protocol.GetRefactorCodeActionsResponse>(request);
const codeActions = response.body.actions;
return map(codeActions, codeAction => this.convertCodeActions(codeAction, fileName));
}
convertCodeActions(entry: protocol.CodeAction, fileName: string): CodeAction {
return {
description: entry.description,
+3
View File
@@ -283,6 +283,7 @@ namespace ts.server {
throttleWaitMilliseconds?: number;
globalPlugins?: string[];
pluginProbeLocations?: string[];
allowLocalPluginLoads?: boolean;
}
export class ProjectService {
@@ -342,6 +343,7 @@ namespace ts.server {
public readonly globalPlugins: ReadonlyArray<string>;
public readonly pluginProbeLocations: ReadonlyArray<string>;
public readonly allowLocalPluginLoads: boolean;
constructor(opts: ProjectServiceOptions) {
this.host = opts.host;
@@ -353,6 +355,7 @@ namespace ts.server {
this.eventHandler = opts.eventHandler;
this.globalPlugins = opts.globalPlugins || emptyArray;
this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray;
this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads;
Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService");
+7 -8
View File
@@ -13,13 +13,6 @@ namespace ts.server {
External
}
function remove<T>(items: T[], item: T) {
const index = items.indexOf(item);
if (index >= 0) {
items.splice(index, 1);
}
}
function countEachFileTypes(infos: ScriptInfo[]): { js: number, jsx: number, ts: number, tsx: number, dts: number } {
const result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 };
for (const info of infos) {
@@ -769,7 +762,7 @@ namespace ts.server {
// remove a root file from project
protected removeRoot(info: ScriptInfo): void {
remove(this.rootFiles, info);
orderedRemoveItem(this.rootFiles, info);
this.rootFilesMap.remove(info.path);
}
}
@@ -910,6 +903,12 @@ namespace ts.server {
// ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
const searchPaths = [combinePaths(host.getExecutingFilePath(), "../../.."), ...this.projectService.pluginProbeLocations];
if (this.projectService.allowLocalPluginLoads) {
const local = getDirectoryPath(this.canonicalConfigFilePath);
this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`);
searchPaths.unshift(local);
}
// Enable tsconfig-specified plugins
if (options.plugins) {
for (const pluginConfigEntry of options.plugins) {
+165 -123
View File
@@ -2,99 +2,104 @@
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
export namespace CommandTypes {
export type Brace = "brace";
// NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`.
export const enum CommandTypes {
Brace = "brace",
/* @internal */
export type BraceFull = "brace-full";
export type BraceCompletion = "braceCompletion";
export type Change = "change";
export type Close = "close";
export type Completions = "completions";
BraceFull = "brace-full",
BraceCompletion = "braceCompletion",
Change = "change",
Close = "close",
Completions = "completions",
/* @internal */
export type CompletionsFull = "completions-full";
export type CompletionDetails = "completionEntryDetails";
export type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export type CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export type Configure = "configure";
export type Definition = "definition";
CompletionsFull = "completions-full",
CompletionDetails = "completionEntryDetails",
CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList",
CompileOnSaveEmitFile = "compileOnSaveEmitFile",
Configure = "configure",
Definition = "definition",
/* @internal */
export type DefinitionFull = "definition-full";
export type Implementation = "implementation";
DefinitionFull = "definition-full",
Implementation = "implementation",
/* @internal */
export type ImplementationFull = "implementation-full";
export type Exit = "exit";
export type Format = "format";
export type Formatonkey = "formatonkey";
ImplementationFull = "implementation-full",
Exit = "exit",
Format = "format",
Formatonkey = "formatonkey",
/* @internal */
export type FormatFull = "format-full";
FormatFull = "format-full",
/* @internal */
export type FormatonkeyFull = "formatonkey-full";
FormatonkeyFull = "formatonkey-full",
/* @internal */
export type FormatRangeFull = "formatRange-full";
export type Geterr = "geterr";
export type GeterrForProject = "geterrForProject";
export type SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export type NavBar = "navbar";
FormatRangeFull = "formatRange-full",
Geterr = "geterr",
GeterrForProject = "geterrForProject",
SemanticDiagnosticsSync = "semanticDiagnosticsSync",
SyntacticDiagnosticsSync = "syntacticDiagnosticsSync",
NavBar = "navbar",
/* @internal */
export type NavBarFull = "navbar-full";
export type Navto = "navto";
NavBarFull = "navbar-full",
Navto = "navto",
/* @internal */
export type NavtoFull = "navto-full";
export type NavTree = "navtree";
export type NavTreeFull = "navtree-full";
export type Occurrences = "occurrences";
export type DocumentHighlights = "documentHighlights";
NavtoFull = "navto-full",
NavTree = "navtree",
NavTreeFull = "navtree-full",
Occurrences = "occurrences",
DocumentHighlights = "documentHighlights",
/* @internal */
export type DocumentHighlightsFull = "documentHighlights-full";
export type Open = "open";
export type Quickinfo = "quickinfo";
DocumentHighlightsFull = "documentHighlights-full",
Open = "open",
Quickinfo = "quickinfo",
/* @internal */
export type QuickinfoFull = "quickinfo-full";
export type References = "references";
QuickinfoFull = "quickinfo-full",
References = "references",
/* @internal */
export type ReferencesFull = "references-full";
export type Reload = "reload";
export type Rename = "rename";
ReferencesFull = "references-full",
Reload = "reload",
Rename = "rename",
/* @internal */
export type RenameInfoFull = "rename-full";
RenameInfoFull = "rename-full",
/* @internal */
export type RenameLocationsFull = "renameLocations-full";
export type Saveto = "saveto";
export type SignatureHelp = "signatureHelp";
RenameLocationsFull = "renameLocations-full",
Saveto = "saveto",
SignatureHelp = "signatureHelp",
/* @internal */
export type SignatureHelpFull = "signatureHelp-full";
export type TypeDefinition = "typeDefinition";
export type ProjectInfo = "projectInfo";
export type ReloadProjects = "reloadProjects";
export type Unknown = "unknown";
export type OpenExternalProject = "openExternalProject";
export type OpenExternalProjects = "openExternalProjects";
export type CloseExternalProject = "closeExternalProject";
SignatureHelpFull = "signatureHelp-full",
TypeDefinition = "typeDefinition",
ProjectInfo = "projectInfo",
ReloadProjects = "reloadProjects",
Unknown = "unknown",
OpenExternalProject = "openExternalProject",
OpenExternalProjects = "openExternalProjects",
CloseExternalProject = "closeExternalProject",
/* @internal */
export type SynchronizeProjectList = "synchronizeProjectList";
SynchronizeProjectList = "synchronizeProjectList",
/* @internal */
export type ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
ApplyChangedToOpenFiles = "applyChangedToOpenFiles",
/* @internal */
export type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full",
/* @internal */
export type Cleanup = "cleanup";
Cleanup = "cleanup",
/* @internal */
export type OutliningSpans = "outliningSpans";
export type TodoComments = "todoComments";
export type Indentation = "indentation";
export type DocCommentTemplate = "docCommentTemplate";
OutliningSpans = "outliningSpans",
TodoComments = "todoComments",
Indentation = "indentation",
DocCommentTemplate = "docCommentTemplate",
/* @internal */
export type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full",
/* @internal */
export type NameOrDottedNameSpan = "nameOrDottedNameSpan";
NameOrDottedNameSpan = "nameOrDottedNameSpan",
/* @internal */
export type BreakpointStatement = "breakpointStatement";
export type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export type GetCodeFixes = "getCodeFixes";
BreakpointStatement = "breakpointStatement",
CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects",
GetCodeFixes = "getCodeFixes",
/* @internal */
export type GetCodeFixesFull = "getCodeFixes-full";
export type GetSupportedCodeFixes = "getSupportedCodeFixes";
GetCodeFixesFull = "getCodeFixes-full",
GetSupportedCodeFixes = "getSupportedCodeFixes",
GetApplicableRefactors = "getApplicableRefactors",
GetRefactorCodeActions = "getRefactorCodeActions",
GetRefactorCodeActionsFull = "getRefactorCodeActions-full",
}
/**
@@ -394,6 +399,54 @@ namespace ts.server.protocol {
position?: number;
}
export type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs;
export interface GetApplicableRefactorsRequest extends Request {
command: CommandTypes.GetApplicableRefactors;
arguments: GetApplicableRefactorsRequestArgs;
}
export type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs;
export interface ApplicableRefactorInfo {
name: string;
description: string;
}
export interface GetApplicableRefactorsResponse extends Response {
body?: ApplicableRefactorInfo[];
}
export interface GetRefactorCodeActionsRequest extends Request {
command: CommandTypes.GetRefactorCodeActions;
arguments: GetRefactorCodeActionsRequestArgs;
}
export type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & {
/* The kind of the applicable refactor */
refactorName: string;
};
export type RefactorCodeActions = {
actions: protocol.CodeAction[];
renameLocation?: number
};
/* @internal */
export type RefactorCodeActionsFull = {
actions: ts.CodeAction[];
renameLocation?: number
};
export interface GetRefactorCodeActionsResponse extends Response {
body: RefactorCodeActions;
}
/* @internal */
export interface GetRefactorCodeActionsFullResponse extends Response {
body: RefactorCodeActionsFull;
}
/**
* Request for the available codefixes at a specific position.
*/
@@ -402,10 +455,7 @@ namespace ts.server.protocol {
arguments: CodeFixRequestArgs;
}
/**
* Instances of this interface specify errorcodes on a specific location in a sourcefile.
*/
export interface CodeFixRequestArgs extends FileRequestArgs {
export interface FileRangeRequestArgs extends FileRequestArgs {
/**
* The line number for the request (1-based).
*/
@@ -437,7 +487,12 @@ namespace ts.server.protocol {
*/
/* @internal */
endPosition?: number;
}
/**
* Instances of this interface specify errorcodes on a specific location in a sourcefile.
*/
export interface CodeFixRequestArgs extends FileRangeRequestArgs {
/**
* Errorcodes we want to get the fixes for.
*/
@@ -644,10 +699,9 @@ namespace ts.server.protocol {
/**
* Span augmented with extra information that denotes the kind of the highlighting to be used for span.
* Kind is taken from HighlightSpanKind type.
*/
export interface HighlightSpan extends TextSpan {
kind: string;
kind: HighlightSpanKind;
}
/**
@@ -784,7 +838,7 @@ namespace ts.server.protocol {
/**
* The items's kind (such as 'className' or 'parameterName' or plain 'text').
*/
kind: string;
kind: ScriptElementKind;
/**
* Optional modifiers for the kind (such as 'public').
@@ -1298,7 +1352,7 @@ namespace ts.server.protocol {
/**
* The symbol's kind (such as 'className' or 'parameterName' or plain 'text').
*/
kind: string;
kind: ScriptElementKind;
/**
* Optional modifiers for the kind (such as 'public').
@@ -1517,7 +1571,7 @@ namespace ts.server.protocol {
/**
* The symbol's kind (such as 'className' or 'parameterName').
*/
kind: string;
kind: ScriptElementKind;
/**
* Optional modifiers for the kind (such as 'public').
*/
@@ -1545,7 +1599,7 @@ namespace ts.server.protocol {
/**
* The symbol's kind (such as 'className' or 'parameterName').
*/
kind: string;
kind: ScriptElementKind;
/**
* Optional modifiers for the kind (such as 'public').
*/
@@ -2011,7 +2065,7 @@ namespace ts.server.protocol {
/**
* The symbol's kind (such as 'className' or 'parameterName').
*/
kind: string;
kind: ScriptElementKind;
/**
* exact, substring, or prefix.
@@ -2052,7 +2106,7 @@ namespace ts.server.protocol {
/**
* Kind of symbol's container symbol (if any).
*/
containerKind?: string;
containerKind?: ScriptElementKind;
}
/**
@@ -2125,7 +2179,7 @@ namespace ts.server.protocol {
/**
* The symbol's kind (such as 'className' or 'parameterName').
*/
kind: string;
kind: ScriptElementKind;
/**
* Optional modifiers for the kind (such as 'public').
@@ -2151,7 +2205,7 @@ namespace ts.server.protocol {
/** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */
export interface NavigationTree {
text: string;
kind: string;
kind: ScriptElementKind;
kindModifiers: string;
spans: TextSpan[];
childItems?: NavigationTree[];
@@ -2245,14 +2299,12 @@ namespace ts.server.protocol {
body?: NavigationTree;
}
export namespace IndentStyle {
export type None = "None";
export type Block = "Block";
export type Smart = "Smart";
export const enum IndentStyle {
None = "None",
Block = "Block",
Smart = "Smart",
}
export type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart;
export interface EditorSettings {
baseIndentSize?: number;
indentSize?: number;
@@ -2349,47 +2401,37 @@ namespace ts.server.protocol {
[option: string]: CompilerOptionsValue | undefined;
}
export namespace JsxEmit {
export type None = "None";
export type Preserve = "Preserve";
export type ReactNative = "ReactNative";
export type React = "React";
export const enum JsxEmit {
None = "None",
Preserve = "Preserve",
ReactNative = "ReactNative",
React = "React",
}
export type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React | JsxEmit.ReactNative;
export namespace ModuleKind {
export type None = "None";
export type CommonJS = "CommonJS";
export type AMD = "AMD";
export type UMD = "UMD";
export type System = "System";
export type ES6 = "ES6";
export type ES2015 = "ES2015";
export const enum ModuleKind {
None = "None",
CommonJS = "CommonJS",
AMD = "AMD",
UMD = "UMD",
System = "System",
ES6 = "ES6",
ES2015 = "ES2015",
}
export type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015;
export namespace ModuleResolutionKind {
export type Classic = "Classic";
export type Node = "Node";
export const enum ModuleResolutionKind {
Classic = "Classic",
Node = "Node",
}
export type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node;
export namespace NewLineKind {
export type Crlf = "Crlf";
export type Lf = "Lf";
export const enum NewLineKind {
Crlf = "Crlf",
Lf = "Lf",
}
export type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf;
export namespace ScriptTarget {
export type ES3 = "ES3";
export type ES5 = "ES5";
export type ES6 = "ES6";
export type ES2015 = "ES2015";
export const enum ScriptTarget {
ES3 = "ES3",
ES5 = "ES5",
ES6 = "ES6",
ES2015 = "ES2015",
}
export type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015;
}
+6 -2
View File
@@ -16,6 +16,7 @@ namespace ts.server {
telemetryEnabled: boolean;
globalPlugins: string[];
pluginProbeLocations: string[];
allowLocalPluginLoads: boolean;
}
const net: {
@@ -403,7 +404,8 @@ namespace ts.server {
logger,
canUseEvents,
globalPlugins: options.globalPlugins,
pluginProbeLocations: options.pluginProbeLocations});
pluginProbeLocations: options.pluginProbeLocations,
allowLocalPluginLoads: options.allowLocalPluginLoads });
if (telemetryEnabled && typingsInstaller) {
typingsInstaller.setTelemetrySender(this);
@@ -743,6 +745,7 @@ namespace ts.server {
const globalPlugins = (findArgument("--globalPlugins") || "").split(",");
const pluginProbeLocations = (findArgument("--pluginProbeLocations") || "").split(",");
const allowLocalPluginLoads = hasArgument("--allowLocalPluginLoads");
const useSingleInferredProject = hasArgument("--useSingleInferredProject");
const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition");
@@ -760,7 +763,8 @@ namespace ts.server {
telemetryEnabled,
logger,
globalPlugins,
pluginProbeLocations
pluginProbeLocations,
allowLocalPluginLoads
};
const ioSession = new IOSession(options);
+98 -113
View File
@@ -106,7 +106,7 @@ namespace ts.server {
}
export interface EventSender {
event(payload: any, eventName: string): void;
event<T>(payload: T, eventName: string): void;
}
function allEditsBeforePos(edits: ts.TextChange[], pos: number) {
@@ -118,100 +118,7 @@ namespace ts.server {
return true;
}
export namespace CommandNames {
export const Brace: protocol.CommandTypes.Brace = "brace";
/* @internal */
export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full";
export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion";
export const Change: protocol.CommandTypes.Change = "change";
export const Close: protocol.CommandTypes.Close = "close";
export const Completions: protocol.CommandTypes.Completions = "completions";
/* @internal */
export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full";
export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails";
export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList";
export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile";
export const Configure: protocol.CommandTypes.Configure = "configure";
export const Definition: protocol.CommandTypes.Definition = "definition";
/* @internal */
export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full";
export const Exit: protocol.CommandTypes.Exit = "exit";
export const Format: protocol.CommandTypes.Format = "format";
export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey";
/* @internal */
export const FormatFull: protocol.CommandTypes.FormatFull = "format-full";
/* @internal */
export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full";
/* @internal */
export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full";
export const Geterr: protocol.CommandTypes.Geterr = "geterr";
export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject";
export const Implementation: protocol.CommandTypes.Implementation = "implementation";
/* @internal */
export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full";
export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync";
export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync";
export const NavBar: protocol.CommandTypes.NavBar = "navbar";
/* @internal */
export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full";
export const NavTree: protocol.CommandTypes.NavTree = "navtree";
export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full";
export const Navto: protocol.CommandTypes.Navto = "navto";
/* @internal */
export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full";
export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences";
export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights";
/* @internal */
export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full";
export const Open: protocol.CommandTypes.Open = "open";
export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo";
/* @internal */
export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full";
export const References: protocol.CommandTypes.References = "references";
/* @internal */
export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full";
export const Reload: protocol.CommandTypes.Reload = "reload";
export const Rename: protocol.CommandTypes.Rename = "rename";
/* @internal */
export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full";
/* @internal */
export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full";
export const Saveto: protocol.CommandTypes.Saveto = "saveto";
export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp";
/* @internal */
export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full";
export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition";
export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo";
export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects";
export const Unknown: protocol.CommandTypes.Unknown = "unknown";
export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject";
export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects";
export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject";
/* @internal */
export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList";
/* @internal */
export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles";
/* @internal */
export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full";
/* @internal */
export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup";
/* @internal */
export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans";
export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments";
export const Indentation: protocol.CommandTypes.Indentation = "indentation";
export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate";
/* @internal */
export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full";
/* @internal */
export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan";
/* @internal */
export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement";
export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects";
export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes";
/* @internal */
export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full";
export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes";
}
export import CommandNames = protocol.CommandTypes;
export function formatMessage<T extends protocol.Message>(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string {
const verboseLogging = logger.hasLevel(LogLevel.verbose);
@@ -368,6 +275,7 @@ namespace ts.server {
globalPlugins?: string[];
pluginProbeLocations?: string[];
allowLocalPluginLoads?: boolean;
}
export class Session implements EventSender {
@@ -421,7 +329,8 @@ namespace ts.server {
throttleWaitMilliseconds,
eventHandler: this.eventHandler,
globalPlugins: opts.globalPlugins,
pluginProbeLocations: opts.pluginProbeLocations
pluginProbeLocations: opts.pluginProbeLocations,
allowLocalPluginLoads: opts.allowLocalPluginLoads
};
this.projectService = new ProjectService(settings);
this.gcTimer = new GcTimer(this.host, /*delay*/ 7000, this.logger);
@@ -450,7 +359,7 @@ namespace ts.server {
break;
case ProjectLanguageServiceStateEvent:
const eventName: protocol.ProjectLanguageServiceStateEventName = "projectLanguageServiceState";
this.event(<protocol.ProjectLanguageServiceStateEventBody>{
this.event<protocol.ProjectLanguageServiceStateEventBody>({
projectName: event.data.project.getProjectName(),
languageServiceEnabled: event.data.languageServiceEnabled
}, eventName);
@@ -494,7 +403,7 @@ namespace ts.server {
this.send(ev);
}
public event(info: any, eventName: string) {
public event<T>(info: T, eventName: string) {
const ev: protocol.Event = {
seq: 0,
type: "event",
@@ -529,7 +438,7 @@ namespace ts.server {
}
const bakedDiags = diags.map((diag) => formatDiag(file, project, diag));
this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag");
this.event<protocol.DiagnosticEventBody>({ file: file, diagnostics: bakedDiags }, "semanticDiag");
}
catch (err) {
this.logError(err, "semantic check");
@@ -541,7 +450,7 @@ namespace ts.server {
const diags = project.getLanguageService().getSyntacticDiagnostics(file);
if (diags) {
const bakedDiags = diags.map((diag) => formatDiag(file, project, diag));
this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag");
this.event<protocol.DiagnosticEventBody>({ file: file, diagnostics: bakedDiags }, "syntaxDiag");
}
}
catch (err) {
@@ -1440,8 +1349,8 @@ namespace ts.server {
return !items
? undefined
: simplifiedResult
? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file))
: items;
? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file))
: items;
}
private decorateNavigationTree(tree: ts.NavigationTree, scriptInfo: ScriptInfo): protocol.NavigationTree {
@@ -1467,8 +1376,8 @@ namespace ts.server {
return !tree
? undefined
: simplifiedResult
? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file))
: tree;
? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file))
: tree;
}
private getNavigateToItems(args: protocol.NavtoRequestArgs, simplifiedResult: boolean): protocol.NavtoItem[] | NavigateToItem[] {
@@ -1555,6 +1464,60 @@ namespace ts.server {
return ts.getSupportedCodeFixes();
}
private isLocation(locationOrSpan: protocol.FileLocationOrRangeRequestArgs): locationOrSpan is protocol.FileLocationRequestArgs {
return (<protocol.FileLocationRequestArgs>locationOrSpan).line !== undefined;
}
private extractPositionAndRange(args: protocol.FileLocationOrRangeRequestArgs, scriptInfo: ScriptInfo): { position: number, textRange: TextRange } {
let position: number = undefined;
let textRange: TextRange;
if (this.isLocation(args)) {
position = getPosition(args);
}
else {
const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
textRange = { pos: startPosition, end: endPosition };
}
return { position, textRange };
function getPosition(loc: protocol.FileLocationRequestArgs) {
return loc.position !== undefined ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset);
}
}
private getApplicableRefactors(args: protocol.GetApplicableRefactorsRequestArgs): protocol.ApplicableRefactorInfo[] {
const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args);
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
const { position, textRange } = this.extractPositionAndRange(args, scriptInfo);
return project.getLanguageService().getApplicableRefactors(file, position || textRange);
}
private getRefactorCodeActions(args: protocol.GetRefactorCodeActionsRequestArgs, simplifiedResult: boolean): protocol.RefactorCodeActions | protocol.RefactorCodeActionsFull {
const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args);
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
const { position, textRange } = this.extractPositionAndRange(args, scriptInfo);
const result: ts.CodeAction[] = project.getLanguageService().getRefactorCodeActions(
file,
this.projectService.getFormatCodeOptions(),
position || textRange,
args.refactorName
);
if (simplifiedResult) {
// Not full
return {
actions: result.map(action => this.mapCodeAction(action, scriptInfo))
};
}
else {
// Full
return {
actions: result
};
}
}
private getCodeFixes(args: protocol.CodeFixRequestArgs, simplifiedResult: boolean): protocol.CodeAction[] | CodeAction[] {
if (args.errorCodes.length === 0) {
return undefined;
@@ -1562,8 +1525,7 @@ namespace ts.server {
const { file, project } = this.getFileAndProjectWithoutRefreshingInferredProjects(args);
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
const startPosition = getStartPosition();
const endPosition = getEndPosition();
const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo);
const formatOptions = this.projectService.getFormatCodeOptions(file);
const codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, formatOptions);
@@ -1576,14 +1538,28 @@ namespace ts.server {
else {
return codeActions;
}
}
function getStartPosition() {
return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
private getStartAndEndPosition(args: protocol.FileRangeRequestArgs, scriptInfo: ScriptInfo) {
let startPosition: number = undefined, endPosition: number = undefined;
if (args.startPosition !== undefined) {
startPosition = args.startPosition;
}
else {
startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
// save the result so we don't always recompute
args.startPosition = startPosition;
}
function getEndPosition() {
return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
if (args.endPosition !== undefined) {
endPosition = args.endPosition;
}
else {
endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
args.endPosition = endPosition;
}
return { startPosition, endPosition };
}
private mapCodeAction(codeAction: CodeAction, scriptInfo: ScriptInfo): protocol.CodeAction {
@@ -1614,8 +1590,8 @@ namespace ts.server {
return !spans
? undefined
: simplifiedResult
? spans.map(span => this.decorateSpan(span, scriptInfo))
: spans;
? spans.map(span => this.decorateSpan(span, scriptInfo))
: spans;
}
private getDiagnosticsForProject(next: NextStep, delay: number, fileName: string): void {
@@ -1940,6 +1916,15 @@ namespace ts.server {
},
[CommandNames.GetSupportedCodeFixes]: () => {
return this.requiredResponse(this.getSupportedCodeFixes());
},
[CommandNames.GetApplicableRefactors]: (request: protocol.GetApplicableRefactorsRequest) => {
return this.requiredResponse(this.getApplicableRefactors(request.arguments));
},
[CommandNames.GetRefactorCodeActions]: (request: protocol.GetRefactorCodeActionsRequest) => {
return this.requiredResponse(this.getRefactorCodeActions(request.arguments, /*simplifiedResult*/ true));
},
[CommandNames.GetRefactorCodeActionsFull]: (request: protocol.GetRefactorCodeActionsRequest) => {
return this.requiredResponse(this.getRefactorCodeActions(request.arguments, /*simplifiedResult*/ false));
}
});
@@ -1997,7 +1982,7 @@ namespace ts.server {
let request: protocol.Request;
try {
request = <protocol.Request>JSON.parse(message);
const {response, responseRequired} = this.executeCommand(request);
const { response, responseRequired } = this.executeCommand(request);
if (this.logger.hasLevel(LogLevel.requestTime)) {
const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4);
+1 -1
View File
@@ -14,7 +14,7 @@ namespace ts.BreakpointResolver {
return undefined;
}
let tokenAtLocation = getTokenAtPosition(sourceFile, position);
let tokenAtLocation = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
// Get previous token if the token is returned starts on new line
+1 -1
View File
@@ -573,7 +573,7 @@ namespace ts {
}
}
function getClassificationTypeName(type: ClassificationType) {
function getClassificationTypeName(type: ClassificationType): ClassificationTypeNames {
switch (type) {
case ClassificationType.comment: return ClassificationTypeNames.comment;
case ClassificationType.identifier: return ClassificationTypeNames.identifier;
+3 -3
View File
@@ -19,14 +19,14 @@ namespace ts {
export namespace codefix {
const codeFixes: CodeFix[][] = [];
export function registerCodeFix(action: CodeFix) {
forEach(action.errorCodes, error => {
export function registerCodeFix(codeFix: CodeFix) {
forEach(codeFix.errorCodes, error => {
let fixes = codeFixes[error];
if (!fixes) {
fixes = [];
codeFixes[error] = fixes;
}
fixes.push(action);
fixes.push(codeFix);
});
}
@@ -22,7 +22,7 @@ namespace ts.codefix {
// We also want to check if the previous line holds a comment for a node on the next line
// if so, we do not want to separate the node from its comment if we can.
if (!isInComment(sourceFile, startPosition) && !isInString(sourceFile, startPosition) && !isInTemplateString(sourceFile, startPosition)) {
const token = getTouchingToken(sourceFile, startPosition);
const token = getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false);
const tokenLeadingCommnets = getLeadingCommentRangesOfNode(token, sourceFile);
if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) {
return {
@@ -13,7 +13,7 @@ namespace ts.codefix {
// This is the identifier of the missing property. eg:
// this.missing = 1;
// ^^^^^^^
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.Identifier) {
return undefined;
@@ -15,7 +15,7 @@ namespace ts.codefix {
const start = context.span.start;
// This is the identifier in the case of a class declaration
// or the class keyword token in the case of a class expression.
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const checker = context.program.getTypeChecker();
if (isClassLike(token.parent)) {
@@ -8,7 +8,7 @@ namespace ts.codefix {
function getActionForClassLikeIncorrectImplementsInterface(context: CodeFixContext): CodeAction[] | undefined {
const sourceFile = context.sourceFile;
const start = context.span.start;
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const checker = context.program.getTypeChecker();
const classDeclaration = getContainingClass(token);
@@ -5,7 +5,7 @@ namespace ts.codefix {
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.ThisKeyword) {
return undefined;
}
@@ -4,7 +4,7 @@ namespace ts.codefix {
errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.ConstructorKeyword) {
return undefined;
@@ -5,7 +5,7 @@ namespace ts.codefix {
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const start = context.span.start;
const token = getTokenAtPosition(sourceFile, start);
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const classDeclNode = getContainingClass(token);
if (!(token.kind === SyntaxKind.Identifier && isClassLike(classDeclNode))) {
return undefined;
@@ -4,7 +4,7 @@ namespace ts.codefix {
errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
if (token.kind !== SyntaxKind.Identifier) {
return undefined;
}
+1 -1
View File
@@ -12,7 +12,7 @@ namespace ts.codefix {
// This is the identifier of the misspelled word. eg:
// this.speling = 1;
// ^^^^^^^
const node = getTokenAtPosition(sourceFile, context.span.start);
const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852
const checker = context.program.getTypeChecker();
let suggestion: string;
if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) {
+1 -1
View File
@@ -130,7 +130,7 @@ namespace ts.codefix {
}
function signatureToMethodDeclaration(signature: Signature, enclosingDeclaration: Node, body?: Block) {
const signatureDeclaration = <MethodDeclaration>checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration);
const signatureDeclaration = <MethodDeclaration>checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.SuppressAnyReturnType);
if (signatureDeclaration) {
signatureDeclaration.decorators = undefined;
signatureDeclaration.modifiers = modifiers;
+2 -2
View File
@@ -128,7 +128,7 @@ namespace ts.codefix {
const allSourceFiles = context.program.getSourceFiles();
const useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false;
const token = getTokenAtPosition(sourceFile, context.span.start);
const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false);
const name = token.getText();
const symbolIdActionMap = new ImportCodeActionMap();
@@ -523,7 +523,7 @@ namespace ts.codefix {
catch (e) { }
}
return relativeFileName;
return getPackageNameFromAtTypesDirectory(relativeFileName);
}
}
@@ -9,11 +9,11 @@ namespace ts.codefix {
const sourceFile = context.sourceFile;
const start = context.span.start;
let token = getTokenAtPosition(sourceFile, start);
let token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
// this handles var ["computed"] = 12;
if (token.kind === SyntaxKind.OpenBracketToken) {
token = getTokenAtPosition(sourceFile, start + 1);
token = getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false);
}
switch (token.kind) {
@@ -48,11 +48,11 @@ namespace ts.codefix {
case SyntaxKind.TypeParameter:
const typeParameters = (<DeclarationWithTypeParameters>token.parent.parent).typeParameters;
if (typeParameters.length === 1) {
const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1);
const previousToken = getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false);
if (!previousToken || previousToken.kind !== SyntaxKind.LessThanToken) {
return deleteRange(typeParameters);
}
const nextToken = getTokenAtPosition(sourceFile, typeParameters.end);
const nextToken = getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false);
if (!nextToken || nextToken.kind !== SyntaxKind.GreaterThanToken) {
return deleteRange(typeParameters);
}
@@ -99,7 +99,7 @@ namespace ts.codefix {
else {
// import |d,| * as ns from './file'
const start = importClause.name.getStart(sourceFile);
const nextToken = getTokenAtPosition(sourceFile, importClause.name.end);
const nextToken = getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false);
if (nextToken && nextToken.kind === SyntaxKind.CommaToken) {
// shift first non-whitespace position after comma to the start position of the node
return deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) });
@@ -116,7 +116,7 @@ namespace ts.codefix {
return deleteNode(importDecl);
}
else {
const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1);
const previousToken = getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false);
if (previousToken && previousToken.kind === SyntaxKind.CommaToken) {
const startPosition = textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, textChanges.Position.FullStart);
return deleteRange({ pos: startPosition, end: namespaceImport.end });
+4 -4
View File
@@ -275,7 +275,7 @@ namespace ts.Completions {
}
}
else if (type.flags & TypeFlags.StringLiteral) {
const name = (<LiteralType>type).text;
const name = (<StringLiteralType>type).value;
if (!uniques.has(name)) {
uniques.set(name, true);
result.push({
@@ -354,12 +354,12 @@ namespace ts.Completions {
let requestJsDocTag = false;
let start = timestamp();
const currentToken = getTokenAtPosition(sourceFile, position);
const currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853
log("getCompletionData: Get current token: " + (timestamp() - start));
start = timestamp();
// Completion not allowed inside comments, bail out if this is the case
const insideComment = isInsideComment(sourceFile, currentToken, position);
const insideComment = isInComment(sourceFile, position, currentToken);
log("getCompletionData: Is inside comment: " + (timestamp() - start));
if (insideComment) {
@@ -449,7 +449,7 @@ namespace ts.Completions {
let isRightOfOpenTag = false;
let isStartingCloseTag = false;
let location = getTouchingPropertyName(sourceFile, position);
let location = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853
if (contextToken) {
// Bail out if this is a known invalid completion location
if (isCompletionListBlocker(contextToken)) {
+5 -5
View File
@@ -1,8 +1,8 @@
/* @internal */
namespace ts.DocumentHighlights {
export function getDocumentHighlights(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] {
const node = getTouchingWord(sourceFile, position);
return node && (getSemanticDocumentHighlights(node, typeChecker, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile));
export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] {
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true);
return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile));
}
function getHighlightSpanForNode(node: Node, sourceFile: SourceFile): HighlightSpan {
@@ -16,8 +16,8 @@ namespace ts.DocumentHighlights {
};
}
function getSemanticDocumentHighlights(node: Node, typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] {
const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken);
function getSemanticDocumentHighlights(node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] {
const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken);
return referenceEntries && convertReferencedSymbols(referenceEntries);
}
+105 -41
View File
@@ -41,14 +41,15 @@ namespace ts.FindAllReferences {
readonly implementations?: boolean;
}
export function findReferencedSymbols(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined {
const referencedSymbols = findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position);
export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined {
const referencedSymbols = findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position);
if (!referencedSymbols || !referencedSymbols.length) {
return undefined;
}
const out: ReferencedSymbol[] = [];
const checker = program.getTypeChecker();
for (const { definition, references } of referencedSymbols) {
// Only include referenced symbols that have a valid definition.
if (definition) {
@@ -59,44 +60,51 @@ namespace ts.FindAllReferences {
return out;
}
export function getImplementationsAtPosition(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] {
const node = getTouchingPropertyName(sourceFile, position);
const referenceEntries = getImplementationReferenceEntries(checker, cancellationToken, sourceFiles, node);
export function getImplementationsAtPosition(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number): ImplementationLocation[] {
// A node in a JSDoc comment can't have an implementation anyway.
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false);
const referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node);
const checker = program.getTypeChecker();
return map(referenceEntries, entry => toImplementationLocation(entry, checker));
}
function getImplementationReferenceEntries(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined {
function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): Entry[] | undefined {
if (node.kind === SyntaxKind.SourceFile) {
return undefined;
}
const checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
const result: NodeEntry[] = [];
Core.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, node => result.push(nodeEntry(node)));
Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, node => result.push(nodeEntry(node)));
return result;
}
else if (node.kind === SyntaxKind.SuperKeyword || isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
// need to "Find all References"
const symbol = typeChecker.getSymbolAtLocation(node);
const symbol = checker.getSymbolAtLocation(node);
return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)];
}
else {
// Perform "Find all References" and retrieve only those that are implementations
return getReferenceEntriesForNode(node, sourceFiles, typeChecker, cancellationToken, { implementations: true });
return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true });
}
}
export function findReferencedEntries(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined {
const x = flattenEntries(findAllReferencedSymbols(checker, cancellationToken, sourceFiles, sourceFile, position, options));
export function findReferencedEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): ReferenceEntry[] | undefined {
const x = flattenEntries(findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options));
return map(x, toReferenceEntry);
}
export function getReferenceEntriesForNode(node: Node, sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined {
return flattenEntries(Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options));
export function getReferenceEntriesForNode(node: Node, program: Program, sourceFiles: SourceFile[], cancellationToken: CancellationToken, options: Options = {}): Entry[] | undefined {
return flattenEntries(Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options));
}
function findAllReferencedSymbols(checker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined {
function findAllReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: SourceFile[], sourceFile: SourceFile, position: number, options?: Options): SymbolAndEntries[] | undefined {
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
return Core.getReferencedSymbolsForNode(node, sourceFiles, checker, cancellationToken, options);
return Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options);
}
function flattenEntries(referenceSymbols: SymbolAndEntries[]): Entry[] {
@@ -142,7 +150,7 @@ namespace ts.FindAllReferences {
const { node, name, kind, displayParts } = info;
const sourceFile = node.getSourceFile();
return {
containerKind: "",
containerKind: ScriptElementKind.unknown,
containerName: "",
fileName: sourceFile.fileName,
kind,
@@ -152,7 +160,7 @@ namespace ts.FindAllReferences {
};
}
function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: string } {
function getDefinitionKindAndDisplayParts(symbol: Symbol, node: Node, checker: TypeChecker): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } {
const { displayParts, symbolKind } =
SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node.getSourceFile(), getContainerNode(node), node);
return { displayParts, kind: symbolKind };
@@ -168,7 +176,7 @@ namespace ts.FindAllReferences {
fileName: node.getSourceFile().fileName,
textSpan: getTextSpan(node),
isWriteAccess: isWriteAccess(node),
isDefinition: isDeclarationName(node) || isLiteralComputedPropertyDeclarationName(node),
isDefinition: isAnyDeclarationName(node) || isLiteralComputedPropertyDeclarationName(node),
isInString
};
}
@@ -183,7 +191,7 @@ namespace ts.FindAllReferences {
}
}
function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: string, displayParts: SymbolDisplayPart[] } {
function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } {
const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node);
if (symbol) {
return getDefinitionKindAndDisplayParts(symbol, node, checker);
@@ -234,22 +242,20 @@ namespace ts.FindAllReferences {
/** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
function isWriteAccess(node: Node): boolean {
if (node.kind === SyntaxKind.Identifier && isDeclarationName(node)) {
if (isAnyDeclarationName(node)) {
return true;
}
const parent = node.parent;
if (parent) {
if (parent.kind === SyntaxKind.PostfixUnaryExpression || parent.kind === SyntaxKind.PrefixUnaryExpression) {
const { parent } = node;
switch (parent && parent.kind) {
case SyntaxKind.PostfixUnaryExpression:
case SyntaxKind.PrefixUnaryExpression:
return true;
}
else if (parent.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>parent).left === node) {
const operator = (<BinaryExpression>parent).operatorToken.kind;
return SyntaxKind.FirstAssignment <= operator && operator <= SyntaxKind.LastAssignment;
}
case SyntaxKind.BinaryExpression:
return (<BinaryExpression>parent).left === node && isAssignmentOperator((<BinaryExpression>parent).operatorToken.kind);
default:
return false;
}
return false;
}
}
@@ -257,7 +263,7 @@ namespace ts.FindAllReferences {
/* @internal */
namespace ts.FindAllReferences.Core {
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
export function getReferencedSymbolsForNode(node: Node, sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined {
export function getReferencedSymbolsForNode(node: Node, program: Program, sourceFiles: SourceFile[], cancellationToken: CancellationToken, options: Options = {}): SymbolAndEntries[] | undefined {
if (node.kind === ts.SyntaxKind.SourceFile) {
return undefined;
}
@@ -269,6 +275,7 @@ namespace ts.FindAllReferences.Core {
}
}
const checker = program.getTypeChecker();
const symbol = checker.getSymbolAtLocation(node);
// Could not find a symbol e.g. unknown identifier
@@ -281,9 +288,65 @@ namespace ts.FindAllReferences.Core {
return undefined;
}
if (symbol.flags & SymbolFlags.Module && isModuleReferenceLocation(node)) {
return getReferencedSymbolsForModule(program, symbol, sourceFiles);
}
return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options);
}
function isModuleReferenceLocation(node: ts.Node): boolean {
if (node.kind !== SyntaxKind.StringLiteral) {
return false;
}
switch (node.parent.kind) {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ExternalModuleReference:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportDeclaration:
return true;
case SyntaxKind.CallExpression:
return isRequireCall(node.parent as CallExpression, /*checkArgumentIsStringLiteral*/ false);
default:
return false;
}
}
function getReferencedSymbolsForModule(program: Program, symbol: Symbol, sourceFiles: SourceFile[]): SymbolAndEntries[] {
Debug.assert(!!symbol.valueDeclaration);
const references = findModuleReferences(program, sourceFiles, symbol).map<Entry>(reference => {
if (reference.kind === "import") {
return { type: "node", node: reference.literal };
}
else {
return {
type: "span",
fileName: reference.referencingFile.fileName,
textSpan: createTextSpanFromRange(reference.ref),
};
}
});
for (const decl of symbol.declarations) {
switch (decl.kind) {
case ts.SyntaxKind.SourceFile:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case ts.SyntaxKind.ModuleDeclaration:
references.push({ type: "node", node: (decl as ts.ModuleDeclaration).name });
break;
default:
Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
}
}
return [{
definition: { type: "symbol", symbol, node: symbol.valueDeclaration },
references
}];
}
/** getReferencedSymbols for special node kinds. */
function getReferencedSymbolsSpecial(node: Node, sourceFiles: SourceFile[], cancellationToken: CancellationToken): SymbolAndEntries[] | undefined {
if (isTypeKeyword(node.kind)) {
@@ -550,7 +613,7 @@ namespace ts.FindAllReferences.Core {
}
function isObjectBindingPatternElementWithoutPropertyName(symbol: Symbol): boolean {
const bindingElement = <BindingElement>getDeclarationOfKind(symbol, SyntaxKind.BindingElement);
const bindingElement = getDeclarationOfKind<BindingElement>(symbol, SyntaxKind.BindingElement);
return bindingElement &&
bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern &&
!bindingElement.propertyName;
@@ -558,7 +621,7 @@ namespace ts.FindAllReferences.Core {
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined {
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
const bindingElement = <BindingElement>getDeclarationOfKind(symbol, SyntaxKind.BindingElement);
const bindingElement = getDeclarationOfKind<BindingElement>(symbol, SyntaxKind.BindingElement);
const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
return typeOfPattern && checker.getPropertyOfType(typeOfPattern, (<Identifier>bindingElement.name).text);
}
@@ -680,7 +743,7 @@ namespace ts.FindAllReferences.Core {
const labelName = targetLabel.text;
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container);
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
// Only pick labels that are either the target label, or have a target that is the target label
if (node && (node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel))) {
references.push(nodeEntry(node));
@@ -718,9 +781,10 @@ namespace ts.FindAllReferences.Core {
}
function addReferencesForKeywordInFile(sourceFile: SourceFile, kind: SyntaxKind, searchText: string, references: Push<NodeEntry>): void {
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText);
// Want fullStart so we can find the symbol in JSDoc comments
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile, /*fullStart*/ true);
for (const position of possiblePositions) {
const referenceLocation = getTouchingPropertyName(sourceFile, position);
const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (referenceLocation.kind === kind) {
references.push(nodeEntry(referenceLocation));
}
@@ -742,13 +806,13 @@ namespace ts.FindAllReferences.Core {
return;
}
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments)) {
for (const position of getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments || container.jsDoc !== undefined)) {
getReferencesAtLocation(sourceFile, position, search, state);
}
}
function getReferencesAtLocation(sourceFile: SourceFile, position: number, search: Search, state: State): void {
const referenceLocation = getTouchingPropertyName(sourceFile, position);
const referenceLocation = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
// This wasn't the start of a token. Check to see if it might be a
@@ -1188,7 +1252,7 @@ namespace ts.FindAllReferences.Core {
const sourceFile = searchSpaceNode.getSourceFile();
const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode);
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || node.kind !== SyntaxKind.SuperKeyword) {
continue;
@@ -1265,7 +1329,7 @@ namespace ts.FindAllReferences.Core {
function getThisReferencesInFile(sourceFile: SourceFile, searchSpaceNode: Node, possiblePositions: number[], result: Entry[]): void {
forEach(possiblePositions, position => {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (!node || !isThis(node)) {
return;
}
@@ -1319,7 +1383,7 @@ namespace ts.FindAllReferences.Core {
function getReferencesForStringLiteralInFile(sourceFile: SourceFile, searchText: string, possiblePositions: number[], references: Push<NodeEntry>): void {
for (const position of possiblePositions) {
const node = getTouchingWord(sourceFile, position);
const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false);
if (node && node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).text === searchText) {
references.push(nodeEntry(node, /*isInString*/ true));
}
+1 -1
View File
@@ -599,7 +599,7 @@ namespace ts.formatting {
child => {
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
},
(nodes: NodeArray<Node>) => {
nodes => {
processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
});
+10 -14
View File
@@ -19,7 +19,7 @@ namespace ts.GoToDefinition {
[getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
}
const node = getTouchingPropertyName(sourceFile, position);
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
return undefined;
}
@@ -95,7 +95,7 @@ namespace ts.GoToDefinition {
/// Goto type
export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] {
const node = getTouchingPropertyName(sourceFile, position);
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
return undefined;
}
@@ -165,7 +165,7 @@ namespace ts.GoToDefinition {
return result;
function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) {
function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) {
// Applicable only if we are in a new expression, or we are on a constructor declaration
// and in either case the symbol has a construct signature definition, i.e. class
if (isNewExpressionTarget(location) || location.kind === SyntaxKind.ConstructorKeyword) {
@@ -173,12 +173,8 @@ namespace ts.GoToDefinition {
// Find the first class-like declaration and try to get the construct signature.
for (const declaration of symbol.getDeclarations()) {
if (isClassLike(declaration)) {
return tryAddSignature(declaration.members,
/*selectConstructors*/ true,
symbolKind,
symbolName,
containerName,
result);
return tryAddSignature(
declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result);
}
}
@@ -188,14 +184,14 @@ namespace ts.GoToDefinition {
return false;
}
function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) {
function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) {
if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) {
return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result);
}
return false;
}
function tryAddSignature(signatureDeclarations: Declaration[] | undefined, selectConstructors: boolean, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) {
function tryAddSignature(signatureDeclarations: Declaration[] | undefined, selectConstructors: boolean, symbolKind: ScriptElementKind, symbolName: string, containerName: string, result: DefinitionInfo[]) {
if (!signatureDeclarations) {
return false;
}
@@ -231,12 +227,12 @@ namespace ts.GoToDefinition {
}
/** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */
function createDefinitionInfo(node: Declaration, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo {
function createDefinitionInfo(node: Declaration, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo {
return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName);
}
/** Creates a DefinitionInfo directly from the name of a declaration. */
function createDefinitionInfoFromName(name: Node, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo {
function createDefinitionInfoFromName(name: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo {
const sourceFile = name.getSourceFile();
return {
fileName: sourceFile.fileName,
@@ -263,7 +259,7 @@ namespace ts.GoToDefinition {
function findReferenceInPosition(refs: FileReference[], pos: number): FileReference {
for (const ref of refs) {
if (ref.pos <= pos && pos < ref.end) {
if (ref.pos <= pos && pos <= ref.end) {
return ref;
}
}
+35 -1
View File
@@ -300,6 +300,40 @@ namespace ts.FindAllReferences {
});
}
export type ModuleReference =
/** "import" also includes require() calls. */
| { kind: "import", literal: StringLiteral }
/** <reference path> or <reference types> */
| { kind: "reference", referencingFile: SourceFile, ref: FileReference };
export function findModuleReferences(program: Program, sourceFiles: SourceFile[], searchModuleSymbol: Symbol): ModuleReference[] {
const refs: ModuleReference[] = [];
const checker = program.getTypeChecker();
for (const referencingFile of sourceFiles) {
const searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === ts.SyntaxKind.SourceFile) {
for (const ref of referencingFile.referencedFiles) {
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
refs.push({ kind: "reference", referencingFile, ref });
}
}
for (const ref of referencingFile.typeReferenceDirectives) {
const referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName);
if (referenced !== undefined && referenced.resolvedFileName === (searchSourceFile as ts.SourceFile).fileName) {
refs.push({ kind: "reference", referencingFile, ref });
}
}
}
forEachImport(referencingFile, (_importDecl, moduleSpecifier) => {
const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
if (moduleSymbol === searchModuleSymbol) {
refs.push({ kind: "import", literal: moduleSpecifier });
}
});
}
return refs;
}
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken): Map<ImporterOrCallExpression[]> {
const map = createMap<ImporterOrCallExpression[]>();
@@ -371,7 +405,7 @@ namespace ts.FindAllReferences {
case SyntaxKind.ExternalModuleReference:
return (decl as ExternalModuleReference).parent;
default:
Debug.assert(false);
Debug.fail(`Unexpected module specifier parent: ${decl.kind}`);
}
}
+3 -3
View File
@@ -44,7 +44,7 @@ namespace ts.JsDoc {
let jsDocTagNameCompletionEntries: CompletionEntry[];
let jsDocTagCompletionEntries: CompletionEntry[];
export function getJsDocCommentsFromDeclarations(declarations: Declaration[]) {
export function getJsDocCommentsFromDeclarations(declarations?: Declaration[]) {
// Only collect doc comments from duplicate declarations once:
// In case of a union property there might be same declaration multiple times
// which only varies in type parameter
@@ -69,7 +69,7 @@ namespace ts.JsDoc {
return documentationComment;
}
export function getJsDocTagsFromDeclarations(declarations: Declaration[]) {
export function getJsDocTagsFromDeclarations(declarations?: Declaration[]) {
// Only collect doc comments from duplicate declarations once.
const tags: JSDocTagInfo[] = [];
forEachUnique(declarations, declaration => {
@@ -158,7 +158,7 @@ namespace ts.JsDoc {
return undefined;
}
const tokenAtPos = getTokenAtPosition(sourceFile, position);
const tokenAtPos = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
const tokenStart = tokenAtPos.getStart();
if (!tokenAtPos || tokenStart < position) {
return undefined;
+1 -1
View File
@@ -205,7 +205,7 @@ namespace ts.NavigateTo {
textSpan: createTextSpanFromNode(declaration),
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: containerName ? (<Identifier>containerName).text : "",
containerKind: containerName ? getNodeKind(container) : ""
containerKind: containerName ? getNodeKind(container) : ScriptElementKind.unknown
};
}
}
+8 -11
View File
@@ -245,18 +245,15 @@ namespace ts.Completions.PathCompletions {
// Get modules that the type checker picked up
const ambientModules = map(typeChecker.getAmbientModules(), sym => stripQuotes(sym.name));
let nonRelativeModules = filter(ambientModules, moduleName => startsWith(moduleName, fragment));
let nonRelativeModuleNames = filter(ambientModules, moduleName => startsWith(moduleName, fragment));
// Nested modules of the form "module-name/sub" need to be adjusted to only return the string
// after the last '/' that appears in the fragment because that's where the replacement span
// starts
if (isNestedModule) {
const moduleNameWithSeperator = ensureTrailingDirectorySeparator(moduleNameFragment);
nonRelativeModules = map(nonRelativeModules, moduleName => {
if (startsWith(fragment, moduleNameWithSeperator)) {
return moduleName.substr(moduleNameWithSeperator.length);
}
return moduleName;
nonRelativeModuleNames = map(nonRelativeModuleNames, nonRelativeModuleName => {
return removePrefix(nonRelativeModuleName, moduleNameWithSeperator);
});
}
@@ -264,7 +261,7 @@ namespace ts.Completions.PathCompletions {
if (!options.moduleResolution || options.moduleResolution === ModuleResolutionKind.NodeJs) {
for (const visibleModule of enumerateNodeModulesVisibleToScript(host, scriptPath)) {
if (!isNestedModule) {
nonRelativeModules.push(visibleModule.moduleName);
nonRelativeModuleNames.push(visibleModule.moduleName);
}
else if (startsWith(visibleModule.moduleName, moduleNameFragment)) {
const nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]);
@@ -272,18 +269,18 @@ namespace ts.Completions.PathCompletions {
for (let f of nestedFiles) {
f = normalizePath(f);
const nestedModule = removeFileExtension(getBaseFileName(f));
nonRelativeModules.push(nestedModule);
nonRelativeModuleNames.push(nestedModule);
}
}
}
}
}
return deduplicate(nonRelativeModules);
return deduplicate(nonRelativeModuleNames);
}
export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): CompletionInfo {
const token = getTokenAtPosition(sourceFile, position);
const token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false);
if (!token) {
return undefined;
}
@@ -458,7 +455,7 @@ namespace ts.Completions.PathCompletions {
}
}
function createCompletionEntryForModule(name: string, kind: string, replacementSpan: TextSpan): CompletionEntry {
function createCompletionEntryForModule(name: string, kind: ScriptElementKind, replacementSpan: TextSpan): CompletionEntry {
return { name, kind, kindModifiers: ScriptElementKindModifier.none, sortText: name, replacementSpan };
}
+69
View File
@@ -0,0 +1,69 @@
/* @internal */
namespace ts {
export interface Refactor {
/** An unique code associated with each refactor */
name: string;
/** Description of the refactor to display in the UI of the editor */
description: string;
/** Compute the associated code actions */
getCodeActions(context: RefactorContext): CodeAction[];
/** A fast syntactic check to see if the refactor is applicable at given position. */
isApplicable(context: RefactorContext): boolean;
}
export interface RefactorContext {
file: SourceFile;
startPosition: number;
endPosition?: number;
program: Program;
newLineCharacter: string;
rulesProvider?: formatting.RulesProvider;
cancellationToken?: CancellationToken;
}
export namespace refactor {
// A map with the refactor code as key, the refactor itself as value
// e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want
const refactors: Map<Refactor> = createMap<Refactor>();
export function registerRefactor(refactor: Refactor) {
refactors.set(refactor.name, refactor);
}
export function getApplicableRefactors(context: RefactorContext): ApplicableRefactorInfo[] | undefined {
let results: ApplicableRefactorInfo[];
const refactorList: Refactor[] = [];
refactors.forEach(refactor => {
refactorList.push(refactor);
});
for (const refactor of refactorList) {
if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) {
return results;
}
if (refactor.isApplicable(context)) {
(results || (results = [])).push({ name: refactor.name, description: refactor.description });
}
}
return results;
}
export function getRefactorCodeActions(context: RefactorContext, refactorName: string): CodeAction[] | undefined {
let result: CodeAction[];
const refactor = refactors.get(refactorName);
if (!refactor) {
return undefined;
}
const codeActions = refactor.getCodeActions(context);
if (codeActions) {
addRange((result || (result = [])), codeActions);
}
return result;
}
}
}
@@ -0,0 +1,209 @@
/* @internal */
namespace ts.refactor {
const convertFunctionToES6Class: Refactor = {
name: "Convert to ES2015 class",
description: Diagnostics.Convert_function_to_an_ES2015_class.message,
getCodeActions,
isApplicable
};
registerRefactor(convertFunctionToES6Class);
function isApplicable(context: RefactorContext): boolean {
const start = context.startPosition;
const node = getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false);
const checker = context.program.getTypeChecker();
let symbol = checker.getSymbolAtLocation(node);
if (symbol && isDeclarationOfFunctionOrClassExpression(symbol)) {
symbol = (symbol.valueDeclaration as VariableDeclaration).initializer.symbol;
}
return symbol && symbol.flags & SymbolFlags.Function && symbol.members && symbol.members.size > 0;
}
function getCodeActions(context: RefactorContext): CodeAction[] | undefined {
const start = context.startPosition;
const sourceFile = context.file;
const checker = context.program.getTypeChecker();
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const ctorSymbol = checker.getSymbolAtLocation(token);
const newLine = context.rulesProvider.getFormatOptions().newLineCharacter;
const deletedNodes: Node[] = [];
const deletes: (() => any)[] = [];
if (!(ctorSymbol.flags & (SymbolFlags.Function | SymbolFlags.Variable))) {
return [];
}
const ctorDeclaration = ctorSymbol.valueDeclaration;
const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context as { newLineCharacter: string, rulesProvider: formatting.RulesProvider });
let precedingNode: Node;
let newClassDeclaration: ClassDeclaration;
switch (ctorDeclaration.kind) {
case SyntaxKind.FunctionDeclaration:
precedingNode = ctorDeclaration;
deleteNode(ctorDeclaration);
newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration as FunctionDeclaration);
break;
case SyntaxKind.VariableDeclaration:
precedingNode = ctorDeclaration.parent.parent;
if ((<VariableDeclarationList>ctorDeclaration.parent).declarations.length === 1) {
deleteNode(precedingNode);
}
else {
deleteNode(ctorDeclaration, /*inList*/ true);
}
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration as VariableDeclaration);
break;
}
if (!newClassDeclaration) {
return [];
}
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine });
for (const deleteCallback of deletes) {
deleteCallback();
}
return [{
description: formatStringFromArgs(Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]),
changes: changeTracker.getChanges()
}];
function deleteNode(node: Node, inList = false) {
if (deletedNodes.some(n => isNodeDescendantOf(node, n))) {
// Parent node has already been deleted; do nothing
return;
}
deletedNodes.push(node);
if (inList) {
deletes.push(() => changeTracker.deleteNodeInList(sourceFile, node));
}
else {
deletes.push(() => changeTracker.deleteNode(sourceFile, node));
}
}
function createClassElementsFromSymbol(symbol: Symbol) {
const memberElements: ClassElement[] = [];
// all instance members are stored in the "member" array of symbol
if (symbol.members) {
symbol.members.forEach(member => {
const memberElement = createClassElement(member, /*modifiers*/ undefined);
if (memberElement) {
memberElements.push(memberElement);
}
});
}
// all static members are stored in the "exports" array of symbol
if (symbol.exports) {
symbol.exports.forEach(member => {
const memberElement = createClassElement(member, [createToken(SyntaxKind.StaticKeyword)]);
if (memberElement) {
memberElements.push(memberElement);
}
});
}
return memberElements;
function shouldConvertDeclaration(_target: PropertyAccessExpression, source: Expression) {
// Right now the only thing we can convert are function expressions - other values shouldn't get
// transformed. We can update this once ES public class properties are available.
return isFunctionLike(source);
}
function createClassElement(symbol: Symbol, modifiers: Modifier[]): ClassElement {
// both properties and methods are bound as property symbols
if (!(symbol.flags & SymbolFlags.Property)) {
return;
}
const memberDeclaration = symbol.valueDeclaration as PropertyAccessExpression;
const assignmentBinaryExpression = memberDeclaration.parent as BinaryExpression;
if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) {
return;
}
// delete the entire statement if this expression is the sole expression to take care of the semicolon at the end
const nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === SyntaxKind.ExpressionStatement
? assignmentBinaryExpression.parent : assignmentBinaryExpression;
deleteNode(nodeToDelete);
if (!assignmentBinaryExpression.right) {
return createProperty([], modifiers, symbol.name, /*questionToken*/ undefined,
/*type*/ undefined, /*initializer*/ undefined);
}
switch (assignmentBinaryExpression.right.kind) {
case SyntaxKind.FunctionExpression:
const functionExpression = assignmentBinaryExpression.right as FunctionExpression;
return createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
case SyntaxKind.ArrowFunction:
const arrowFunction = assignmentBinaryExpression.right as ArrowFunction;
const arrowFunctionBody = arrowFunction.body;
let bodyBlock: Block;
// case 1: () => { return [1,2,3] }
if (arrowFunctionBody.kind === SyntaxKind.Block) {
bodyBlock = arrowFunctionBody as Block;
}
// case 2: () => [1,2,3]
else {
const expression = arrowFunctionBody as Expression;
bodyBlock = createBlock([createReturn(expression)]);
}
return createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
default:
// Don't try to declare members in JavaScript files
if (isSourceFileJavaScript(sourceFile)) {
return;
}
return createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
}
}
}
function createClassFromVariableDeclaration(node: VariableDeclaration): ClassDeclaration {
const initializer = node.initializer as FunctionExpression;
if (!initializer || initializer.kind !== SyntaxKind.FunctionExpression) {
return undefined;
}
if (node.name.kind !== SyntaxKind.Identifier) {
return undefined;
}
const memberElements = createClassElementsFromSymbol(initializer.symbol);
if (initializer.body) {
memberElements.unshift(createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body));
}
return createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name,
/*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
}
function createClassFromFunctionDeclaration(node: FunctionDeclaration): ClassDeclaration {
const memberElements = createClassElementsFromSymbol(ctorSymbol);
if (node.body) {
memberElements.unshift(createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, node.parameters, node.body));
}
return createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name,
/*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements);
}
}
}
+1
View File
@@ -0,0 +1 @@
/// <reference path="convertFunctionToEs6Class.ts" />
+1 -1
View File
@@ -53,7 +53,7 @@ namespace ts.Rename {
}
}
function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo {
function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo {
return {
canRename: true,
kind,
+74 -31
View File
@@ -25,7 +25,9 @@
/// <reference path='formatting\smartIndenter.ts' />
/// <reference path='textChanges.ts' />
/// <reference path='codeFixProvider.ts' />
/// <reference path='refactorProvider.ts' />
/// <reference path='codefixes\fixes.ts' />
/// <reference path='refactors\refactors.ts' />
namespace ts {
/** The version of the language service API */
@@ -105,6 +107,7 @@ namespace ts {
scanner.setTextPos(pos);
while (pos < end) {
const token = useJSDocScanner ? scanner.scanJSDocToken() : scanner.scan();
Debug.assert(token !== SyntaxKind.EndOfFileToken); // Else it would infinitely loop
const textPos = scanner.getTextPos();
if (textPos <= end) {
nodes.push(createNode(token, pos, textPos, this));
@@ -133,10 +136,15 @@ namespace ts {
}
private createChildren(sourceFile?: SourceFileLike) {
let children: Node[];
if (this.kind >= SyntaxKind.FirstNode) {
if (isJSDocTag(this)) {
/** Don't add trivia for "tokens" since this is in a comment. */
const children: Node[] = [];
this.forEachChild(child => { children.push(child); });
this._children = children;
}
else if (this.kind >= SyntaxKind.FirstNode) {
const children: Node[] = [];
scanner.setText((sourceFile || this.getSourceFile()).text);
children = [];
let pos = this.pos;
const useJSDocScanner = this.kind >= SyntaxKind.FirstJSDocTagNode && this.kind <= SyntaxKind.LastJSDocTagNode;
const processNode = (node: Node) => {
@@ -153,7 +161,7 @@ namespace ts {
if (pos < nodes.pos) {
pos = this.addSyntheticNodes(children, pos, nodes.pos, useJSDocScanner);
}
children.push(this.createSyntaxList(<NodeArray<Node>>nodes));
children.push(this.createSyntaxList(nodes));
pos = nodes.end;
};
// jsDocComments need to be the first children
@@ -171,8 +179,11 @@ namespace ts {
this.addSyntheticNodes(children, pos, this.end);
}
scanner.setText(undefined);
this._children = children;
}
else {
this._children = emptyArray;
}
this._children = children || emptyArray;
}
public getChildCount(sourceFile?: SourceFile): number {
@@ -213,7 +224,7 @@ namespace ts {
return child.kind < SyntaxKind.FirstNode ? child : child.getLastToken(sourceFile);
}
public forEachChild<T>(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T {
public forEachChild<T>(cbNode: (node: Node) => T, cbNodeArray?: (nodes: NodeArray<Node>) => T): T {
return forEachChild(this, cbNode, cbNodeArray);
}
}
@@ -298,15 +309,15 @@ namespace ts {
class SymbolObject implements Symbol {
flags: SymbolFlags;
name: string;
declarations: Declaration[];
declarations?: Declaration[];
// Undefined is used to indicate the value has not been computed. If, after computing, the
// symbol has no doc comment, then the empty string will be returned.
documentationComment: SymbolDisplayPart[];
// symbol has no doc comment, then the empty array will be returned.
documentationComment?: SymbolDisplayPart[];
// Undefined is used to indicate the value has not been computed. If, after computing, the
// symbol has no JSDoc tags, then the empty array will be returned.
tags: JSDocTagInfo[];
tags?: JSDocTagInfo[];
constructor(flags: SymbolFlags, name: string) {
this.flags = flags;
@@ -321,7 +332,7 @@ namespace ts {
return this.name;
}
getDeclarations(): Declaration[] {
getDeclarations(): Declaration[] | undefined {
return this.declarations;
}
@@ -360,6 +371,7 @@ namespace ts {
_incrementExpressionBrand: any;
_unaryExpressionBrand: any;
_expressionBrand: any;
/*@internal*/typeArguments: NodeArray<TypeNode>;
constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) {
super(pos, end);
}
@@ -371,7 +383,7 @@ namespace ts {
flags: TypeFlags;
objectFlags?: ObjectFlags;
id: number;
symbol: Symbol;
symbol?: Symbol;
constructor(checker: TypeChecker, flags: TypeFlags) {
this.checker = checker;
this.flags = flags;
@@ -379,13 +391,13 @@ namespace ts {
getFlags(): TypeFlags {
return this.flags;
}
getSymbol(): Symbol {
getSymbol(): Symbol | undefined {
return this.symbol;
}
getProperties(): Symbol[] {
return this.checker.getPropertiesOfType(this);
}
getProperty(propertyName: string): Symbol {
getProperty(propertyName: string): Symbol | undefined {
return this.checker.getPropertyOfType(this, propertyName);
}
getApparentProperties(): Symbol[] {
@@ -397,13 +409,13 @@ namespace ts {
getConstructSignatures(): Signature[] {
return this.checker.getSignaturesOfType(this, SignatureKind.Construct);
}
getStringIndexType(): Type {
getStringIndexType(): Type | undefined {
return this.checker.getIndexTypeOfType(this, IndexKind.String);
}
getNumberIndexType(): Type {
getNumberIndexType(): Type | undefined {
return this.checker.getIndexTypeOfType(this, IndexKind.Number);
}
getBaseTypes(): BaseType[] {
getBaseTypes(): BaseType[] | undefined {
return this.flags & TypeFlags.Object && this.objectFlags & (ObjectFlags.Class | ObjectFlags.Interface)
? this.checker.getBaseTypes(<InterfaceType><Type>this)
: undefined;
@@ -416,7 +428,7 @@ namespace ts {
class SignatureObject implements Signature {
checker: TypeChecker;
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
typeParameters?: TypeParameter[];
parameters: Symbol[];
thisParameter: Symbol;
resolvedReturnType: Type;
@@ -426,12 +438,12 @@ namespace ts {
hasLiteralTypes: boolean;
// Undefined is used to indicate the value has not been computed. If, after computing, the
// symbol has no doc comment, then the empty string will be returned.
documentationComment: SymbolDisplayPart[];
// symbol has no doc comment, then the empty array will be returned.
documentationComment?: SymbolDisplayPart[];
// Undefined is used to indicate the value has not been computed. If, after computing, the
// symbol has no doc comment, then the empty array will be returned.
jsDocTags: JSDocTagInfo[];
jsDocTags?: JSDocTagInfo[];
constructor(checker: TypeChecker) {
this.checker = checker;
@@ -439,7 +451,7 @@ namespace ts {
getDeclaration(): SignatureDeclaration {
return this.declaration;
}
getTypeParameters(): TypeParameter[] {
getTypeParameters(): TypeParameter[] | undefined {
return this.typeParameters;
}
getParameters(): Symbol[] {
@@ -1365,7 +1377,7 @@ namespace ts {
synchronizeHostData();
const sourceFile = getValidSourceFile(fileName);
const node = getTouchingPropertyName(sourceFile, position);
const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (node === sourceFile) {
return undefined;
}
@@ -1428,7 +1440,7 @@ namespace ts {
/// Goto implementation
function getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] {
synchronizeHostData();
return FindAllReferences.getImplementationsAtPosition(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
return FindAllReferences.getImplementationsAtPosition(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
}
/// References and Occurrences
@@ -1450,7 +1462,7 @@ namespace ts {
synchronizeHostData();
const sourceFilesToSearch = map(filesToSearch, f => program.getSourceFile(f));
const sourceFile = getValidSourceFile(fileName);
return DocumentHighlights.getDocumentHighlights(program.getTypeChecker(), cancellationToken, sourceFile, position, sourceFilesToSearch);
return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
}
function getOccurrencesAtPositionCore(fileName: string, position: number): ReferenceEntry[] {
@@ -1488,12 +1500,12 @@ namespace ts {
function getReferences(fileName: string, position: number, options?: FindAllReferences.Options) {
synchronizeHostData();
return FindAllReferences.findReferencedEntries(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options);
return FindAllReferences.findReferencedEntries(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, options);
}
function findReferences(fileName: string, position: number): ReferencedSymbol[] {
synchronizeHostData();
return FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
return FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position);
}
/// NavigateTo
@@ -1552,7 +1564,7 @@ namespace ts {
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
// Get node at the location
const node = getTouchingPropertyName(sourceFile, startPos);
const node = getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false);
if (node === sourceFile) {
return;
@@ -1663,7 +1675,7 @@ namespace ts {
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
const result: TextSpan[] = [];
const token = getTouchingToken(sourceFile, position);
const token = getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false);
if (token.getStart(sourceFile) === position) {
const matchKind = getMatchingTokenKind(token);
@@ -1865,8 +1877,7 @@ namespace ts {
// OK, we have found a match in the file. This is only an acceptable match if
// it is contained within a comment.
const token = getTokenAtPosition(sourceFile, matchPosition);
if (!isInsideComment(sourceFile, token, matchPosition)) {
if (!isInComment(sourceFile, matchPosition)) {
continue;
}
@@ -1970,11 +1981,43 @@ namespace ts {
return Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position);
}
function getRefactorContext(file: SourceFile, positionOrRange: number | TextRange, formatOptions?: FormatCodeSettings): RefactorContext {
const [startPosition, endPosition] = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end];
return {
file,
startPosition,
endPosition,
program: getProgram(),
newLineCharacter: host.getNewLine(),
rulesProvider: getRuleProvider(formatOptions),
cancellationToken
};
}
function getApplicableRefactors(fileName: string, positionOrRange: number | TextRange): ApplicableRefactorInfo[] {
synchronizeHostData();
const file = getValidSourceFile(fileName);
return refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange));
}
function getRefactorCodeActions(
fileName: string,
formatOptions: FormatCodeSettings,
positionOrRange: number | TextRange,
refactorName: string): CodeAction[] | undefined {
synchronizeHostData();
const file = getValidSourceFile(fileName);
return refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName);
}
return {
dispose,
cleanupSemanticCache,
getSyntacticDiagnostics,
getSemanticDiagnostics,
getApplicableRefactors,
getRefactorCodeActions,
getCompilerOptionsDiagnostics,
getSyntacticClassifications,
getSemanticClassifications,
+8 -7
View File
@@ -1,7 +1,7 @@
/* @internal */
namespace ts.SymbolDisplay {
// TODO(drosen): use contextual SemanticMeaning.
export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): string {
export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind {
const { flags } = symbol;
if (flags & SymbolFlags.Class) return getDeclarationOfKind(symbol, SyntaxKind.ClassExpression) ?
@@ -22,7 +22,7 @@ namespace ts.SymbolDisplay {
return result;
}
function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node) {
function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind {
if (typeChecker.isUndefinedSymbol(symbol)) {
return ScriptElementKind.variableElement;
}
@@ -275,7 +275,7 @@ namespace ts.SymbolDisplay {
}
if (symbolFlags & SymbolFlags.Module) {
addNewLineIfDisplayPartsExist();
const declaration = <ModuleDeclaration>getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration);
const declaration = getDeclarationOfKind<ModuleDeclaration>(symbol, SyntaxKind.ModuleDeclaration);
const isNamespace = declaration && declaration.name && declaration.name.kind === SyntaxKind.Identifier;
displayParts.push(keywordPart(isNamespace ? SyntaxKind.NamespaceKeyword : SyntaxKind.ModuleKeyword));
displayParts.push(spacePart());
@@ -296,9 +296,9 @@ namespace ts.SymbolDisplay {
}
else {
// Method/function type parameter
let declaration = <Node>getDeclarationOfKind(symbol, SyntaxKind.TypeParameter);
Debug.assert(declaration !== undefined);
declaration = declaration.parent;
const decl = getDeclarationOfKind(symbol, SyntaxKind.TypeParameter);
Debug.assert(decl !== undefined);
const declaration = decl.parent;
if (declaration) {
if (isFunctionLikeKind(declaration.kind)) {
@@ -336,7 +336,8 @@ namespace ts.SymbolDisplay {
displayParts.push(spacePart());
displayParts.push(operatorPart(SyntaxKind.EqualsToken));
displayParts.push(spacePart());
displayParts.push(displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral));
displayParts.push(displayPart(getTextOfConstantValue(constantValue),
typeof constantValue === "number" ? SymbolDisplayPartKind.numericLiteral : SymbolDisplayPartKind.stringLiteral));
}
}
}
+22 -30
View File
@@ -157,7 +157,7 @@ namespace ts.textChanges {
private changes: Change[] = [];
private readonly newLineCharacter: string;
public static fromCodeFixContext(context: CodeFixContext) {
public static fromCodeFixContext(context: { newLineCharacter: string, rulesProvider: formatting.RulesProvider }) {
return new ChangeTracker(context.newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed, context.rulesProvider);
}
@@ -202,7 +202,7 @@ namespace ts.textChanges {
return this;
}
if (index !== containingList.length - 1) {
const nextToken = getTokenAtPosition(sourceFile, node.end);
const nextToken = getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false);
if (nextToken && isSeparator(node, nextToken)) {
// find first non-whitespace position in the leading trivia of the node
const startPosition = skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
@@ -214,7 +214,7 @@ namespace ts.textChanges {
}
}
else {
const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end);
const previousToken = getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false);
if (previousToken && isSeparator(node, previousToken)) {
this.deleteNodeRange(sourceFile, previousToken, node);
}
@@ -254,9 +254,9 @@ namespace ts.textChanges {
public insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node, options: InsertNodeOptions & ConfigurableEnd = {}) {
if ((isStatementButNotDeclaration(after)) ||
after.kind === SyntaxKind.PropertyDeclaration ||
after.kind === SyntaxKind.PropertySignature ||
after.kind === SyntaxKind.MethodSignature) {
after.kind === SyntaxKind.PropertyDeclaration ||
after.kind === SyntaxKind.PropertySignature ||
after.kind === SyntaxKind.MethodSignature) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
if (sourceFile.text.charCodeAt(after.end - 1) !== CharacterCodes.semicolon) {
@@ -292,7 +292,7 @@ namespace ts.textChanges {
if (index !== containingList.length - 1) {
// any element except the last one
// use next sibling as an anchor
const nextToken = getTokenAtPosition(sourceFile, after.end);
const nextToken = getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false);
if (nextToken && isSeparator(after, nextToken)) {
// for list
// a, b, c
@@ -481,7 +481,7 @@ namespace ts.textChanges {
return (options.prefix || "") + text + (options.suffix || "");
}
private static normalize(changes: Change[]) {
private static normalize(changes: Change[]): Change[] {
// order changes by start position
const normalized = stableSort(changes, (a, b) => a.range.pos - b.range.pos);
// verify that change intervals do not overlap, except possibly at end points.
@@ -497,8 +497,8 @@ namespace ts.textChanges {
readonly node: Node;
}
export function getNonformattedText(node: Node, sourceFile: SourceFile, newLine: NewLineKind): NonFormattedText {
const options = { newLine, target: sourceFile.languageVersion };
export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLine: NewLineKind): NonFormattedText {
const options = { newLine, target: sourceFile && sourceFile.languageVersion };
const writer = new Writer(getNewLineCharacter(options));
const printer = createPrinter(options, writer);
printer.writeNode(EmitHint.Unspecified, node, sourceFile, writer);
@@ -528,26 +528,6 @@ namespace ts.textChanges {
return skipTrivia(s, 0) === s.length;
}
const nullTransformationContext: TransformationContext = {
enableEmitNotification: noop,
enableSubstitution: noop,
endLexicalEnvironment: () => undefined,
getCompilerOptions: notImplemented,
getEmitHost: notImplemented,
getEmitResolver: notImplemented,
hoistFunctionDeclaration: noop,
hoistVariableDeclaration: noop,
isEmitNotificationEnabled: notImplemented,
isSubstitutionEnabled: notImplemented,
onEmitNode: noop,
onSubstituteNode: notImplemented,
readEmitHelpers: notImplemented,
requestEmitHelper: noop,
resumeLexicalEnvironment: noop,
startLexicalEnvironment: noop,
suspendLexicalEnvironment: noop
};
function assignPositionsToNode(node: Node): Node {
const visited = visitEachChild(node, assignPositionsToNode, nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode);
// create proxy node for non synthesized nodes
@@ -580,6 +560,8 @@ namespace ts.textChanges {
public readonly onEmitNode: PrintHandlers["onEmitNode"];
public readonly onBeforeEmitNodeArray: PrintHandlers["onBeforeEmitNodeArray"];
public readonly onAfterEmitNodeArray: PrintHandlers["onAfterEmitNodeArray"];
public readonly onBeforeEmitToken: PrintHandlers["onBeforeEmitToken"];
public readonly onAfterEmitToken: PrintHandlers["onAfterEmitToken"];
constructor(newLine: string) {
this.writer = createTextWriter(newLine);
@@ -602,6 +584,16 @@ namespace ts.textChanges {
setEnd(nodes, this.lastNonTriviaPosition);
}
};
this.onBeforeEmitToken = node => {
if (node) {
setPos(node, this.lastNonTriviaPosition);
}
};
this.onAfterEmitToken = node => {
if (node) {
setEnd(node, this.lastNonTriviaPosition);
}
};
}
private setLastNonTriviaPosition(s: string, force: boolean) {

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