Merge branch 'master' into testPerf

Conflicts:
	src/harness/harness.ts
This commit is contained in:
Daniel Rosenwasser
2015-05-04 15:16:36 -07:00
869 changed files with 27637 additions and 12736 deletions
+1
View File
@@ -46,3 +46,4 @@ scripts/*.js.map
coverage/
internal/
**/.DS_Store
.settings/
+2 -1
View File
@@ -4,4 +4,5 @@ scripts
src
tests
Jakefile
.travis.yml
.travis.yml
.settings/
+52 -18
View File
@@ -1237,11 +1237,41 @@ interface SymbolConstructor {
isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object.Called by the semantics of the
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
split: symbol;
/**
* A method that converts an object to a corresponding primitive value.Called by the ToPrimitive
* abstract operation.
@@ -4728,6 +4758,16 @@ declare module Reflect {
function setPrototypeOf(target: any, proto: any): boolean;
}
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
}
/**
* Represents the completion of an asynchronous operation
*/
@@ -4738,14 +4778,16 @@ interface Promise<T> {
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | Promise<TResult>, onrejected?: (reason: any) => TResult | Promise<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | Promise<T>): Promise<T>;
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
[Symbol.toStringTag]: string;
}
interface PromiseConstructor {
@@ -4756,13 +4798,11 @@ interface PromiseConstructor {
/**
* Creates a new Promise.
* @param init A callback used to initialize the promise. This callback is passed two arguments:
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(init: (resolve: (value?: T | Promise<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
<T>(init: (resolve: (value?: T | Promise<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -4770,15 +4810,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of values.
* @returns A new Promise.
*/
all(values: Promise<void>[]): Promise<void>;
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
@@ -4786,7 +4818,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: (T | Promise<T>)[]): Promise<T>;
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
/**
* Creates a new rejected promise for the provided reason.
@@ -4807,13 +4839,15 @@ interface PromiseConstructor {
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | Promise<T>): Promise<T>;
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
[Symbol.species]: Function;
}
declare var Promise: PromiseConstructor;
+143
View File
@@ -1231,6 +1231,139 @@ interface ArrayBufferView {
byteOffset: number;
}
interface DataView {
buffer: ArrayBuffer;
byteLength: number;
byteOffset: number;
/**
* Gets the Float32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Float64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat64(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt8(byteOffset: number): number;
/**
* Gets the Int16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint8(byteOffset: number): number;
/**
* Gets the Uint16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint32(byteOffset: number, littleEndian: boolean): number;
/**
* Stores an Float32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Float64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat64(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setInt8(byteOffset: number, value: number): void;
/**
* Stores an Int16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setUint8(byteOffset: number, value: number): void;
/**
* Stores an Uint16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint32(byteOffset: number, value: number, littleEndian: boolean): void;
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
}
declare var DataView: DataViewConstructor;
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
@@ -7222,6 +7355,8 @@ interface HTMLCanvasElement extends HTMLElement {
* Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.
* @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl");
*/
getContext(contextId: "2d"): CanvasRenderingContext2D;
getContext(contextId: "experimental-webgl"): WebGLRenderingContext;
getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext;
/**
* Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.
@@ -15857,11 +15992,13 @@ interface DocumentEvent {
createEvent(eventInterface:"CloseEvent"): CloseEvent;
createEvent(eventInterface:"CommandEvent"): CommandEvent;
createEvent(eventInterface:"CompositionEvent"): CompositionEvent;
createEvent(eventInterface: "CustomEvent"): CustomEvent;
createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent;
createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent;
createEvent(eventInterface:"DragEvent"): DragEvent;
createEvent(eventInterface:"ErrorEvent"): ErrorEvent;
createEvent(eventInterface:"Event"): Event;
createEvent(eventInterface:"Events"): Event;
createEvent(eventInterface:"FocusEvent"): FocusEvent;
createEvent(eventInterface:"GamepadEvent"): GamepadEvent;
createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent;
@@ -15876,8 +16013,12 @@ interface DocumentEvent {
createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent;
createEvent(eventInterface:"MessageEvent"): MessageEvent;
createEvent(eventInterface:"MouseEvent"): MouseEvent;
createEvent(eventInterface:"MouseEvents"): MouseEvent;
createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent;
createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent;
createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent;
createEvent(eventInterface:"MutationEvent"): MutationEvent;
createEvent(eventInterface:"MutationEvents"): MutationEvent;
createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent;
createEvent(eventInterface:"NavigationEvent"): NavigationEvent;
createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer;
@@ -15888,6 +16029,7 @@ interface DocumentEvent {
createEvent(eventInterface:"PopStateEvent"): PopStateEvent;
createEvent(eventInterface:"ProgressEvent"): ProgressEvent;
createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent;
createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent;
createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent;
createEvent(eventInterface:"StorageEvent"): StorageEvent;
createEvent(eventInterface:"TextEvent"): TextEvent;
@@ -15895,6 +16037,7 @@ interface DocumentEvent {
createEvent(eventInterface:"TrackEvent"): TrackEvent;
createEvent(eventInterface:"TransitionEvent"): TransitionEvent;
createEvent(eventInterface:"UIEvent"): UIEvent;
createEvent(eventInterface:"UIEvents"): UIEvent;
createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent;
createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent;
createEvent(eventInterface:"WheelEvent"): WheelEvent;
+143
View File
@@ -61,6 +61,139 @@ interface ArrayBufferView {
byteOffset: number;
}
interface DataView {
buffer: ArrayBuffer;
byteLength: number;
byteOffset: number;
/**
* Gets the Float32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Float64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat64(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt8(byteOffset: number): number;
/**
* Gets the Int16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint8(byteOffset: number): number;
/**
* Gets the Uint16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint32(byteOffset: number, littleEndian: boolean): number;
/**
* Stores an Float32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Float64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat64(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setInt8(byteOffset: number, value: number): void;
/**
* Stores an Int16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setUint8(byteOffset: number, value: number): void;
/**
* Stores an Uint16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint32(byteOffset: number, value: number, littleEndian: boolean): void;
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
}
declare var DataView: DataViewConstructor;
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
@@ -6052,6 +6185,8 @@ interface HTMLCanvasElement extends HTMLElement {
* Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.
* @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl");
*/
getContext(contextId: "2d"): CanvasRenderingContext2D;
getContext(contextId: "experimental-webgl"): WebGLRenderingContext;
getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext;
/**
* Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.
@@ -14687,11 +14822,13 @@ interface DocumentEvent {
createEvent(eventInterface:"CloseEvent"): CloseEvent;
createEvent(eventInterface:"CommandEvent"): CommandEvent;
createEvent(eventInterface:"CompositionEvent"): CompositionEvent;
createEvent(eventInterface: "CustomEvent"): CustomEvent;
createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent;
createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent;
createEvent(eventInterface:"DragEvent"): DragEvent;
createEvent(eventInterface:"ErrorEvent"): ErrorEvent;
createEvent(eventInterface:"Event"): Event;
createEvent(eventInterface:"Events"): Event;
createEvent(eventInterface:"FocusEvent"): FocusEvent;
createEvent(eventInterface:"GamepadEvent"): GamepadEvent;
createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent;
@@ -14706,8 +14843,12 @@ interface DocumentEvent {
createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent;
createEvent(eventInterface:"MessageEvent"): MessageEvent;
createEvent(eventInterface:"MouseEvent"): MouseEvent;
createEvent(eventInterface:"MouseEvents"): MouseEvent;
createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent;
createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent;
createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent;
createEvent(eventInterface:"MutationEvent"): MutationEvent;
createEvent(eventInterface:"MutationEvents"): MutationEvent;
createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent;
createEvent(eventInterface:"NavigationEvent"): NavigationEvent;
createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer;
@@ -14718,6 +14859,7 @@ interface DocumentEvent {
createEvent(eventInterface:"PopStateEvent"): PopStateEvent;
createEvent(eventInterface:"ProgressEvent"): ProgressEvent;
createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent;
createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent;
createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent;
createEvent(eventInterface:"StorageEvent"): StorageEvent;
createEvent(eventInterface:"TextEvent"): TextEvent;
@@ -14725,6 +14867,7 @@ interface DocumentEvent {
createEvent(eventInterface:"TrackEvent"): TrackEvent;
createEvent(eventInterface:"TransitionEvent"): TransitionEvent;
createEvent(eventInterface:"UIEvent"): UIEvent;
createEvent(eventInterface:"UIEvents"): UIEvent;
createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent;
createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent;
createEvent(eventInterface:"WheelEvent"): WheelEvent;
+62 -18
View File
@@ -1237,11 +1237,41 @@ interface SymbolConstructor {
isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object.Called by the semantics of the
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
split: symbol;
/**
* A method that converts an object to a corresponding primitive value.Called by the ToPrimitive
* abstract operation.
@@ -4728,6 +4758,16 @@ declare module Reflect {
function setPrototypeOf(target: any, proto: any): boolean;
}
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
}
/**
* Represents the completion of an asynchronous operation
*/
@@ -4738,14 +4778,16 @@ interface Promise<T> {
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | Promise<TResult>, onrejected?: (reason: any) => TResult | Promise<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | Promise<T>): Promise<T>;
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
[Symbol.toStringTag]: string;
}
interface PromiseConstructor {
@@ -4756,13 +4798,11 @@ interface PromiseConstructor {
/**
* Creates a new Promise.
* @param init A callback used to initialize the promise. This callback is passed two arguments:
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(init: (resolve: (value?: T | Promise<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
<T>(init: (resolve: (value?: T | Promise<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -4770,15 +4810,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of values.
* @returns A new Promise.
*/
all(values: Promise<void>[]): Promise<void>;
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
@@ -4786,7 +4818,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: (T | Promise<T>)[]): Promise<T>;
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
/**
* Creates a new rejected promise for the provided reason.
@@ -4807,13 +4839,15 @@ interface PromiseConstructor {
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | Promise<T>): Promise<T>;
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
[Symbol.species]: Function;
}
declare var Promise: PromiseConstructor;
@@ -8700,6 +8734,8 @@ interface HTMLCanvasElement extends HTMLElement {
* Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.
* @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl");
*/
getContext(contextId: "2d"): CanvasRenderingContext2D;
getContext(contextId: "experimental-webgl"): WebGLRenderingContext;
getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext;
/**
* Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.
@@ -17335,11 +17371,13 @@ interface DocumentEvent {
createEvent(eventInterface:"CloseEvent"): CloseEvent;
createEvent(eventInterface:"CommandEvent"): CommandEvent;
createEvent(eventInterface:"CompositionEvent"): CompositionEvent;
createEvent(eventInterface: "CustomEvent"): CustomEvent;
createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent;
createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent;
createEvent(eventInterface:"DragEvent"): DragEvent;
createEvent(eventInterface:"ErrorEvent"): ErrorEvent;
createEvent(eventInterface:"Event"): Event;
createEvent(eventInterface:"Events"): Event;
createEvent(eventInterface:"FocusEvent"): FocusEvent;
createEvent(eventInterface:"GamepadEvent"): GamepadEvent;
createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent;
@@ -17354,8 +17392,12 @@ interface DocumentEvent {
createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent;
createEvent(eventInterface:"MessageEvent"): MessageEvent;
createEvent(eventInterface:"MouseEvent"): MouseEvent;
createEvent(eventInterface:"MouseEvents"): MouseEvent;
createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent;
createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent;
createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent;
createEvent(eventInterface:"MutationEvent"): MutationEvent;
createEvent(eventInterface:"MutationEvents"): MutationEvent;
createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent;
createEvent(eventInterface:"NavigationEvent"): NavigationEvent;
createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer;
@@ -17366,6 +17408,7 @@ interface DocumentEvent {
createEvent(eventInterface:"PopStateEvent"): PopStateEvent;
createEvent(eventInterface:"ProgressEvent"): ProgressEvent;
createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent;
createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent;
createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent;
createEvent(eventInterface:"StorageEvent"): StorageEvent;
createEvent(eventInterface:"TextEvent"): TextEvent;
@@ -17373,6 +17416,7 @@ interface DocumentEvent {
createEvent(eventInterface:"TrackEvent"): TrackEvent;
createEvent(eventInterface:"TransitionEvent"): TransitionEvent;
createEvent(eventInterface:"UIEvent"): UIEvent;
createEvent(eventInterface:"UIEvents"): UIEvent;
createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent;
createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent;
createEvent(eventInterface:"WheelEvent"): WheelEvent;
+133
View File
@@ -61,6 +61,139 @@ interface ArrayBufferView {
byteOffset: number;
}
interface DataView {
buffer: ArrayBuffer;
byteLength: number;
byteOffset: number;
/**
* Gets the Float32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Float64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat64(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt8(byteOffset: number): number;
/**
* Gets the Int16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint8(byteOffset: number): number;
/**
* Gets the Uint16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint32(byteOffset: number, littleEndian: boolean): number;
/**
* Stores an Float32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Float64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat64(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setInt8(byteOffset: number, value: number): void;
/**
* Stores an Int16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setUint8(byteOffset: number, value: number): void;
/**
* Stores an Uint16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint32(byteOffset: number, value: number, littleEndian: boolean): void;
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
}
declare var DataView: DataViewConstructor;
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
+2614 -1941
View File
File diff suppressed because it is too large Load Diff
+3490 -2718
View File
File diff suppressed because it is too large Load Diff
+181 -125
View File
@@ -140,132 +140,133 @@ declare module "typescript" {
DeclareKeyword = 115,
GetKeyword = 116,
ModuleKeyword = 117,
RequireKeyword = 118,
NumberKeyword = 119,
SetKeyword = 120,
StringKeyword = 121,
SymbolKeyword = 122,
TypeKeyword = 123,
FromKeyword = 124,
OfKeyword = 125,
QualifiedName = 126,
ComputedPropertyName = 127,
TypeParameter = 128,
Parameter = 129,
Decorator = 130,
PropertySignature = 131,
PropertyDeclaration = 132,
MethodSignature = 133,
MethodDeclaration = 134,
Constructor = 135,
GetAccessor = 136,
SetAccessor = 137,
CallSignature = 138,
ConstructSignature = 139,
IndexSignature = 140,
TypeReference = 141,
FunctionType = 142,
ConstructorType = 143,
TypeQuery = 144,
TypeLiteral = 145,
ArrayType = 146,
TupleType = 147,
UnionType = 148,
ParenthesizedType = 149,
ObjectBindingPattern = 150,
ArrayBindingPattern = 151,
BindingElement = 152,
ArrayLiteralExpression = 153,
ObjectLiteralExpression = 154,
PropertyAccessExpression = 155,
ElementAccessExpression = 156,
CallExpression = 157,
NewExpression = 158,
TaggedTemplateExpression = 159,
TypeAssertionExpression = 160,
ParenthesizedExpression = 161,
FunctionExpression = 162,
ArrowFunction = 163,
DeleteExpression = 164,
TypeOfExpression = 165,
VoidExpression = 166,
PrefixUnaryExpression = 167,
PostfixUnaryExpression = 168,
BinaryExpression = 169,
ConditionalExpression = 170,
TemplateExpression = 171,
YieldExpression = 172,
SpreadElementExpression = 173,
ClassExpression = 174,
OmittedExpression = 175,
TemplateSpan = 176,
HeritageClauseElement = 177,
SemicolonClassElement = 178,
Block = 179,
VariableStatement = 180,
EmptyStatement = 181,
ExpressionStatement = 182,
IfStatement = 183,
DoStatement = 184,
WhileStatement = 185,
ForStatement = 186,
ForInStatement = 187,
ForOfStatement = 188,
ContinueStatement = 189,
BreakStatement = 190,
ReturnStatement = 191,
WithStatement = 192,
SwitchStatement = 193,
LabeledStatement = 194,
ThrowStatement = 195,
TryStatement = 196,
DebuggerStatement = 197,
VariableDeclaration = 198,
VariableDeclarationList = 199,
FunctionDeclaration = 200,
ClassDeclaration = 201,
InterfaceDeclaration = 202,
TypeAliasDeclaration = 203,
EnumDeclaration = 204,
ModuleDeclaration = 205,
ModuleBlock = 206,
CaseBlock = 207,
ImportEqualsDeclaration = 208,
ImportDeclaration = 209,
ImportClause = 210,
NamespaceImport = 211,
NamedImports = 212,
ImportSpecifier = 213,
ExportAssignment = 214,
ExportDeclaration = 215,
NamedExports = 216,
ExportSpecifier = 217,
MissingDeclaration = 218,
ExternalModuleReference = 219,
CaseClause = 220,
DefaultClause = 221,
HeritageClause = 222,
CatchClause = 223,
PropertyAssignment = 224,
ShorthandPropertyAssignment = 225,
EnumMember = 226,
SourceFile = 227,
SyntaxList = 228,
Count = 229,
NamespaceKeyword = 118,
RequireKeyword = 119,
NumberKeyword = 120,
SetKeyword = 121,
StringKeyword = 122,
SymbolKeyword = 123,
TypeKeyword = 124,
FromKeyword = 125,
OfKeyword = 126,
QualifiedName = 127,
ComputedPropertyName = 128,
TypeParameter = 129,
Parameter = 130,
Decorator = 131,
PropertySignature = 132,
PropertyDeclaration = 133,
MethodSignature = 134,
MethodDeclaration = 135,
Constructor = 136,
GetAccessor = 137,
SetAccessor = 138,
CallSignature = 139,
ConstructSignature = 140,
IndexSignature = 141,
TypeReference = 142,
FunctionType = 143,
ConstructorType = 144,
TypeQuery = 145,
TypeLiteral = 146,
ArrayType = 147,
TupleType = 148,
UnionType = 149,
ParenthesizedType = 150,
ObjectBindingPattern = 151,
ArrayBindingPattern = 152,
BindingElement = 153,
ArrayLiteralExpression = 154,
ObjectLiteralExpression = 155,
PropertyAccessExpression = 156,
ElementAccessExpression = 157,
CallExpression = 158,
NewExpression = 159,
TaggedTemplateExpression = 160,
TypeAssertionExpression = 161,
ParenthesizedExpression = 162,
FunctionExpression = 163,
ArrowFunction = 164,
DeleteExpression = 165,
TypeOfExpression = 166,
VoidExpression = 167,
PrefixUnaryExpression = 168,
PostfixUnaryExpression = 169,
BinaryExpression = 170,
ConditionalExpression = 171,
TemplateExpression = 172,
YieldExpression = 173,
SpreadElementExpression = 174,
ClassExpression = 175,
OmittedExpression = 176,
ExpressionWithTypeArguments = 177,
TemplateSpan = 178,
SemicolonClassElement = 179,
Block = 180,
VariableStatement = 181,
EmptyStatement = 182,
ExpressionStatement = 183,
IfStatement = 184,
DoStatement = 185,
WhileStatement = 186,
ForStatement = 187,
ForInStatement = 188,
ForOfStatement = 189,
ContinueStatement = 190,
BreakStatement = 191,
ReturnStatement = 192,
WithStatement = 193,
SwitchStatement = 194,
LabeledStatement = 195,
ThrowStatement = 196,
TryStatement = 197,
DebuggerStatement = 198,
VariableDeclaration = 199,
VariableDeclarationList = 200,
FunctionDeclaration = 201,
ClassDeclaration = 202,
InterfaceDeclaration = 203,
TypeAliasDeclaration = 204,
EnumDeclaration = 205,
ModuleDeclaration = 206,
ModuleBlock = 207,
CaseBlock = 208,
ImportEqualsDeclaration = 209,
ImportDeclaration = 210,
ImportClause = 211,
NamespaceImport = 212,
NamedImports = 213,
ImportSpecifier = 214,
ExportAssignment = 215,
ExportDeclaration = 216,
NamedExports = 217,
ExportSpecifier = 218,
MissingDeclaration = 219,
ExternalModuleReference = 220,
CaseClause = 221,
DefaultClause = 222,
HeritageClause = 223,
CatchClause = 224,
PropertyAssignment = 225,
ShorthandPropertyAssignment = 226,
EnumMember = 227,
SourceFile = 228,
SyntaxList = 229,
Count = 230,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
LastReservedWord = 101,
FirstKeyword = 66,
LastKeyword = 125,
LastKeyword = 126,
FirstFutureReservedWord = 102,
LastFutureReservedWord = 110,
FirstTypeNode = 141,
LastTypeNode = 149,
FirstTypeNode = 142,
LastTypeNode = 150,
FirstPunctuation = 14,
LastPunctuation = 64,
FirstToken = 0,
LastToken = 125,
LastToken = 126,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
@@ -274,7 +275,7 @@ declare module "typescript" {
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 64,
FirstNode = 126,
FirstNode = 127,
}
const enum NodeFlags {
Export = 1,
@@ -290,7 +291,8 @@ declare module "typescript" {
Let = 4096,
Const = 8192,
OctalLiteral = 16384,
ExportContext = 32768,
Namespace = 32768,
ExportContext = 65536,
Modifier = 499,
AccessibilityModifier = 112,
BlockScoped = 12288,
@@ -553,7 +555,7 @@ declare module "typescript" {
typeArguments?: NodeArray<TypeNode>;
arguments: NodeArray<Expression>;
}
interface HeritageClauseElement extends TypeNode {
interface ExpressionWithTypeArguments extends TypeNode {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
}
@@ -672,7 +674,7 @@ declare module "typescript" {
}
interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray<HeritageClauseElement>;
types?: NodeArray<ExpressionWithTypeArguments>;
}
interface TypeAliasDeclaration extends Declaration, ModuleElement {
name: Identifier;
@@ -756,6 +758,9 @@ declare module "typescript" {
getSourceFile(fileName: string): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
readDirectory(rootDir: string, extension: string): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
@@ -804,6 +809,7 @@ declare module "typescript" {
sourceMapFile: string;
sourceMapSourceRoot: string;
sourceMapSources: string[];
sourceMapSourcesContent?: string[];
inputSourceFileNames: string[];
sourceMapNames?: string[];
sourceMapMappings: string;
@@ -1082,11 +1088,14 @@ declare module "typescript" {
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
listFiles?: boolean;
locale?: string;
mapRoot?: string;
module?: ModuleKind;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
@@ -1113,6 +1122,7 @@ declare module "typescript" {
CommonJS = 1,
AMD = 2,
UMD = 3,
System = 4,
}
interface LineAndCharacter {
line: number;
@@ -1226,7 +1236,7 @@ declare module "typescript" {
const version: string;
function findConfigFile(searchPath: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program): Diagnostic[];
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
@@ -1236,14 +1246,26 @@ declare module "typescript" {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readConfigFile(fileName: string): any;
function readConfigFile(fileName: string): {
config?: any;
error?: Diagnostic;
};
/**
* Parse the text of the tsconfig.json file
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
function parseConfigFileText(fileName: string, jsonText: string): {
config?: any;
error?: Diagnostic;
};
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseConfigFile(json: any, basePath?: string): ParsedCommandLine;
function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine;
}
declare module "typescript" {
/** The version of the language service API */
@@ -1340,8 +1362,16 @@ declare module "typescript" {
getSyntacticDiagnostics(fileName: string): Diagnostic[];
getSemanticDiagnostics(fileName: string): Diagnostic[];
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* @deprecated Use getEncodedSyntacticClassifications instead.
*/
getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
/**
* @deprecated Use getEncodedSemanticClassifications instead.
*/
getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications;
getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications;
getCompletionsAtPosition(fileName: string, position: number): CompletionInfo;
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails;
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo;
@@ -1370,6 +1400,10 @@ declare module "typescript" {
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {
spans: number[];
endOfLineState: EndOfLineState;
}
interface ClassifiedSpan {
textSpan: TextSpan;
classificationType: string;
@@ -1581,7 +1615,7 @@ declare module "typescript" {
text: string;
}
const enum EndOfLineState {
Start = 0,
None = 0,
InMultiLineCommentTrivia = 1,
InSingleQuoteStringLiteral = 2,
InDoubleQuoteStringLiteral = 3,
@@ -1627,8 +1661,10 @@ declare module "typescript" {
* classifications which may be incorrectly categorized will be given
* back as Identifiers in order to allow the syntactic classifier to
* subsume the classification.
* @deprecated Use getLexicalClassifications instead.
*/
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult;
getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications;
}
/**
* The document registry represents a store of SourceFile objects that can be shared between
@@ -1739,7 +1775,27 @@ declare module "typescript" {
static interfaceName: string;
static moduleName: string;
static typeParameterName: string;
static typeAlias: string;
static typeAliasName: string;
static parameterName: string;
}
const enum ClassificationType {
comment = 1,
identifier = 2,
keyword = 3,
numericLiteral = 4,
operator = 5,
stringLiteral = 6,
regularExpressionLiteral = 7,
whiteSpace = 8,
text = 9,
punctuation = 10,
className = 11,
enumName = 12,
interfaceName = 13,
moduleName = 14,
typeParameterName = 15,
typeAliasName = 16,
parameterName = 17,
}
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
+4142 -3121
View File
File diff suppressed because it is too large Load Diff
+181 -125
View File
@@ -140,132 +140,133 @@ declare module ts {
DeclareKeyword = 115,
GetKeyword = 116,
ModuleKeyword = 117,
RequireKeyword = 118,
NumberKeyword = 119,
SetKeyword = 120,
StringKeyword = 121,
SymbolKeyword = 122,
TypeKeyword = 123,
FromKeyword = 124,
OfKeyword = 125,
QualifiedName = 126,
ComputedPropertyName = 127,
TypeParameter = 128,
Parameter = 129,
Decorator = 130,
PropertySignature = 131,
PropertyDeclaration = 132,
MethodSignature = 133,
MethodDeclaration = 134,
Constructor = 135,
GetAccessor = 136,
SetAccessor = 137,
CallSignature = 138,
ConstructSignature = 139,
IndexSignature = 140,
TypeReference = 141,
FunctionType = 142,
ConstructorType = 143,
TypeQuery = 144,
TypeLiteral = 145,
ArrayType = 146,
TupleType = 147,
UnionType = 148,
ParenthesizedType = 149,
ObjectBindingPattern = 150,
ArrayBindingPattern = 151,
BindingElement = 152,
ArrayLiteralExpression = 153,
ObjectLiteralExpression = 154,
PropertyAccessExpression = 155,
ElementAccessExpression = 156,
CallExpression = 157,
NewExpression = 158,
TaggedTemplateExpression = 159,
TypeAssertionExpression = 160,
ParenthesizedExpression = 161,
FunctionExpression = 162,
ArrowFunction = 163,
DeleteExpression = 164,
TypeOfExpression = 165,
VoidExpression = 166,
PrefixUnaryExpression = 167,
PostfixUnaryExpression = 168,
BinaryExpression = 169,
ConditionalExpression = 170,
TemplateExpression = 171,
YieldExpression = 172,
SpreadElementExpression = 173,
ClassExpression = 174,
OmittedExpression = 175,
TemplateSpan = 176,
HeritageClauseElement = 177,
SemicolonClassElement = 178,
Block = 179,
VariableStatement = 180,
EmptyStatement = 181,
ExpressionStatement = 182,
IfStatement = 183,
DoStatement = 184,
WhileStatement = 185,
ForStatement = 186,
ForInStatement = 187,
ForOfStatement = 188,
ContinueStatement = 189,
BreakStatement = 190,
ReturnStatement = 191,
WithStatement = 192,
SwitchStatement = 193,
LabeledStatement = 194,
ThrowStatement = 195,
TryStatement = 196,
DebuggerStatement = 197,
VariableDeclaration = 198,
VariableDeclarationList = 199,
FunctionDeclaration = 200,
ClassDeclaration = 201,
InterfaceDeclaration = 202,
TypeAliasDeclaration = 203,
EnumDeclaration = 204,
ModuleDeclaration = 205,
ModuleBlock = 206,
CaseBlock = 207,
ImportEqualsDeclaration = 208,
ImportDeclaration = 209,
ImportClause = 210,
NamespaceImport = 211,
NamedImports = 212,
ImportSpecifier = 213,
ExportAssignment = 214,
ExportDeclaration = 215,
NamedExports = 216,
ExportSpecifier = 217,
MissingDeclaration = 218,
ExternalModuleReference = 219,
CaseClause = 220,
DefaultClause = 221,
HeritageClause = 222,
CatchClause = 223,
PropertyAssignment = 224,
ShorthandPropertyAssignment = 225,
EnumMember = 226,
SourceFile = 227,
SyntaxList = 228,
Count = 229,
NamespaceKeyword = 118,
RequireKeyword = 119,
NumberKeyword = 120,
SetKeyword = 121,
StringKeyword = 122,
SymbolKeyword = 123,
TypeKeyword = 124,
FromKeyword = 125,
OfKeyword = 126,
QualifiedName = 127,
ComputedPropertyName = 128,
TypeParameter = 129,
Parameter = 130,
Decorator = 131,
PropertySignature = 132,
PropertyDeclaration = 133,
MethodSignature = 134,
MethodDeclaration = 135,
Constructor = 136,
GetAccessor = 137,
SetAccessor = 138,
CallSignature = 139,
ConstructSignature = 140,
IndexSignature = 141,
TypeReference = 142,
FunctionType = 143,
ConstructorType = 144,
TypeQuery = 145,
TypeLiteral = 146,
ArrayType = 147,
TupleType = 148,
UnionType = 149,
ParenthesizedType = 150,
ObjectBindingPattern = 151,
ArrayBindingPattern = 152,
BindingElement = 153,
ArrayLiteralExpression = 154,
ObjectLiteralExpression = 155,
PropertyAccessExpression = 156,
ElementAccessExpression = 157,
CallExpression = 158,
NewExpression = 159,
TaggedTemplateExpression = 160,
TypeAssertionExpression = 161,
ParenthesizedExpression = 162,
FunctionExpression = 163,
ArrowFunction = 164,
DeleteExpression = 165,
TypeOfExpression = 166,
VoidExpression = 167,
PrefixUnaryExpression = 168,
PostfixUnaryExpression = 169,
BinaryExpression = 170,
ConditionalExpression = 171,
TemplateExpression = 172,
YieldExpression = 173,
SpreadElementExpression = 174,
ClassExpression = 175,
OmittedExpression = 176,
ExpressionWithTypeArguments = 177,
TemplateSpan = 178,
SemicolonClassElement = 179,
Block = 180,
VariableStatement = 181,
EmptyStatement = 182,
ExpressionStatement = 183,
IfStatement = 184,
DoStatement = 185,
WhileStatement = 186,
ForStatement = 187,
ForInStatement = 188,
ForOfStatement = 189,
ContinueStatement = 190,
BreakStatement = 191,
ReturnStatement = 192,
WithStatement = 193,
SwitchStatement = 194,
LabeledStatement = 195,
ThrowStatement = 196,
TryStatement = 197,
DebuggerStatement = 198,
VariableDeclaration = 199,
VariableDeclarationList = 200,
FunctionDeclaration = 201,
ClassDeclaration = 202,
InterfaceDeclaration = 203,
TypeAliasDeclaration = 204,
EnumDeclaration = 205,
ModuleDeclaration = 206,
ModuleBlock = 207,
CaseBlock = 208,
ImportEqualsDeclaration = 209,
ImportDeclaration = 210,
ImportClause = 211,
NamespaceImport = 212,
NamedImports = 213,
ImportSpecifier = 214,
ExportAssignment = 215,
ExportDeclaration = 216,
NamedExports = 217,
ExportSpecifier = 218,
MissingDeclaration = 219,
ExternalModuleReference = 220,
CaseClause = 221,
DefaultClause = 222,
HeritageClause = 223,
CatchClause = 224,
PropertyAssignment = 225,
ShorthandPropertyAssignment = 226,
EnumMember = 227,
SourceFile = 228,
SyntaxList = 229,
Count = 230,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
LastReservedWord = 101,
FirstKeyword = 66,
LastKeyword = 125,
LastKeyword = 126,
FirstFutureReservedWord = 102,
LastFutureReservedWord = 110,
FirstTypeNode = 141,
LastTypeNode = 149,
FirstTypeNode = 142,
LastTypeNode = 150,
FirstPunctuation = 14,
LastPunctuation = 64,
FirstToken = 0,
LastToken = 125,
LastToken = 126,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
@@ -274,7 +275,7 @@ declare module ts {
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 64,
FirstNode = 126,
FirstNode = 127,
}
const enum NodeFlags {
Export = 1,
@@ -290,7 +291,8 @@ declare module ts {
Let = 4096,
Const = 8192,
OctalLiteral = 16384,
ExportContext = 32768,
Namespace = 32768,
ExportContext = 65536,
Modifier = 499,
AccessibilityModifier = 112,
BlockScoped = 12288,
@@ -553,7 +555,7 @@ declare module ts {
typeArguments?: NodeArray<TypeNode>;
arguments: NodeArray<Expression>;
}
interface HeritageClauseElement extends TypeNode {
interface ExpressionWithTypeArguments extends TypeNode {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
}
@@ -672,7 +674,7 @@ declare module ts {
}
interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray<HeritageClauseElement>;
types?: NodeArray<ExpressionWithTypeArguments>;
}
interface TypeAliasDeclaration extends Declaration, ModuleElement {
name: Identifier;
@@ -756,6 +758,9 @@ declare module ts {
getSourceFile(fileName: string): SourceFile;
getCurrentDirectory(): string;
}
interface ParseConfigHost {
readDirectory(rootDir: string, extension: string): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
@@ -804,6 +809,7 @@ declare module ts {
sourceMapFile: string;
sourceMapSourceRoot: string;
sourceMapSources: string[];
sourceMapSourcesContent?: string[];
inputSourceFileNames: string[];
sourceMapNames?: string[];
sourceMapMappings: string;
@@ -1082,11 +1088,14 @@ declare module ts {
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
listFiles?: boolean;
locale?: string;
mapRoot?: string;
module?: ModuleKind;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
@@ -1113,6 +1122,7 @@ declare module ts {
CommonJS = 1,
AMD = 2,
UMD = 3,
System = 4,
}
interface LineAndCharacter {
line: number;
@@ -1226,7 +1236,7 @@ declare module ts {
const version: string;
function findConfigFile(searchPath: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
function getPreEmitDiagnostics(program: Program): Diagnostic[];
function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[];
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
@@ -1236,14 +1246,26 @@ declare module ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
function readConfigFile(fileName: string): any;
function readConfigFile(fileName: string): {
config?: any;
error?: Diagnostic;
};
/**
* Parse the text of the tsconfig.json file
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
function parseConfigFileText(fileName: string, jsonText: string): {
config?: any;
error?: Diagnostic;
};
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
function parseConfigFile(json: any, basePath?: string): ParsedCommandLine;
function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine;
}
declare module ts {
/** The version of the language service API */
@@ -1340,8 +1362,16 @@ declare module ts {
getSyntacticDiagnostics(fileName: string): Diagnostic[];
getSemanticDiagnostics(fileName: string): Diagnostic[];
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* @deprecated Use getEncodedSyntacticClassifications instead.
*/
getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
/**
* @deprecated Use getEncodedSemanticClassifications instead.
*/
getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications;
getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications;
getCompletionsAtPosition(fileName: string, position: number): CompletionInfo;
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails;
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo;
@@ -1370,6 +1400,10 @@ declare module ts {
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {
spans: number[];
endOfLineState: EndOfLineState;
}
interface ClassifiedSpan {
textSpan: TextSpan;
classificationType: string;
@@ -1581,7 +1615,7 @@ declare module ts {
text: string;
}
const enum EndOfLineState {
Start = 0,
None = 0,
InMultiLineCommentTrivia = 1,
InSingleQuoteStringLiteral = 2,
InDoubleQuoteStringLiteral = 3,
@@ -1627,8 +1661,10 @@ declare module ts {
* classifications which may be incorrectly categorized will be given
* back as Identifiers in order to allow the syntactic classifier to
* subsume the classification.
* @deprecated Use getLexicalClassifications instead.
*/
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult;
getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications;
}
/**
* The document registry represents a store of SourceFile objects that can be shared between
@@ -1739,7 +1775,27 @@ declare module ts {
static interfaceName: string;
static moduleName: string;
static typeParameterName: string;
static typeAlias: string;
static typeAliasName: string;
static parameterName: string;
}
const enum ClassificationType {
comment = 1,
identifier = 2,
keyword = 3,
numericLiteral = 4,
operator = 5,
stringLiteral = 6,
regularExpressionLiteral = 7,
whiteSpace = 8,
text = 9,
punctuation = 10,
className = 11,
enumName = 12,
interfaceName = 13,
moduleName = 14,
typeParameterName = 15,
typeAliasName = 16,
parameterName = 17,
}
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
+4142 -3121
View File
File diff suppressed because it is too large Load Diff
+35 -43
View File
@@ -2473,7 +2473,7 @@ module ts {
let declaration = <ClassDeclaration>getDeclarationOfKind(type.symbol, SyntaxKind.ClassDeclaration);
let baseTypeNode = getClassExtendsHeritageClauseElement(declaration);
if (baseTypeNode) {
let baseType = getTypeFromHeritageClauseElement(baseTypeNode);
let baseType = getTypeFromTypeNode(baseTypeNode);
if (baseType !== unknownType) {
if (getTargetType(baseType).flags & TypeFlags.Class) {
if (type !== baseType && !hasBaseType(<InterfaceType>baseType, type)) {
@@ -2495,7 +2495,7 @@ module ts {
for (let declaration of type.symbol.declarations) {
if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(<InterfaceDeclaration>declaration)) {
for (let node of getInterfaceBaseTypeNodes(<InterfaceDeclaration>declaration)) {
let baseType = getTypeFromHeritageClauseElement(node);
let baseType = getTypeFromTypeNode(node);
if (baseType !== unknownType) {
if (getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface)) {
@@ -3182,7 +3182,7 @@ module ts {
function getRestTypeOfSignature(signature: Signature): Type {
if (signature.hasRestParameter) {
let type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
let type = getTypeOfSymbol(lastOrUndefined(signature.parameters));
if (type.flags & TypeFlags.Reference && (<TypeReference>type).target === globalArrayType) {
return (<TypeReference>type).typeArguments[0];
}
@@ -3310,7 +3310,7 @@ module ts {
return type;
}
function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: TypeReferenceNode | HeritageClauseElement, typeParameterSymbol: Symbol): boolean {
function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: TypeReferenceNode | ExpressionWithTypeArguments, typeParameterSymbol: Symbol): boolean {
let links = getNodeLinks(typeReferenceNode);
if (links.isIllegalTypeReferenceInConstraint !== undefined) {
return links.isIllegalTypeReferenceInConstraint;
@@ -3359,25 +3359,17 @@ module ts {
}
}
function getTypeFromTypeReference(node: TypeReferenceNode): Type {
return getTypeFromTypeReferenceOrHeritageClauseElement(node);
}
function getTypeFromHeritageClauseElement(node: HeritageClauseElement): Type {
return getTypeFromTypeReferenceOrHeritageClauseElement(node);
}
function getTypeFromTypeReferenceOrHeritageClauseElement(node: TypeReferenceNode | HeritageClauseElement): Type {
function getTypeFromTypeReferenceOrExpressionWithTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments): Type {
let links = getNodeLinks(node);
if (!links.resolvedType) {
let type: Type;
// We don't currently support heritage clauses with complex expressions in them.
// For these cases, we just set the type to be the unknownType.
if (node.kind !== SyntaxKind.HeritageClauseElement || isSupportedHeritageClauseElement(<HeritageClauseElement>node)) {
if (node.kind !== SyntaxKind.ExpressionWithTypeArguments || isSupportedExpressionWithTypeArguments(<ExpressionWithTypeArguments>node)) {
let typeNameOrExpression = node.kind === SyntaxKind.TypeReference
? (<TypeReferenceNode>node).typeName
: (<HeritageClauseElement>node).expression;
: (<ExpressionWithTypeArguments>node).expression;
let symbol = resolveEntityName(typeNameOrExpression, SymbolFlags.Type);
if (symbol) {
@@ -3667,9 +3659,9 @@ module ts {
case SyntaxKind.StringLiteral:
return getTypeFromStringLiteral(<StringLiteral>node);
case SyntaxKind.TypeReference:
return getTypeFromTypeReference(<TypeReferenceNode>node);
case SyntaxKind.HeritageClauseElement:
return getTypeFromHeritageClauseElement(<HeritageClauseElement>node);
return getTypeFromTypeReferenceOrExpressionWithTypeArguments(<TypeReferenceNode>node);
case SyntaxKind.ExpressionWithTypeArguments:
return getTypeFromTypeReferenceOrExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
case SyntaxKind.TypeQuery:
return getTypeFromTypeQueryNode(<TypeQueryNode>node);
case SyntaxKind.ArrayType:
@@ -5674,7 +5666,7 @@ module ts {
// If last parameter is contextually rest parameter get its type
if (indexOfParameter === (func.parameters.length - 1) &&
funcHasRestParameters && contextualSignature.hasRestParameter && func.parameters.length >= contextualSignature.parameters.length) {
return getTypeOfSymbol(contextualSignature.parameters[contextualSignature.parameters.length - 1]);
return getTypeOfSymbol(lastOrUndefined(contextualSignature.parameters));
}
}
}
@@ -7223,9 +7215,9 @@ module ts {
links.type = instantiateType(getTypeAtPosition(context, i), mapper);
}
if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) {
let parameter = signature.parameters[signature.parameters.length - 1];
let parameter = lastOrUndefined(signature.parameters);
let links = getSymbolLinks(parameter);
links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper);
links.type = instantiateType(getTypeOfSymbol(lastOrUndefined(context.parameters)), mapper);
}
}
@@ -8380,20 +8372,20 @@ module ts {
function checkTypeReferenceNode(node: TypeReferenceNode) {
checkGrammarTypeReferenceInStrictMode(node.typeName);
return checkTypeReferenceOrHeritageClauseElement(node);
return checkTypeReferenceOrExpressionWithTypeArguments(node);
}
function checkHeritageClauseElement(node: HeritageClauseElement) {
checkGrammarHeritageClauseElementInStrictMode(<PropertyAccessExpression>node.expression);
function checkExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
checkGrammarExpressionWithTypeArgumentsInStrictMode(<PropertyAccessExpression>node.expression);
return checkTypeReferenceOrHeritageClauseElement(node);
return checkTypeReferenceOrExpressionWithTypeArguments(node);
}
function checkTypeReferenceOrHeritageClauseElement(node: TypeReferenceNode | HeritageClauseElement) {
function checkTypeReferenceOrExpressionWithTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments) {
// Grammar checking
checkGrammarTypeArguments(node, node.typeArguments);
let type = getTypeFromTypeReferenceOrHeritageClauseElement(node);
let type = getTypeFromTypeReferenceOrExpressionWithTypeArguments(node);
if (type !== unknownType && node.typeArguments) {
// Do type argument local checks only if referenced type is successfully resolved
let len = node.typeArguments.length;
@@ -9959,12 +9951,12 @@ module ts {
let staticType = <ObjectType>getTypeOfSymbol(symbol);
let baseTypeNode = getClassExtendsHeritageClauseElement(node);
if (baseTypeNode) {
if (!isSupportedHeritageClauseElement(baseTypeNode)) {
if (!isSupportedExpressionWithTypeArguments(baseTypeNode)) {
error(baseTypeNode.expression, Diagnostics.Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses);
}
emitExtends = emitExtends || !isInAmbientContext(node);
checkHeritageClauseElement(baseTypeNode);
checkExpressionWithTypeArguments(baseTypeNode);
}
let baseTypes = getBaseTypes(type);
if (baseTypes.length) {
@@ -9991,13 +9983,13 @@ module ts {
let implementedTypeNodes = getClassImplementsHeritageClauseElements(node);
if (implementedTypeNodes) {
forEach(implementedTypeNodes, typeRefNode => {
if (!isSupportedHeritageClauseElement(typeRefNode)) {
if (!isSupportedExpressionWithTypeArguments(typeRefNode)) {
error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
}
checkHeritageClauseElement(typeRefNode);
checkExpressionWithTypeArguments(typeRefNode);
if (produceDiagnostics) {
let t = getTypeFromHeritageClauseElement(typeRefNode);
let t = getTypeFromTypeNode(typeRefNode);
if (t !== unknownType) {
let declaredType = (t.flags & TypeFlags.Reference) ? (<TypeReference>t).target : t;
if (declaredType.flags & (TypeFlags.Class | TypeFlags.Interface)) {
@@ -10192,11 +10184,11 @@ module ts {
}
}
forEach(getInterfaceBaseTypeNodes(node), heritageElement => {
if (!isSupportedHeritageClauseElement(heritageElement)) {
if (!isSupportedExpressionWithTypeArguments(heritageElement)) {
error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
}
checkHeritageClauseElement(heritageElement);
checkExpressionWithTypeArguments(heritageElement);
});
forEach(node.members, checkSourceElement);
@@ -10689,7 +10681,7 @@ module ts {
}
checkExternalModuleExports(container);
if (node.isExportEquals) {
if (node.isExportEquals && !isInAmbientContext(node)) {
if (languageVersion >= ScriptTarget.ES6) {
// export assignment is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_or_higher_Consider_using_export_default_instead);
@@ -11159,7 +11151,7 @@ module ts {
node = node.parent;
}
return node.parent && node.parent.kind === SyntaxKind.HeritageClauseElement;
return node.parent && node.parent.kind === SyntaxKind.ExpressionWithTypeArguments;
}
function isTypeNode(node: Node): boolean {
@@ -11179,7 +11171,7 @@ module ts {
case SyntaxKind.StringLiteral:
// Specialized signatures can have string literals as their parameters' type names
return node.parent.kind === SyntaxKind.Parameter;
case SyntaxKind.HeritageClauseElement:
case SyntaxKind.ExpressionWithTypeArguments:
return true;
// Identifiers and qualified names may be type nodes, depending on their context. Climb
@@ -11213,7 +11205,7 @@ module ts {
return true;
}
switch (parent.kind) {
case SyntaxKind.HeritageClauseElement:
case SyntaxKind.ExpressionWithTypeArguments:
return true;
case SyntaxKind.TypeParameter:
return node === (<TypeParameterDeclaration>parent).constraint;
@@ -11291,7 +11283,7 @@ module ts {
}
if (isHeritageClauseElementIdentifier(<EntityName>entityName)) {
let meaning = entityName.parent.kind === SyntaxKind.HeritageClauseElement ? SymbolFlags.Type : SymbolFlags.Namespace;
let meaning = entityName.parent.kind === SyntaxKind.ExpressionWithTypeArguments ? SymbolFlags.Type : SymbolFlags.Namespace;
meaning |= SymbolFlags.Alias;
return resolveEntityName(<EntityName>entityName, meaning);
}
@@ -11700,7 +11692,7 @@ module ts {
// * The serialized type of a TypeReference with a value declaration is its entity name.
// * The serialized type of a TypeReference with a call or construct signature is "Function".
// * The serialized type of any other type is "Object".
let type = getTypeFromTypeReference(node);
let type = getTypeFromTypeNode(node);
if (type.flags & TypeFlags.Void) {
return "void 0";
}
@@ -12122,7 +12114,7 @@ module ts {
// public // error at public
// public.private.package // error at public
// B.private.B // no error
function checkGrammarHeritageClauseElementInStrictMode(expression: Expression) {
function checkGrammarExpressionWithTypeArgumentsInStrictMode(expression: Expression) {
// Example:
// class C extends public // error at public
if (expression && expression.kind === SyntaxKind.Identifier) {
@@ -12133,7 +12125,7 @@ module ts {
// in PropertyAccessExpression. According to grammar production of MemberExpression,
// the left component expression is a PrimaryExpression (i.e. Identifier) while the other
// component after dots can be IdentifierName.
checkGrammarHeritageClauseElementInStrictMode((<PropertyAccessExpression>expression).expression);
checkGrammarExpressionWithTypeArgumentsInStrictMode((<PropertyAccessExpression>expression).expression);
}
}
@@ -12842,7 +12834,7 @@ module ts {
function checkGrammarBindingElement(node: BindingElement) {
if (node.dotDotDotToken) {
let elements = (<BindingPattern>node.parent).elements;
if (node !== elements[elements.length - 1]) {
if (node !== lastOrUndefined(elements)) {
return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern);
}
+14
View File
@@ -66,11 +66,25 @@ module ts {
paramType: Diagnostics.KIND,
error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_or_umd
},
{
name: "newLine",
type: {
"crlf": NewLineKind.CarriageReturnLineFeed,
"lf": NewLineKind.LineFeed
},
description: Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
paramType: Diagnostics.NEWLINE,
error: Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF
},
{
name: "noEmit",
type: "boolean",
description: Diagnostics.Do_not_emit_outputs,
},
{
name: "noEmitHelpers",
type: "boolean"
},
{
name: "noEmitOnError",
type: "boolean",
+2 -2
View File
@@ -470,7 +470,7 @@ module ts {
let normalized: string[] = [];
for (let part of parts) {
if (part !== ".") {
if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") {
if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
normalized.pop();
}
else {
@@ -586,7 +586,7 @@ module ts {
export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean) {
let pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
let directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") {
if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
// If the directory path given was of type test/cases/ then we really need components of directory to be only till its name
// that is ["test", "cases", ""] needs to be actually ["test", "cases"]
directoryComponents.length--;
+7 -7
View File
@@ -329,8 +329,8 @@ module ts {
case SyntaxKind.VoidKeyword:
case SyntaxKind.StringLiteral:
return writeTextOfNode(currentSourceFile, type);
case SyntaxKind.HeritageClauseElement:
return emitHeritageClauseElement(<HeritageClauseElement>type);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>type);
case SyntaxKind.TypeReference:
return emitTypeReference(<TypeReferenceNode>type);
case SyntaxKind.TypeQuery:
@@ -376,8 +376,8 @@ module ts {
}
}
function emitHeritageClauseElement(node: HeritageClauseElement) {
if (isSupportedHeritageClauseElement(node)) {
function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression);
emitEntityName(<Identifier | PropertyAccessExpression>node.expression);
if (node.typeArguments) {
@@ -861,14 +861,14 @@ module ts {
}
}
function emitHeritageClause(typeReferences: HeritageClauseElement[], isImplementsList: boolean) {
function emitHeritageClause(typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) {
if (typeReferences) {
write(isImplementsList ? " implements " : " extends ");
emitCommaList(typeReferences, emitTypeOfTypeReference);
}
function emitTypeOfTypeReference(node: HeritageClauseElement) {
if (isSupportedHeritageClauseElement(node)) {
function emitTypeOfTypeReference(node: ExpressionWithTypeArguments) {
if (isSupportedExpressionWithTypeArguments(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError);
}
@@ -502,6 +502,9 @@ module ts {
Preserve_new_lines_when_emitting_code: { code: 6057, category: DiagnosticCategory.Message, key: "Preserve new-lines when emitting code." },
Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: DiagnosticCategory.Message, key: "Specifies the root directory of input files. Use to control the output directory structure with --outDir." },
File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: DiagnosticCategory.Error, key: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." },
Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." },
NEWLINE: { code: 6061, category: DiagnosticCategory.Message, key: "NEWLINE" },
Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." },
Variable_0_implicitly_has_an_1_type: { code: 7005, category: DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." },
Parameter_0_implicitly_has_an_1_type: { code: 7006, category: DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." },
Member_0_implicitly_has_an_1_type: { code: 7008, category: DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." },
+12
View File
@@ -1998,6 +1998,18 @@
"category": "Error",
"code": 6059
},
"Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"category": "Message",
"code": 6060
},
"NEWLINE": {
"category": "Message",
"code": 6061
},
"Argument for '--newLine' option must be 'CRLF' or 'LF'.": {
"category": "Error",
"code": 6062
},
"Variable '{0}' implicitly has an '{1}' type.": {
+5 -5
View File
@@ -267,7 +267,7 @@ var ts;
var sourceMapNameIndexMap = {};
var sourceMapNameIndices = [];
function getSourceMapNameIndex() {
return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1;
return sourceMapNameIndices.length ? lastOrUndefined(sourceMapNameIndices) : -1;
}
// Last recorded and encoded spans
var lastRecordedSourceMapSpan;
@@ -5084,11 +5084,11 @@ var ts;
}
}
function hasDetachedComments(pos) {
return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos;
return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos;
}
function getLeadingCommentsWithoutDetachedComments() {
// get the leading comments from detachedPos
var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos);
var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@@ -5189,13 +5189,13 @@ var ts;
// All comments look like they could have been part of the copyright header. Make
// sure there is at least one blank line between it and the node. If not, it's not
// a copyright header.
var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end);
var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end);
var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
// Valid detachedComments
ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment);
var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end };
var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: lastOrUndefined(detachedComments).end };
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
}
+189 -44
View File
@@ -3,12 +3,6 @@
/* @internal */
module ts {
// represents one LexicalEnvironment frame to store unique generated names
interface ScopeFrame {
names: Map<string>;
previous: ScopeFrame;
}
export function isExternalModuleOrDeclarationFile(sourceFile: SourceFile) {
return isExternalModule(sourceFile) || isDeclarationFile(sourceFile);
}
@@ -18,14 +12,13 @@ module ts {
Auto = 0x00000000, // No preferred name
CountMask = 0x0FFFFFFF, // Temp variable counter
_i = 0x10000000, // Use/preference flag for '_i'
_n = 0x20000000, // Use/preference flag for '_n'
}
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult {
// emit output for the __extends helper function
const extendsHelper = `
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -34,7 +27,7 @@ var __extends = this.__extends || function (d, b) {
// emit output for the __decorate helper function
const decorateHelper = `
if (typeof __decorate !== "function") __decorate = function (decorators, target, key, desc) {
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
@@ -45,13 +38,13 @@ if (typeof __decorate !== "function") __decorate = function (decorators, target,
// emit output for the __metadata helper function
const metadataHelper = `
if (typeof __metadata !== "function") __metadata = function (k, v) {
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};`;
// emit output for the __param helper function
const paramHelper = `
if (typeof __param !== "function") __param = function (paramIndex, decorator) {
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};`;
@@ -343,7 +336,7 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
let sourceMapNameIndexMap: Map<number> = {};
let sourceMapNameIndices: number[] = [];
function getSourceMapNameIndex() {
return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1;
return sourceMapNameIndices.length ? lastOrUndefined(sourceMapNameIndices) : -1;
}
// Last recorded and encoded spans
@@ -2683,15 +2676,17 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) {
for (let specifier of exportSpecifiers[name.text]) {
writeLine();
emitStart(specifier.name);
if (compilerOptions.module === ModuleKind.System) {
emitStart(specifier.name);
write(`${exportFunctionForFile}("`);
emitNodeWithoutSourceMap(specifier.name);
write(`", `);
emitExpressionIdentifier(name);
write(")")
emitEnd(specifier.name);
}
else {
emitStart(specifier.name);
emitContainingModuleName(specifier);
write(".");
emitNodeWithoutSourceMap(specifier.name);
@@ -3486,10 +3481,10 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
}
}
function getInitializedProperties(node: ClassLikeDeclaration, static: boolean) {
function getInitializedProperties(node: ClassLikeDeclaration, isStatic: boolean) {
let properties: PropertyDeclaration[] = [];
for (let member of node.members) {
if (member.kind === SyntaxKind.PropertyDeclaration && static === ((member.flags & NodeFlags.Static) !== 0) && (<PropertyDeclaration>member).initializer) {
if (member.kind === SyntaxKind.PropertyDeclaration && isStatic === ((member.flags & NodeFlags.Static) !== 0) && (<PropertyDeclaration>member).initializer) {
properties.push(<PropertyDeclaration>member);
}
}
@@ -3641,7 +3636,7 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
}
}
function emitConstructor(node: ClassLikeDeclaration, baseTypeElement: HeritageClauseElement) {
function emitConstructor(node: ClassLikeDeclaration, baseTypeElement: ExpressionWithTypeArguments) {
let saveTempFlags = tempFlags;
let saveTempVariables = tempVariables;
let saveTempParameters = tempParameters;
@@ -3656,7 +3651,7 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
tempParameters = saveTempParameters;
}
function emitConstructorWorker(node: ClassLikeDeclaration, baseTypeElement: HeritageClauseElement) {
function emitConstructorWorker(node: ClassLikeDeclaration, baseTypeElement: ExpressionWithTypeArguments) {
// Check if we have property assignment inside class declaration.
// If there is property assignment, we need to emit constructor whether users define it or not
// If there is no property assignment, we can omit constructor if users do not define it
@@ -4968,7 +4963,135 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
}
}
function hoistTopLevelVariableAndFunctionDeclarations(node: SourceFile): void {
function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations: (Identifier | Declaration)[]): string {
// when resolving exports local exported entries/indirect exported entries in the module
// should always win over entries with similar names that were added via star exports
// to support this we store names of local/indirect exported entries in a set.
// this set is used to filter names brought by star expors.
if (!hasExportStars) {
// local names set is needed only in presence of star exports
return undefined;
}
// local names set should only be added if we have anything exported
if (!exportedDeclarations && isEmpty(exportSpecifiers)) {
// no exported declarations (export var ...) or export specifiers (export {x})
// check if we have any non star export declarations.
let hasExportDeclarationWithExportClause = false;
for (let externalImport of externalImports) {
if (externalImport.kind === SyntaxKind.ExportDeclaration && (<ExportDeclaration>externalImport).exportClause) {
hasExportDeclarationWithExportClause = true;
break;
}
}
if (!hasExportDeclarationWithExportClause) {
// we still need to emit exportStar helper
return emitExportStarFunction(/*localNames*/ undefined);
}
}
const exportedNamesStorageRef = makeUniqueName("exportedNames");
writeLine();
write(`var ${exportedNamesStorageRef} = {`);
increaseIndent();
let started = false;
if (exportedDeclarations) {
for (let i = 0; i < exportedDeclarations.length; ++i) {
// write name of exported declaration, i.e 'export var x...'
writeExportedName(exportedDeclarations[i]);
}
}
if (exportSpecifiers) {
for (let n in exportSpecifiers) {
for (let specifier of exportSpecifiers[n]) {
// write name of export specified, i.e. 'export {x}'
writeExportedName(specifier.name);
}
}
}
for (let externalImport of externalImports) {
if (externalImport.kind !== SyntaxKind.ExportDeclaration) {
continue;
}
let exportDecl = <ExportDeclaration>externalImport;
if (!exportDecl.exportClause) {
// export * from ...
continue;
}
for (let element of exportDecl.exportClause.elements) {
// write name of indirectly exported entry, i.e. 'export {x} from ...'
writeExportedName(element.name || element.propertyName);
}
}
decreaseIndent();
writeLine();
write("};");
return emitExportStarFunction(exportedNamesStorageRef);
function emitExportStarFunction(localNames: string): string {
const exportStarFunction = makeUniqueName("exportStar");
writeLine();
// define an export star helper function
write(`function ${exportStarFunction}(m) {`);
increaseIndent();
writeLine();
write(`for(var n in m) {`);
increaseIndent();
writeLine();
write(`if (n !== "default"`);
if (localNames) {
write(`&& !${localNames}.hasOwnProperty(n)`);
}
write(`) ${exportFunctionForFile}(n, m[n]);`);
decreaseIndent();
writeLine();
write("}");
decreaseIndent();
writeLine();
write("}")
return exportStarFunction;
}
function writeExportedName(node: Identifier | Declaration): void {
// do not record default exports
// they are local to module and never overwritten (explicitly skipped) by star export
if (node.kind !== SyntaxKind.Identifier && node.flags & NodeFlags.Default) {
return;
}
if (started) {
write(",");
}
else {
started = true;
}
writeLine();
write("'");
if (node.kind === SyntaxKind.Identifier) {
emitNodeWithoutSourceMap(node);
}
else {
emitDeclarationName(<Declaration>node);
}
write("': true");
}
}
function processTopLevelVariableAndFunctionDeclarations(node: SourceFile): (Identifier | Declaration)[] {
// per ES6 spec:
// 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method
// - var declarations are initialized to undefined - 14.a.ii
@@ -4980,6 +5103,7 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
// including variables declarations for module and class declarations
let hoistedVars: (Identifier | ClassDeclaration | ModuleDeclaration)[];
let hoistedFunctionDeclarations: FunctionDeclaration[];
let exportedDeclarations: (Identifier | Declaration)[];
visit(node);
@@ -4997,6 +5121,14 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
else {
emit(local);
}
let flags = getCombinedNodeFlags(local.kind === SyntaxKind.Identifier ? local.parent : local);
if (flags & NodeFlags.Export) {
if (!exportedDeclarations) {
exportedDeclarations = [];
}
exportedDeclarations.push(local);
}
}
write(";")
}
@@ -5005,9 +5137,18 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
for (let f of hoistedFunctionDeclarations) {
writeLine();
emit(f);
if (f.flags & NodeFlags.Export) {
if (!exportedDeclarations) {
exportedDeclarations = [];
}
exportedDeclarations.push(f);
}
}
}
return exportedDeclarations;
function visit(node: Node): void {
if (node.kind === SyntaxKind.FunctionDeclaration) {
if (!hoistedFunctionDeclarations) {
@@ -5121,12 +5262,13 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
// }
emitVariableDeclarationsForImports();
writeLine();
hoistTopLevelVariableAndFunctionDeclarations(node);
var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node);
let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations)
writeLine();
write("return {");
increaseIndent();
writeLine();
emitSetters();
emitSetters(exportStarFunction);
writeLine();
emitExecute(node, startIndex);
emitTempDeclarations(/*newLine*/ true)
@@ -5135,7 +5277,7 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
write("}"); // return
}
function emitSetters() {
function emitSetters(exportStarFunction: string) {
write("setters:[");
for (let i = 0; i < externalImports.length; ++i) {
if (i !== 0) {
@@ -5163,7 +5305,7 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
increaseIndent();
writeLine();
// save import into the local
write(`${importVariableName} = ${parameterName}`);
write(`${importVariableName} = ${parameterName};`);
writeLine();
let defaultName =
@@ -5228,9 +5370,8 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
writeLine();
// export * from 'foo'
// emit as:
// for (var n in _foo) exports(n, _foo[n]);
// NOTE: it is safe to use name 'n' since parameter name always starts with '_'
write(`for (var n in ${parameterName}) ${exportFunctionForFile}(n, ${parameterName}[n]);`);
// exportStar(_foo);
write(`${exportStarFunction}(${parameterName});`);
}
writeLine();
@@ -5473,24 +5614,28 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
// emit prologue directives prior to __extends
var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false);
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitExtends)) {
writeLines(extendsHelper);
extendsEmitted = true;
}
if (!decorateEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitDecorate) {
writeLines(decorateHelper);
if (compilerOptions.emitDecoratorMetadata) {
writeLines(metadataHelper);
// Only emit helpers if the user did not say otherwise.
if (!compilerOptions.noEmitHelpers) {
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitExtends)) {
writeLines(extendsHelper);
extendsEmitted = true;
}
decorateEmitted = true;
}
if (!paramEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitParam) {
writeLines(paramHelper);
paramEmitted = true;
if (!decorateEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitDecorate) {
writeLines(decorateHelper);
if (compilerOptions.emitDecoratorMetadata) {
writeLines(metadataHelper);
}
decorateEmitted = true;
}
if (!paramEmitted && resolver.getNodeCheckFlags(node) & NodeCheckFlags.EmitParam) {
writeLines(paramHelper);
paramEmitted = true;
}
}
if (isExternalModule(node) || compilerOptions.separateCompilation) {
@@ -5745,13 +5890,13 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
}
function hasDetachedComments(pos: number) {
return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos;
return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos;
}
function getLeadingCommentsWithoutDetachedComments() {
// get the leading comments from detachedPos
let leadingComments = getLeadingCommentRanges(currentSourceFile.text,
detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos);
lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@@ -5872,13 +6017,13 @@ if (typeof __param !== "function") __param = function (paramIndex, decorator) {
// All comments look like they could have been part of the copyright header. Make
// sure there is at least one blank line between it and the node. If not, it's not
// a copyright header.
let lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end);
let lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end);
let nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
// Valid detachedComments
emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
let currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end };
let currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: lastOrUndefined(detachedComments).end };
if (detachedCommentsInfo) {
detachedCommentsInfo.push(currentDetachedCommentInfo);
}
+7 -7
View File
@@ -308,9 +308,9 @@ module ts {
return visitNode(cbNode, (<ComputedPropertyName>node).expression);
case SyntaxKind.HeritageClause:
return visitNodes(cbNodes, (<HeritageClause>node).types);
case SyntaxKind.HeritageClauseElement:
return visitNode(cbNode, (<HeritageClauseElement>node).expression) ||
visitNodes(cbNodes, (<HeritageClauseElement>node).typeArguments);
case SyntaxKind.ExpressionWithTypeArguments:
return visitNode(cbNode, (<ExpressionWithTypeArguments>node).expression) ||
visitNodes(cbNodes, (<ExpressionWithTypeArguments>node).typeArguments);
case SyntaxKind.ExternalModuleReference:
return visitNode(cbNode, (<ExternalModuleReference>node).expression);
case SyntaxKind.MissingDeclaration:
@@ -1691,7 +1691,7 @@ module ts {
do {
templateSpans.push(parseTemplateSpan());
}
while (templateSpans[templateSpans.length - 1].literal.kind === SyntaxKind.TemplateMiddle)
while (lastOrUndefined(templateSpans).literal.kind === SyntaxKind.TemplateMiddle)
templateSpans.end = getNodeEnd();
template.templateSpans = templateSpans;
@@ -4284,15 +4284,15 @@ module ts {
let node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
node.token = token;
nextToken();
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseHeritageClauseElement);
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
return finishNode(node);
}
return undefined;
}
function parseHeritageClauseElement(): HeritageClauseElement {
let node = <HeritageClauseElement>createNode(SyntaxKind.HeritageClauseElement);
function parseExpressionWithTypeArguments(): ExpressionWithTypeArguments {
let node = <ExpressionWithTypeArguments>createNode(SyntaxKind.ExpressionWithTypeArguments);
node.expression = parseLeftHandSideExpressionOrHigher();
if (token === SyntaxKind.LessThanToken) {
node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
+9 -1
View File
@@ -10,6 +10,9 @@ module ts {
/** The version of the TypeScript compiler release */
export const version = "1.5.0";
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export function findConfigFile(searchPath: string): string {
var fileName = "tsconfig.json";
while (true) {
@@ -91,6 +94,11 @@ module ts {
}
}
let newLine =
options.newLine === NewLineKind.CarriageReturnLineFeed ? carriageReturnLineFeed :
options.newLine === NewLineKind.LineFeed ? lineFeed :
sys.newLine;
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
@@ -98,7 +106,7 @@ module ts {
getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName,
getNewLine: () => sys.newLine
getNewLine: () => newLine
};
}
+3 -6
View File
@@ -2,12 +2,10 @@
/// <reference path="diagnosticInformationMap.generated.ts"/>
module ts {
/* @internal */
export interface ErrorCallback {
(message: DiagnosticMessage, length: number): void;
}
/* @internal */
export interface Scanner {
getStartPos(): number;
getToken(): SyntaxKind;
@@ -522,7 +520,7 @@ module ts {
}
collecting = true;
if (result && result.length) {
result[result.length - 1].hasTrailingNewLine = true;
lastOrUndefined(result).hasTrailingNewLine = true;
}
continue;
case CharacterCodes.tab:
@@ -569,7 +567,7 @@ module ts {
default:
if (ch > CharacterCodes.maxAsciiCharacter && (isWhiteSpace(ch) || isLineBreak(ch))) {
if (result && result.length && isLineBreak(ch)) {
result[result.length - 1].hasTrailingNewLine = true;
lastOrUndefined(result).hasTrailingNewLine = true;
}
pos++;
continue;
@@ -600,8 +598,7 @@ module ts {
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
// Creates a scanner over a (possibly unspecified) range of a piece of text.
/* @internal */
/** Creates a scanner over a (possibly unspecified) range of a piece of text. */
export function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner {
let pos: number; // Current position (end position of text of current token)
let end: number; // end of text
+10 -3
View File
@@ -206,9 +206,9 @@ module ts {
SpreadElementExpression,
ClassExpression,
OmittedExpression,
ExpressionWithTypeArguments,
// Misc
TemplateSpan,
HeritageClauseElement,
SemicolonClassElement,
// Element
Block,
@@ -741,7 +741,7 @@ module ts {
arguments: NodeArray<Expression>;
}
export interface HeritageClauseElement extends TypeNode {
export interface ExpressionWithTypeArguments extends TypeNode {
expression: LeftHandSideExpression;
typeArguments?: NodeArray<TypeNode>;
}
@@ -893,7 +893,7 @@ module ts {
export interface HeritageClause extends Node {
token: SyntaxKind;
types?: NodeArray<HeritageClauseElement>;
types?: NodeArray<ExpressionWithTypeArguments>;
}
export interface TypeAliasDeclaration extends Declaration, ModuleElement {
@@ -1664,7 +1664,9 @@ module ts {
locale?: string;
mapRoot?: string;
module?: ModuleKind;
newLine?: NewLineKind;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
@@ -1700,6 +1702,11 @@ module ts {
System = 4,
}
export const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
}
export interface LineAndCharacter {
line: number;
/*
+8 -8
View File
@@ -856,7 +856,7 @@ module ts {
}
export function hasRestParameters(s: SignatureDeclaration): boolean {
return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined;
return s.parameters.length > 0 && lastOrUndefined(s.parameters).dotDotDotToken !== undefined;
}
export function isLiteralKind(kind: SyntaxKind): boolean {
@@ -1362,7 +1362,7 @@ module ts {
let lineStartsOfS = computeLineStarts(s);
if (lineStartsOfS.length > 1) {
lineCount = lineCount + lineStartsOfS.length - 1;
linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1];
linePos = output.length - s.length + lastOrUndefined(lineStartsOfS);
}
}
}
@@ -1671,16 +1671,16 @@ module ts {
// Returns false if this heritage clause element's expression contains something unsupported
// (i.e. not a name or dotted name).
export function isSupportedHeritageClauseElement(node: HeritageClauseElement): boolean {
return isSupportedHeritageClauseElementExpression(node.expression);
export function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean {
return isSupportedExpressionWithTypeArgumentsRest(node.expression);
}
function isSupportedHeritageClauseElementExpression(node: Expression): boolean {
function isSupportedExpressionWithTypeArgumentsRest(node: Expression): boolean {
if (node.kind === SyntaxKind.Identifier) {
return true;
}
else if (node.kind === SyntaxKind.PropertyAccessExpression) {
return isSupportedHeritageClauseElementExpression((<PropertyAccessExpression>node).expression);
return isSupportedExpressionWithTypeArgumentsRest((<PropertyAccessExpression>node).expression);
}
else {
return false;
@@ -1727,8 +1727,8 @@ module ts {
output.push(((charCode >> 6) & 0B00111111) | 0B10000000);
output.push((charCode & 0B00111111) | 0B10000000);
}
else {
Debug.assert(false, "Unexpected code point");
else {
Debug.assert(false, "Unexpected code point");
}
}
+33 -1
View File
@@ -1571,6 +1571,28 @@ module FourSlash {
this.currentCaretPosition = definition.textSpan.start;
}
public goToTypeDefinition(definitionIndex: number) {
if (definitionIndex === 0) {
this.scenarioActions.push('<GoToTypeDefinition />');
}
else {
this.taoInvalidReason = 'GoToTypeDefinition not supported for non-zero definition indices';
}
var definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
if (!definitions || !definitions.length) {
this.raiseError('goToTypeDefinition failed - expected to at least one definition location but got 0');
}
if (definitionIndex >= definitions.length) {
this.raiseError('goToTypeDefinition failed - definitionIndex value (' + definitionIndex + ') exceeds definition list size (' + definitions.length + ')');
}
var definition = definitions[definitionIndex];
this.openFile(definition.fileName);
this.currentCaretPosition = definition.textSpan.start;
}
public verifyDefinitionLocationExists(negative: boolean) {
this.taoInvalidReason = 'verifyDefinitionLocationExists NYI';
@@ -1590,8 +1612,18 @@ module FourSlash {
var assertFn = negative ? assert.notEqual : assert.equal;
var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var actualCount = definitions && definitions.length || 0;
assertFn(definitions.length, expectedCount, this.messageAtLastKnownMarker("Definitions Count"));
assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Definitions Count"));
}
public verifyTypeDefinitionsCount(negative: boolean, expectedCount: number) {
var assertFn = negative ? assert.notEqual : assert.equal;
var definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
var actualCount = definitions && definitions.length || 0;
assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Type definitions Count"));
}
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
+39 -11
View File
@@ -806,6 +806,9 @@ module Harness {
return result;
}
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export var defaultLibFileName = 'lib.d.ts';
export var defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export var defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
@@ -823,7 +826,8 @@ module Harness {
scriptTarget: ts.ScriptTarget,
useCaseSensitiveFileNames: boolean,
// the currentDirectory is needed for rwcRunner to passed in specified current directory to compiler host
currentDirectory?: string): ts.CompilerHost {
currentDirectory?: string,
newLineKind?: ts.NewLineKind): ts.CompilerHost {
// Local get canonical file name function, that depends on passed in parameter for useCaseSensitiveFileNames
function getCanonicalFileName(fileName: string): string {
@@ -842,6 +846,11 @@ module Harness {
};
inputFiles.forEach(register);
let newLine =
newLineKind === ts.NewLineKind.CarriageReturnLineFeed ? carriageReturnLineFeed :
newLineKind === ts.NewLineKind.LineFeed ? lineFeed :
ts.sys.newLine;
return {
getCurrentDirectory,
getSourceFile: (fn, languageVersion) => {
@@ -870,7 +879,7 @@ module Harness {
writeFile,
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => ts.sys.newLine
getNewLine: () => newLine
};
}
@@ -960,7 +969,7 @@ module Harness {
var programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
var program = ts.createProgram(programFiles, options, createCompilerHost(inputFiles.concat(includeBuiltFiles).concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target, useCaseSensitiveFileNames, currentDirectory));
options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine));
var emitResult = program.emit();
@@ -977,7 +986,7 @@ module Harness {
// reset what newline means in case the last test changed it
ts.sys.newLine = newLine;
return options;
function setOptionForSetting(setting: Harness.TestCaseParser.CompilerSetting) {
switch (setting.flag.toLowerCase()) {
// "fileName", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve"
@@ -1019,6 +1028,14 @@ module Harness {
}
break;
case 'emitdecoratormetadata':
options.emitDecoratorMetadata = setting.value === 'true';
break;
case 'noemithelpers':
options.noEmitHelpers = setting.value === 'true';
break;
case 'noemitonerror':
options.noEmitOnError = !!setting.value;
break;
@@ -1062,7 +1079,18 @@ module Harness {
break;
case 'newline':
case 'newlines':
if (setting.value.toLowerCase() === 'crlf') {
options.newLine = ts.NewLineKind.CarriageReturnLineFeed;
}
else if (setting.value.toLowerCase() === 'lf') {
options.newLine = ts.NewLineKind.LineFeed;
}
else {
throw new Error('Unknown option for newLine: ' + setting.value);
}
break;
case 'normalizenewline':
newLine = setting.value;
break;
@@ -1116,8 +1144,8 @@ module Harness {
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
}
}
}
}
}
public compileDeclarationFiles(inputFiles: { unitName: string; content: string; }[],
@@ -1483,12 +1511,12 @@ module Harness {
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module",
"nolib", "sourcemap", "target", "out", "outdir", "noemitonerror",
"noimplicitany", "noresolve", "newline", "newlines", "emitbom",
"nolib", "sourcemap", "target", "out", "outdir", "noemithelpers", "noemitonerror",
"noimplicitany", "noresolve", "newline", "normalizenewline", "emitbom",
"errortruncation", "usecasesensitivefilenames", "preserveconstenums",
"includebuiltfile", "suppressimplicitanyindexerrors", "stripinternal",
"separatecompilation", "inlinesourcemap", "maproot", "sourceroot",
"inlinesources"];
"inlinesources", "emitdecoratormetadata"];
function extractCompilerSettings(content: string): CompilerSetting[] {
@@ -1742,4 +1770,4 @@ module Harness {
}
// TODO: not sure why Utils.evalFile isn't working with this, eventually will concat it like old compiler instead of eval
eval(Harness.tcServicesFile);
eval(Harness.tcServicesFile);
+12
View File
@@ -241,6 +241,9 @@ module Harness.LanguageService {
class ClassifierShimProxy implements ts.Classifier {
constructor(private shim: ts.ClassifierShim) {
}
getEncodedLexicalClassifications(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.Classifications {
throw new Error("NYI");
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
var result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
var entries: ts.ClassificationInfo[] = [];
@@ -306,6 +309,12 @@ module Harness.LanguageService {
getSemanticClassifications(fileName: string, span: ts.TextSpan): ts.ClassifiedSpan[] {
return unwrapJSONCallResult(this.shim.getSemanticClassifications(fileName, span.start, span.length));
}
getEncodedSyntacticClassifications(fileName: string, span: ts.TextSpan): ts.Classifications {
return unwrapJSONCallResult(this.shim.getEncodedSyntacticClassifications(fileName, span.start, span.length));
}
getEncodedSemanticClassifications(fileName: string, span: ts.TextSpan): ts.Classifications {
return unwrapJSONCallResult(this.shim.getEncodedSemanticClassifications(fileName, span.start, span.length));
}
getCompletionsAtPosition(fileName: string, position: number): ts.CompletionInfo {
return unwrapJSONCallResult(this.shim.getCompletionsAtPosition(fileName, position));
}
@@ -333,6 +342,9 @@ module Harness.LanguageService {
getDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[] {
return unwrapJSONCallResult(this.shim.getDefinitionAtPosition(fileName, position));
}
getTypeDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[]{
return unwrapJSONCallResult(this.shim.getTypeDefinitionAtPosition(fileName, position));
}
getReferencesAtPosition(fileName: string, position: number): ts.ReferenceEntry[] {
return unwrapJSONCallResult(this.shim.getReferencesAtPosition(fileName, position));
}
+36 -76
View File
@@ -331,7 +331,7 @@ class ProjectRunner extends RunnerBase {
var name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
describe(name, () => {
function verifyCompilerResults(compilerResult: BatchCompileProjectTestCaseResult) {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
function getCompilerResolutionInfo() {
var resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
scenario: testCase.scenario,
@@ -356,23 +356,33 @@ class ProjectRunner extends RunnerBase {
return resolutionInfo;
}
it('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, () => {
var compilerResult: BatchCompileProjectTestCaseResult;
it(name + ": " + moduleNameToString(moduleKind) , () => {
// Compile using node
compilerResult = batchCompilerProjectTestCase(moduleKind);
});
it('Resolution information of (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Resolution information of (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.json', () => {
return JSON.stringify(getCompilerResolutionInfo(), undefined, " ");
});
});
if (compilerResult.errors.length) {
it('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, () => {
it('Errors for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (compilerResult.errors.length) {
Harness.Baseline.runBaseline('Errors for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.errors.txt', () => {
return getErrorsBaseline(compilerResult);
});
});
}
}
});
it('Baseline of emitted result (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
if (testCase.baselineCheck) {
ts.forEach(compilerResult.outputFiles, outputFile => {
it('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Baseline of emitted result (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + outputFile.fileName, () => {
try {
return ts.sys.readFile(getProjectOutputFolder(outputFile.fileName, compilerResult.moduleKind));
@@ -382,89 +392,39 @@ class ProjectRunner extends RunnerBase {
}
});
});
});
}
});
it('SourceMapRecord for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (compilerResult.sourceMapData) {
it('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
Harness.Baseline.runBaseline('SourceMapRecord for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.sourcemap.txt', () => {
return Harness.SourceMapRecoder.getSourceMapRecord(compilerResult.sourceMapData, compilerResult.program,
ts.filter(compilerResult.outputFiles, outputFile => Harness.Compiler.isJS(outputFile.emittedFileName)));
});
}
});
// Verify that all the generated .d.ts files compile
// Verify that all the generated .d.ts files compile
it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
var dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
it('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, () => {
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
return getErrorsBaseline(dTsCompileResult);
});
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
return getErrorsBaseline(dTsCompileResult);
});
}
}
}
}
var nodeCompilerResult: BatchCompileProjectTestCaseResult;
var amdCompilerResult: BatchCompileProjectTestCaseResult;
it(name + ": node", () => {
// Compile using node
nodeCompilerResult = batchCompilerProjectTestCase(ts.ModuleKind.CommonJS);
verifyCompilerResults(nodeCompilerResult);
});
it(name + ": amd", () => {
// Compile using amd
amdCompilerResult = batchCompilerProjectTestCase(ts.ModuleKind.AMD);
verifyCompilerResults(amdCompilerResult);
});
if (testCase.runTest) {
it(name + ": runTest", () => {
if (!nodeCompilerResult || !amdCompilerResult) {
return;
}
//TODO(ryanca/danquirk): Either support this or remove this option from the interface as well as test case json files
// Node results
assert.isTrue(!nodeCompilerResult.nonSubfolderDiskFiles, "Cant run test case that generates parent folders/absolute path");
//it("runs without error: (" + moduleNameToString(nodeCompilerResult.moduleKind) + ')', function (done: any) {
// Exec.exec("node.exe", ['"' + baseLineLocalPath(nodeCompilerResult.outputFiles[0].diskRelativeName, nodeCompilerResult.moduleKind) + '"'], function (res) {
// Harness.Assert.equal(res.stdout, "");
// Harness.Assert.equal(res.stderr, "");
// done();
// })
//});
// Amd results
assert.isTrue(!amdCompilerResult.nonSubfolderDiskFiles, "Cant run test case that generates parent folders/absolute path");
//var amdDriverTemplate = "var requirejs = require('../r.js');\n\n" +
// "requirejs.config({\n" +
// " nodeRequire: require\n" +
// "});\n\n" +
// "requirejs(['{0}'],\n" +
// "function ({0}) {\n" +
// "});";
//var moduleName = baseLineLocalPath(amdCompilerResult.outputFiles[0].diskRelativeName, amdCompilerResult.moduleKind).replace(/\.js$/, "");
//sys.writeFile(testCase.projectRoot + '/driver.js', amdDriverTemplate.replace(/\{0}/g, moduleName));
//it("runs without error (" + moduleNameToString(amdCompilerResult.moduleKind) + ')', function (done: any) {
// Exec.exec("node.exe", ['"' + testCase.projectRoot + '/driver.js"'], function (res) {
// Harness.Assert.equal(res.stdout, "");
// Harness.Assert.equal(res.stderr, "");
// done();
// })
//});
});
after(() => {
nodeCompilerResult = undefined;
amdCompilerResult = undefined;
compilerResult = undefined;
});
}
verifyCompilerResults(ts.ModuleKind.CommonJS);
verifyCompilerResults(ts.ModuleKind.AMD);
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
+10
View File
@@ -3697,6 +3697,8 @@ interface HTMLCanvasElement extends HTMLElement {
* Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.
* @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl");
*/
getContext(contextId: "2d"): CanvasRenderingContext2D;
getContext(contextId: "experimental-webgl"): WebGLRenderingContext;
getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext;
/**
* Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.
@@ -12332,11 +12334,13 @@ interface DocumentEvent {
createEvent(eventInterface:"CloseEvent"): CloseEvent;
createEvent(eventInterface:"CommandEvent"): CommandEvent;
createEvent(eventInterface:"CompositionEvent"): CompositionEvent;
createEvent(eventInterface: "CustomEvent"): CustomEvent;
createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent;
createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent;
createEvent(eventInterface:"DragEvent"): DragEvent;
createEvent(eventInterface:"ErrorEvent"): ErrorEvent;
createEvent(eventInterface:"Event"): Event;
createEvent(eventInterface:"Events"): Event;
createEvent(eventInterface:"FocusEvent"): FocusEvent;
createEvent(eventInterface:"GamepadEvent"): GamepadEvent;
createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent;
@@ -12351,8 +12355,12 @@ interface DocumentEvent {
createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent;
createEvent(eventInterface:"MessageEvent"): MessageEvent;
createEvent(eventInterface:"MouseEvent"): MouseEvent;
createEvent(eventInterface:"MouseEvents"): MouseEvent;
createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent;
createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent;
createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent;
createEvent(eventInterface:"MutationEvent"): MutationEvent;
createEvent(eventInterface:"MutationEvents"): MutationEvent;
createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent;
createEvent(eventInterface:"NavigationEvent"): NavigationEvent;
createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer;
@@ -12363,6 +12371,7 @@ interface DocumentEvent {
createEvent(eventInterface:"PopStateEvent"): PopStateEvent;
createEvent(eventInterface:"ProgressEvent"): ProgressEvent;
createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent;
createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent;
createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent;
createEvent(eventInterface:"StorageEvent"): StorageEvent;
createEvent(eventInterface:"TextEvent"): TextEvent;
@@ -12370,6 +12379,7 @@ interface DocumentEvent {
createEvent(eventInterface:"TrackEvent"): TrackEvent;
createEvent(eventInterface:"TransitionEvent"): TransitionEvent;
createEvent(eventInterface:"UIEvent"): UIEvent;
createEvent(eventInterface:"UIEvents"): UIEvent;
createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent;
createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent;
createEvent(eventInterface:"WheelEvent"): WheelEvent;
+52 -18
View File
@@ -51,11 +51,41 @@ interface SymbolConstructor {
isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object.Called by the semantics of the
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
split: symbol;
/**
* A method that converts an object to a corresponding primitive value.Called by the ToPrimitive
* abstract operation.
@@ -3542,6 +3572,16 @@ declare module Reflect {
function setPrototypeOf(target: any, proto: any): boolean;
}
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
}
/**
* Represents the completion of an asynchronous operation
*/
@@ -3552,14 +3592,16 @@ interface Promise<T> {
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | Promise<TResult>, onrejected?: (reason: any) => TResult | Promise<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | Promise<T>): Promise<T>;
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
[Symbol.toStringTag]: string;
}
interface PromiseConstructor {
@@ -3570,13 +3612,11 @@ interface PromiseConstructor {
/**
* Creates a new Promise.
* @param init A callback used to initialize the promise. This callback is passed two arguments:
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(init: (resolve: (value?: T | Promise<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
<T>(init: (resolve: (value?: T | Promise<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -3584,15 +3624,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of values.
* @returns A new Promise.
*/
all(values: Promise<void>[]): Promise<void>;
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
@@ -3600,7 +3632,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: (T | Promise<T>)[]): Promise<T>;
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
/**
* Creates a new rejected promise for the provided reason.
@@ -3621,13 +3653,15 @@ interface PromiseConstructor {
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | Promise<T>): Promise<T>;
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
[Symbol.species]: Function;
}
declare var Promise: PromiseConstructor;
+133
View File
@@ -45,6 +45,139 @@ interface ArrayBufferView {
byteOffset: number;
}
interface DataView {
buffer: ArrayBuffer;
byteLength: number;
byteOffset: number;
/**
* Gets the Float32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Float64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getFloat64(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt8(byteOffset: number): number;
/**
* Gets the Int16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Int32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getInt32(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint8 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint8(byteOffset: number): number;
/**
* Gets the Uint16 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint16(byteOffset: number, littleEndian: boolean): number;
/**
* Gets the Uint32 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
*/
getUint32(byteOffset: number, littleEndian: boolean): number;
/**
* Stores an Float32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Float64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setFloat64(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setInt8(byteOffset: number, value: number): void;
/**
* Stores an Int16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Int32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setInt32(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint8 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
*/
setUint8(byteOffset: number, value: number): void;
/**
* Stores an Uint16 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint16(byteOffset: number, value: number, littleEndian: boolean): void;
/**
* Stores an Uint32 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written,
* otherwise a little-endian value should be written.
*/
setUint32(byteOffset: number, value: number, littleEndian: boolean): void;
}
interface DataViewConstructor {
new (buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): DataView;
}
declare var DataView: DataViewConstructor;
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
+34
View File
@@ -300,6 +300,32 @@ module ts.server {
});
}
getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
file: fileName,
line: lineOffset.line,
offset: lineOffset.offset,
};
var request = this.processRequest<protocol.TypeDefinitionRequest>(CommandNames.TypeDefinition, args);
var response = this.processResponse<protocol.TypeDefinitionResponse>(request);
return response.body.map(entry => {
var fileName = entry.file;
var start = this.lineOffsetToPosition(fileName, entry.start);
var end = this.lineOffsetToPosition(fileName, entry.end);
return {
containerKind: "",
containerName: "",
fileName: fileName,
textSpan: ts.createTextSpanFromBounds(start, end),
kind: "",
name: ""
};
});
}
findReferences(fileName: string, position: number): ReferencedSymbol[]{
// Not yet implemented.
return [];
@@ -533,6 +559,14 @@ module ts.server {
throw new Error("Not Implemented Yet.");
}
getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications {
throw new Error("Not Implemented Yet.");
}
getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications {
throw new Error("Not Implemented Yet.");
}
getProgram(): Program {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
+4 -3
View File
@@ -424,7 +424,7 @@ module ts.server {
getFormatCodeOptions(file?: string) {
if (file) {
var info = this.filenameToScriptInfo[file];
var info = this.filenameToScriptInfo[file];
if (info) {
return info.formatCodeOptions;
}
@@ -750,6 +750,7 @@ module ts.server {
if (content !== undefined) {
var indentSize: number;
info = new ScriptInfo(this.host, fileName, content, openedByClient);
info.setFormatOptions(this.getFormatCodeOptions());
this.filenameToScriptInfo[fileName] = info;
if (!info.isOpen) {
info.fileWatcher = this.host.watchFile(fileName, _ => { this.watchedFileChanged(fileName); });
@@ -772,7 +773,7 @@ module ts.server {
findConfigFile(searchPath: string): string {
while (true) {
var fileName = ts.combinePaths(searchPath, "tsconfig.json");
if (sys.fileExists(fileName)) {
if (this.host.fileExists(fileName)) {
return fileName;
}
var parentPath = ts.getDirectoryPath(searchPath);
@@ -922,7 +923,7 @@ module ts.server {
var proj = this.createProject(configFilename, projectOptions);
for (var i = 0, len = parsedCommandLine.fileNames.length; i < len; i++) {
var rootFilename = parsedCommandLine.fileNames[i];
if (ts.sys.fileExists(rootFilename)) {
if (this.host.fileExists(rootFilename)) {
var info = this.openFile(rootFilename, clientFileName == rootFilename);
proj.addRoot(info);
}
+15
View File
@@ -125,6 +125,14 @@ declare module ts.server.protocol {
export interface DefinitionRequest extends FileLocationRequest {
}
/**
* Go to type request; value of command field is
* "typeDefinition". Return response giving the file locations that
* define the type for the symbol found in file at location line, col.
*/
export interface TypeDefinitionRequest extends FileLocationRequest {
}
/**
* Location in source code expressed as (one-based) line and character offset.
*/
@@ -165,6 +173,13 @@ declare module ts.server.protocol {
body?: FileSpan[];
}
/**
* Definition response message. Gives text range for definition.
*/
export interface TypeDefinitionResponse extends Response {
body?: FileSpan[];
}
/**
* Get occurrences request; value of command field is
* "occurrences". Return response giving spans that are relevant
+30 -2
View File
@@ -97,6 +97,7 @@ module ts.server {
export var Rename = "rename";
export var Saveto = "saveto";
export var SignatureHelp = "signatureHelp";
export var TypeDefinition = "typeDefinition";
export var Unknown = "unknown";
}
@@ -285,7 +286,29 @@ module ts.server {
}));
}
getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[] {
getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] {
var file = ts.normalizePath(fileName);
var project = this.projectService.getProjectForFile(file);
if (!project) {
throw Errors.NoProject;
}
var compilerService = project.compilerService;
var position = compilerService.host.lineOffsetToPosition(file, line, offset);
var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position);
if (!definitions) {
return undefined;
}
return definitions.map(def => ({
file: def.fileName,
start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start),
end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan))
}));
}
getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[]{
fileName = ts.normalizePath(fileName);
let project = this.projectService.getProjectForFile(fileName);
@@ -519,7 +542,7 @@ module ts.server {
IndentSize: formatOptions.IndentSize,
TabSize: formatOptions.TabSize,
NewLineCharacter: "\n",
ConvertTabsToSpaces: true,
ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces,
};
var indentPosition =
compilerService.languageService.getIndentationAtPosition(file, position, editorOptions);
@@ -817,6 +840,11 @@ module ts.server {
response = this.getDefinition(defArgs.line, defArgs.offset, defArgs.file);
break;
}
case CommandNames.TypeDefinition: {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file);
break;
}
case CommandNames.References: {
var refArgs = <protocol.FileLocationRequestArgs>request.arguments;
response = this.getReferences(refArgs.line, refArgs.offset, refArgs.file);
+3 -3
View File
@@ -446,14 +446,14 @@ module ts.BreakpointResolver {
// fall through.
case SyntaxKind.CatchClause:
return spanInNode((<Block>node.parent).statements[(<Block>node.parent).statements.length - 1]);;
return spanInNode(lastOrUndefined((<Block>node.parent).statements));;
case SyntaxKind.CaseBlock:
// breakpoint in last statement of the last clause
let caseBlock = <CaseBlock>node.parent;
let lastClause = caseBlock.clauses[caseBlock.clauses.length - 1];
let lastClause = lastOrUndefined(caseBlock.clauses);
if (lastClause) {
return spanInNode(lastClause.statements[lastClause.statements.length - 1]);
return spanInNode(lastOrUndefined(lastClause.statements));
}
return undefined;
+9 -2
View File
@@ -323,6 +323,9 @@ module ts.formatting {
let previousParent: Node;
let previousRangeStartLine: number;
let lastIndentedLine: number;
let indentationOnLastIndentedLine: number;
let edits: TextChange[] = [];
formattingScanner.advance();
@@ -416,7 +419,9 @@ module ts.formatting {
// if node is located on the same line with the parent
// - inherit indentation from the parent
// - push children if either parent of node itself has non-zero delta
indentation = parentDynamicIndentation.getIndentation();
indentation = startLine === lastIndentedLine
? indentationOnLastIndentedLine
: parentDynamicIndentation.getIndentation();
delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta);
}
return {
@@ -716,7 +721,6 @@ module ts.formatting {
continue;
}
let triviaStartLine = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos).line;
switch (triviaItem.kind) {
case SyntaxKind.MultiLineCommentTrivia:
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind);
@@ -741,6 +745,9 @@ module ts.formatting {
if (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) {
let tokenIndentation = dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind);
insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded);
lastIndentedLine = tokenStart.line;
indentationOnLastIndentedLine = tokenIndentation;
}
}
+1 -1
View File
@@ -51,7 +51,7 @@ module ts.formatting {
if (isStarted) {
if (trailingTrivia) {
Debug.assert(trailingTrivia.length !== 0);
wasNewLine = trailingTrivia[trailingTrivia.length - 1].kind === SyntaxKind.NewLineTrivia;
wasNewLine = lastOrUndefined(trailingTrivia).kind === SyntaxKind.NewLineTrivia;
}
else {
wasNewLine = false;
+348 -153
View File
@@ -197,6 +197,9 @@ module ts {
let list = createNode(SyntaxKind.SyntaxList, nodes.pos, nodes.end, NodeFlags.Synthetic, this);
list._children = [];
let pos = nodes.pos;
for (let node of nodes) {
if (pos < node.pos) {
pos = this.addSyntheticNodes(list._children, pos, node.pos);
@@ -969,9 +972,20 @@ module ts {
getSemanticDiagnostics(fileName: string): Diagnostic[];
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* @deprecated Use getEncodedSyntacticClassifications instead.
*/
getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
/**
* @deprecated Use getEncodedSemanticClassifications instead.
*/
getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[];
// Encoded as triples of [start, length, ClassificationType].
getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications;
getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications;
getCompletionsAtPosition(fileName: string, position: number): CompletionInfo;
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails;
@@ -987,6 +1001,8 @@ module ts {
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[];
getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[];
getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[];
getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[];
findReferences(fileName: string, position: number): ReferencedSymbol[];
getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[];
@@ -1015,6 +1031,11 @@ module ts {
dispose(): void;
}
export interface Classifications {
spans: number[],
endOfLineState: EndOfLineState
}
export interface ClassifiedSpan {
textSpan: TextSpan;
classificationType: string; // ClassificationTypeNames
@@ -1258,7 +1279,7 @@ module ts {
}
export const enum EndOfLineState {
Start,
None,
InMultiLineCommentTrivia,
InSingleQuoteStringLiteral,
InDoubleQuoteStringLiteral,
@@ -1308,8 +1329,10 @@ module ts {
* classifications which may be incorrectly categorized will be given
* back as Identifiers in order to allow the syntactic classifier to
* subsume the classification.
* @deprecated Use getLexicalClassifications instead.
*/
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult;
getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications;
}
/**
@@ -1484,7 +1507,28 @@ module ts {
public static interfaceName = "interface name";
public static moduleName = "module name";
public static typeParameterName = "type parameter name";
public static typeAlias = "type alias name";
public static typeAliasName = "type alias name";
public static parameterName = "parameter name";
}
export const enum ClassificationType {
comment = 1,
identifier = 2,
keyword = 3,
numericLiteral = 4,
operator = 5,
stringLiteral = 6,
regularExpressionLiteral = 7,
whiteSpace = 8,
text = 9,
punctuation = 10,
className = 11,
enumName = 12,
interfaceName = 13,
moduleName = 14,
typeParameterName = 15,
typeAliasName = 16,
parameterName = 17
}
/// Language Service
@@ -3460,19 +3504,6 @@ module ts {
return ScriptElementKind.unknown;
}
function getTypeKind(type: Type): string {
let flags = type.getFlags();
if (flags & TypeFlags.Enum) return ScriptElementKind.enumElement;
if (flags & TypeFlags.Class) return ScriptElementKind.classElement;
if (flags & TypeFlags.Interface) return ScriptElementKind.interfaceElement;
if (flags & TypeFlags.TypeParameter) return ScriptElementKind.typeParameterElement;
if (flags & TypeFlags.Intrinsic) return ScriptElementKind.primitiveType;
if (flags & TypeFlags.StringLiteral) return ScriptElementKind.primitiveType;
return ScriptElementKind.unknown;
}
function getSymbolModifiers(symbol: Symbol): string {
return symbol && symbol.declarations && symbol.declarations.length > 0
? getNodeModifiers(symbol.declarations[0])
@@ -3887,6 +3918,71 @@ module ts {
};
}
function getDefinitionFromSymbol(symbol: Symbol, node: Node): DefinitionInfo[] {
let typeChecker = program.getTypeChecker();
let result: DefinitionInfo[] = [];
let declarations = symbol.getDeclarations();
let symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
let symbolKind = getSymbolKind(symbol, node);
let containerSymbol = symbol.parent;
let containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : "";
if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) &&
!tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) {
// Just add all the declarations.
forEach(declarations, declaration => {
result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName));
});
}
return result;
function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: string, 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) {
if (symbol.flags & SymbolFlags.Class) {
let classDeclaration = <ClassDeclaration>symbol.getDeclarations()[0];
Debug.assert(classDeclaration && classDeclaration.kind === SyntaxKind.ClassDeclaration);
return tryAddSignature(classDeclaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result);
}
}
return false;
}
function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: string, 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[], selectConstructors: boolean, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) {
let declarations: Declaration[] = [];
let definition: Declaration;
forEach(signatureDeclarations, d => {
if ((selectConstructors && d.kind === SyntaxKind.Constructor) ||
(!selectConstructors && (d.kind === SyntaxKind.FunctionDeclaration || d.kind === SyntaxKind.MethodDeclaration || d.kind === SyntaxKind.MethodSignature))) {
declarations.push(d);
if ((<FunctionLikeDeclaration>d).body) definition = d;
}
});
if (definition) {
result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName));
return true;
}
else if (declarations.length) {
result.push(createDefinitionInfo(lastOrUndefined(declarations), symbolKind, symbolName, containerName));
return true;
}
return false;
}
}
/// Goto definition
function getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
synchronizeHostData();
@@ -3961,67 +4057,47 @@ module ts {
declaration => createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName));
}
let result: DefinitionInfo[] = [];
let declarations = symbol.getDeclarations();
let symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol
let symbolKind = getSymbolKind(symbol, node);
let containerSymbol = symbol.parent;
let containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : "";
return getDefinitionFromSymbol(symbol, node);
}
if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) &&
!tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) {
// Just add all the declarations.
forEach(declarations, declaration => {
result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName));
});
/// Goto type
function getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
synchronizeHostData();
let sourceFile = getValidSourceFile(fileName);
let node = getTouchingPropertyName(sourceFile, position);
if (!node) {
return undefined;
}
return result;
let typeChecker = program.getTypeChecker();
function tryAddConstructSignature(symbol: Symbol, location: Node, symbolKind: string, 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) {
if (symbol.flags & SymbolFlags.Class) {
let classDeclaration = <ClassDeclaration>symbol.getDeclarations()[0];
Debug.assert(classDeclaration && classDeclaration.kind === SyntaxKind.ClassDeclaration);
return tryAddSignature(classDeclaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result);
}
}
return false;
let symbol = typeChecker.getSymbolAtLocation(node);
if (!symbol) {
return undefined;
}
function tryAddCallSignature(symbol: Symbol, location: Node, symbolKind: string, 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;
let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node);
if (!type) {
return undefined;
}
function tryAddSignature(signatureDeclarations: Declaration[], selectConstructors: boolean, symbolKind: string, symbolName: string, containerName: string, result: DefinitionInfo[]) {
let declarations: Declaration[] = [];
let definition: Declaration;
forEach(signatureDeclarations, d => {
if ((selectConstructors && d.kind === SyntaxKind.Constructor) ||
(!selectConstructors && (d.kind === SyntaxKind.FunctionDeclaration || d.kind === SyntaxKind.MethodDeclaration || d.kind === SyntaxKind.MethodSignature))) {
declarations.push(d);
if ((<FunctionLikeDeclaration>d).body) definition = d;
if (type.flags & TypeFlags.Union) {
var result: DefinitionInfo[] = [];
forEach((<UnionType>type).types, t => {
if (t.symbol) {
result.push(...getDefinitionFromSymbol(t.symbol, node));
}
});
if (definition) {
result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName));
return true;
}
else if (declarations.length) {
result.push(createDefinitionInfo(declarations[declarations.length - 1], symbolKind, symbolName, containerName));
return true;
}
return false;
return result;
}
if (!type.symbol) {
return undefined;
}
return getDefinitionFromSymbol(type.symbol, node);
}
function getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
@@ -5373,7 +5449,7 @@ module ts {
}
return;
function getPropertySymbolFromTypeReference(typeReference: HeritageClauseElement) {
function getPropertySymbolFromTypeReference(typeReference: ExpressionWithTypeArguments) {
if (typeReference) {
let type = typeChecker.getTypeAtLocation(typeReference);
if (type) {
@@ -5634,7 +5710,7 @@ module ts {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeReference || node.parent.kind === SyntaxKind.HeritageClauseElement;
return node.parent.kind === SyntaxKind.TypeReference || node.parent.kind === SyntaxKind.ExpressionWithTypeArguments;
}
function isNamespaceReference(node: Node): boolean {
@@ -5652,7 +5728,7 @@ module ts {
isLastClause = (<PropertyAccessExpression>root).name === node;
}
if (!isLastClause && root.parent.kind === SyntaxKind.HeritageClauseElement && root.parent.parent.kind === SyntaxKind.HeritageClause) {
if (!isLastClause && root.parent.kind === SyntaxKind.ExpressionWithTypeArguments && root.parent.parent.kind === SyntaxKind.HeritageClause) {
let decl = root.parent.parent.parent;
return (decl.kind === SyntaxKind.ClassDeclaration && (<HeritageClause>root.parent.parent).token === SyntaxKind.ImplementsKeyword) ||
(decl.kind === SyntaxKind.InterfaceDeclaration && (<HeritageClause>root.parent.parent).token === SyntaxKind.ExtendsKeyword);
@@ -5804,35 +5880,45 @@ module ts {
return NavigationBar.getNavigationBarItems(sourceFile);
}
function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]{
return convertClassifications(getEncodedSemanticClassifications(fileName, span));
}
function getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications {
synchronizeHostData();
let sourceFile = getValidSourceFile(fileName);
let typeChecker = program.getTypeChecker();
let result: ClassifiedSpan[] = [];
let result: number[] = [];
processNode(sourceFile);
return result;
return { spans: result, endOfLineState: EndOfLineState.None };
function classifySymbol(symbol: Symbol, meaningAtPosition: SemanticMeaning) {
function pushClassification(start: number, length: number, type: ClassificationType) {
result.push(start);
result.push(length);
result.push(type);
}
function classifySymbol(symbol: Symbol, meaningAtPosition: SemanticMeaning): ClassificationType {
let flags = symbol.getFlags();
if (flags & SymbolFlags.Class) {
return ClassificationTypeNames.className;
return ClassificationType.className;
}
else if (flags & SymbolFlags.Enum) {
return ClassificationTypeNames.enumName;
return ClassificationType.enumName;
}
else if (flags & SymbolFlags.TypeAlias) {
return ClassificationTypeNames.typeAlias;
return ClassificationType.typeAliasName;
}
else if (meaningAtPosition & SemanticMeaning.Type) {
if (flags & SymbolFlags.Interface) {
return ClassificationTypeNames.interfaceName;
return ClassificationType.interfaceName;
}
else if (flags & SymbolFlags.TypeParameter) {
return ClassificationTypeNames.typeParameterName;
return ClassificationType.typeParameterName;
}
}
else if (flags & SymbolFlags.Module) {
@@ -5841,7 +5927,7 @@ module ts {
// - There exists a module declaration which actually impacts the value side.
if (meaningAtPosition & SemanticMeaning.Namespace ||
(meaningAtPosition & SemanticMeaning.Value && hasValueSideModule(symbol))) {
return ClassificationTypeNames.moduleName;
return ClassificationType.moduleName;
}
}
@@ -5865,10 +5951,7 @@ module ts {
if (symbol) {
let type = classifySymbol(symbol, getMeaningFromLocation(node));
if (type) {
result.push({
textSpan: createTextSpan(node.getStart(), node.getWidth()),
classificationType: type
});
pushClassification(node.getStart(), node.getWidth(), type);
}
}
}
@@ -5878,7 +5961,46 @@ module ts {
}
}
function getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
function getClassificationTypeName(type: ClassificationType) {
switch (type) {
case ClassificationType.comment: return ClassificationTypeNames.comment;
case ClassificationType.identifier: return ClassificationTypeNames.identifier;
case ClassificationType.keyword: return ClassificationTypeNames.keyword;
case ClassificationType.numericLiteral: return ClassificationTypeNames.numericLiteral;
case ClassificationType.operator: return ClassificationTypeNames.operator;
case ClassificationType.stringLiteral: return ClassificationTypeNames.stringLiteral;
case ClassificationType.whiteSpace: return ClassificationTypeNames.whiteSpace;
case ClassificationType.text: return ClassificationTypeNames.text;
case ClassificationType.punctuation: return ClassificationTypeNames.punctuation;
case ClassificationType.className: return ClassificationTypeNames.className;
case ClassificationType.enumName: return ClassificationTypeNames.enumName;
case ClassificationType.interfaceName: return ClassificationTypeNames.interfaceName;
case ClassificationType.moduleName: return ClassificationTypeNames.moduleName;
case ClassificationType.typeParameterName: return ClassificationTypeNames.typeParameterName;
case ClassificationType.typeAliasName: return ClassificationTypeNames.typeAliasName;
case ClassificationType.parameterName: return ClassificationTypeNames.parameterName;
}
}
function convertClassifications(classifications: Classifications): ClassifiedSpan[] {
Debug.assert(classifications.spans.length % 3 === 0);
let dense = classifications.spans;
let result: ClassifiedSpan[] = [];
for (let i = 0, n = dense.length; i < n; i += 3) {
result.push({
textSpan: createTextSpan(dense[i], dense[i + 1]),
classificationType: getClassificationTypeName(dense[i + 2])
});
}
return result;
}
function getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]{
return convertClassifications(getEncodedSyntacticClassifications(fileName, span));
}
function getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications {
// doesn't use compiler - no need to synchronize with host
let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
@@ -5886,10 +6008,16 @@ module ts {
let triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text);
let mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text);
let result: ClassifiedSpan[] = [];
let result: number[] = [];
processElement(sourceFile);
return result;
return { spans: result, endOfLineState: EndOfLineState.None };
function pushClassification(start: number, length: number, type: ClassificationType) {
result.push(start);
result.push(length);
result.push(type);
}
function classifyLeadingTrivia(token: Node): void {
let tokenStart = skipTrivia(sourceFile.text, token.pos, /*stopAfterLineBreak:*/ false);
@@ -5912,10 +6040,7 @@ module ts {
if (isComment(kind)) {
// Simple comment. Just add as is.
result.push({
textSpan: createTextSpan(start, width),
classificationType: ClassificationTypeNames.comment
})
pushClassification(start, width, ClassificationType.comment);
continue;
}
@@ -5926,10 +6051,7 @@ module ts {
// for the <<<<<<< and >>>>>>> markers, we just add them in as comments
// in the classification stream.
if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) {
result.push({
textSpan: createTextSpan(start, width),
classificationType: ClassificationTypeNames.comment
});
pushClassification(start, width, ClassificationType.comment);
continue;
}
@@ -5950,11 +6072,7 @@ module ts {
break;
}
}
result.push({
textSpan: createTextSpanFromBounds(start, i),
classificationType: ClassificationTypeNames.comment
});
pushClassification(start, i - start, ClassificationType.comment);
mergeConflictScanner.setTextPos(i);
while (mergeConflictScanner.getTextPos() < end) {
@@ -5969,10 +6087,7 @@ module ts {
let type = classifyTokenType(tokenKind);
if (type) {
result.push({
textSpan: createTextSpanFromBounds(start, end),
classificationType: type
});
pushClassification(start, end - start, type);
}
}
@@ -5982,10 +6097,7 @@ module ts {
if (token.getWidth() > 0) {
let type = classifyTokenType(token.kind, token);
if (type) {
result.push({
textSpan: createTextSpan(token.getStart(), token.getWidth()),
classificationType: type
});
pushClassification(token.getStart(), token.getWidth(), type);
}
}
}
@@ -5993,9 +6105,9 @@ module ts {
// for accurate classification, the actual token should be passed in. however, for
// cases like 'disabled merge code' classification, we just get the token kind and
// classify based on that instead.
function classifyTokenType(tokenKind: SyntaxKind, token?: Node): string {
function classifyTokenType(tokenKind: SyntaxKind, token?: Node): ClassificationType {
if (isKeyword(tokenKind)) {
return ClassificationTypeNames.keyword;
return ClassificationType.keyword;
}
// Special case < and > If they appear in a generic context they are punctuation,
@@ -6004,7 +6116,7 @@ module ts {
// If the node owning the token has a type argument list or type parameter list, then
// we can effectively assume that a '<' and '>' belong to those lists.
if (token && getTypeArgumentOrTypeParameterList(token.parent)) {
return ClassificationTypeNames.punctuation;
return ClassificationType.punctuation;
}
}
@@ -6015,7 +6127,7 @@ module ts {
if (token.parent.kind === SyntaxKind.VariableDeclaration ||
token.parent.kind === SyntaxKind.PropertyDeclaration ||
token.parent.kind === SyntaxKind.Parameter) {
return ClassificationTypeNames.operator;
return ClassificationType.operator;
}
}
@@ -6023,58 +6135,64 @@ module ts {
token.parent.kind === SyntaxKind.PrefixUnaryExpression ||
token.parent.kind === SyntaxKind.PostfixUnaryExpression ||
token.parent.kind === SyntaxKind.ConditionalExpression) {
return ClassificationTypeNames.operator;
return ClassificationType.operator;
}
}
return ClassificationTypeNames.punctuation;
return ClassificationType.punctuation;
}
else if (tokenKind === SyntaxKind.NumericLiteral) {
return ClassificationTypeNames.numericLiteral;
return ClassificationType.numericLiteral;
}
else if (tokenKind === SyntaxKind.StringLiteral) {
return ClassificationTypeNames.stringLiteral;
return ClassificationType.stringLiteral;
}
else if (tokenKind === SyntaxKind.RegularExpressionLiteral) {
// TODO: we should get another classification type for these literals.
return ClassificationTypeNames.stringLiteral;
return ClassificationType.stringLiteral;
}
else if (isTemplateLiteralKind(tokenKind)) {
// TODO (drosen): we should *also* get another classification type for these literals.
return ClassificationTypeNames.stringLiteral;
return ClassificationType.stringLiteral;
}
else if (tokenKind === SyntaxKind.Identifier) {
if (token) {
switch (token.parent.kind) {
case SyntaxKind.ClassDeclaration:
if ((<ClassDeclaration>token.parent).name === token) {
return ClassificationTypeNames.className;
return ClassificationType.className;
}
return;
case SyntaxKind.TypeParameter:
if ((<TypeParameterDeclaration>token.parent).name === token) {
return ClassificationTypeNames.typeParameterName;
return ClassificationType.typeParameterName;
}
return;
case SyntaxKind.InterfaceDeclaration:
if ((<InterfaceDeclaration>token.parent).name === token) {
return ClassificationTypeNames.interfaceName;
return ClassificationType.interfaceName;
}
return;
case SyntaxKind.EnumDeclaration:
if ((<EnumDeclaration>token.parent).name === token) {
return ClassificationTypeNames.enumName;
return ClassificationType.enumName;
}
return;
case SyntaxKind.ModuleDeclaration:
if ((<ModuleDeclaration>token.parent).name === token) {
return ClassificationTypeNames.moduleName;
return ClassificationType.moduleName;
}
return;
case SyntaxKind.Parameter:
if ((<ParameterDeclaration>token.parent).name === token) {
return ClassificationType.parameterName;
}
return;
}
}
return ClassificationTypeNames.text;
return ClassificationType.text;
}
}
@@ -6405,11 +6523,14 @@ module ts {
getCompilerOptionsDiagnostics,
getSyntacticClassifications,
getSemanticClassifications,
getEncodedSyntacticClassifications,
getEncodedSemanticClassifications,
getCompletionsAtPosition,
getCompletionEntryDetails,
getSignatureHelpItems,
getQuickInfoAtPosition,
getDefinitionAtPosition,
getTypeDefinitionAtPosition,
getReferencesAtPosition,
findReferences,
getOccurrencesAtPosition,
@@ -6545,10 +6666,67 @@ module ts {
// if there are more cases we want the classifier to be better at.
return true;
}
function convertClassifications(classifications: Classifications, text: string): ClassificationResult {
var entries: ClassificationInfo[] = [];
let dense = classifications.spans;
let lastEnd = 0;
for (let i = 0, n = dense.length; i < n; i += 3) {
let start = dense[i];
let length = dense[i + 1];
let type = <ClassificationType>dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
let whitespaceLength = start - lastEnd;
if (whitespaceLength > 0) {
entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace });
}
}
entries.push({ length, classification: convertClassification(type) });
lastEnd = start + length;
}
let whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace });
}
return { entries, finalLexState: classifications.endOfLineState };
}
function convertClassification(type: ClassificationType): TokenClass {
switch (type) {
case ClassificationType.comment: return TokenClass.Comment;
case ClassificationType.keyword: return TokenClass.Keyword;
case ClassificationType.numericLiteral: return TokenClass.NumberLiteral;
case ClassificationType.operator: return TokenClass.Operator;
case ClassificationType.stringLiteral: return TokenClass.StringLiteral;
case ClassificationType.whiteSpace: return TokenClass.Whitespace;
case ClassificationType.punctuation: return TokenClass.Punctuation;
case ClassificationType.identifier:
case ClassificationType.className:
case ClassificationType.enumName:
case ClassificationType.interfaceName:
case ClassificationType.moduleName:
case ClassificationType.typeParameterName:
case ClassificationType.typeAliasName:
case ClassificationType.text:
case ClassificationType.parameterName:
default:
return TokenClass.Identifier;
}
}
function getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult {
return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text);
}
// If there is a syntactic classifier ('syntacticClassifierAbsent' is false),
// we will be more conservative in order to avoid conflicting with the syntactic classifier.
function getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult {
function getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications {
let offset = 0;
let token = SyntaxKind.Unknown;
let lastNonTriviaToken = SyntaxKind.Unknown;
@@ -6591,9 +6769,9 @@ module ts {
scanner.setText(text);
let result: ClassificationResult = {
finalLexState: EndOfLineState.Start,
entries: []
let result: Classifications = {
endOfLineState: EndOfLineState.None,
spans: []
};
// We can run into an unfortunate interaction between the lexical and syntactic classifier
@@ -6706,7 +6884,7 @@ module ts {
let start = scanner.getTokenPos();
let end = scanner.getTextPos();
addResult(end - start, classFromKind(token));
addResult(start, end, classFromKind(token));
if (end >= text.length) {
if (token === SyntaxKind.StringLiteral) {
@@ -6723,7 +6901,7 @@ module ts {
// If we have an odd number of backslashes, then the multiline string is unclosed
if (numBackslashes & 1) {
let quoteChar = tokenText.charCodeAt(0);
result.finalLexState = quoteChar === CharacterCodes.doubleQuote
result.endOfLineState = quoteChar === CharacterCodes.doubleQuote
? EndOfLineState.InDoubleQuoteStringLiteral
: EndOfLineState.InSingleQuoteStringLiteral;
}
@@ -6732,16 +6910,16 @@ module ts {
else if (token === SyntaxKind.MultiLineCommentTrivia) {
// Check to see if the multiline comment was unclosed.
if (scanner.isUnterminated()) {
result.finalLexState = EndOfLineState.InMultiLineCommentTrivia;
result.endOfLineState = EndOfLineState.InMultiLineCommentTrivia;
}
}
else if (isTemplateLiteralKind(token)) {
if (scanner.isUnterminated()) {
if (token === SyntaxKind.TemplateTail) {
result.finalLexState = EndOfLineState.InTemplateMiddleOrTail;
result.endOfLineState = EndOfLineState.InTemplateMiddleOrTail;
}
else if (token === SyntaxKind.NoSubstitutionTemplateLiteral) {
result.finalLexState = EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate;
result.endOfLineState = EndOfLineState.InTemplateHeadOrNoSubstitutionTemplate;
}
else {
Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token);
@@ -6749,20 +6927,34 @@ module ts {
}
}
else if (templateStack.length > 0 && lastOrUndefined(templateStack) === SyntaxKind.TemplateHead) {
result.finalLexState = EndOfLineState.InTemplateSubstitutionPosition;
result.endOfLineState = EndOfLineState.InTemplateSubstitutionPosition;
}
}
}
function addResult(length: number, classification: TokenClass): void {
if (length > 0) {
// If this is the first classification we're adding to the list, then remove any
// offset we have if we were continuing a construct from the previous line.
if (result.entries.length === 0) {
length -= offset;
}
function addResult(start: number, end: number, classification: ClassificationType): void {
if (classification === ClassificationType.whiteSpace) {
// Don't bother with whitespace classifications. They're not needed.
return;
}
result.entries.push({ length: length, classification: classification });
if (start === 0 && offset > 0) {
// We're classifying the first token, and this was a case where we prepended
// text. We should consider the start of this token to be at the start of
// the original text.
start += offset;
}
// All our tokens are in relation to the augmented text. Move them back to be
// relative to the original text.
start -= offset;
end -= offset;
let length = end - start;
if (length > 0) {
result.spans.push(start);
result.spans.push(length);
result.spans.push(classification);
}
}
}
@@ -6829,41 +7021,44 @@ module ts {
return token >= SyntaxKind.FirstKeyword && token <= SyntaxKind.LastKeyword;
}
function classFromKind(token: SyntaxKind) {
function classFromKind(token: SyntaxKind): ClassificationType {
if (isKeyword(token)) {
return TokenClass.Keyword;
return ClassificationType.keyword;
}
else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) {
return TokenClass.Operator;
return ClassificationType.operator;
}
else if (token >= SyntaxKind.FirstPunctuation && token <= SyntaxKind.LastPunctuation) {
return TokenClass.Punctuation;
return ClassificationType.punctuation;
}
switch (token) {
case SyntaxKind.NumericLiteral:
return TokenClass.NumberLiteral;
return ClassificationType.numericLiteral;
case SyntaxKind.StringLiteral:
return TokenClass.StringLiteral;
return ClassificationType.stringLiteral;
case SyntaxKind.RegularExpressionLiteral:
return TokenClass.RegExpLiteral;
return ClassificationType.regularExpressionLiteral;
case SyntaxKind.ConflictMarkerTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineCommentTrivia:
return TokenClass.Comment;
return ClassificationType.comment;
case SyntaxKind.WhitespaceTrivia:
case SyntaxKind.NewLineTrivia:
return TokenClass.Whitespace;
return ClassificationType.whiteSpace;
case SyntaxKind.Identifier:
default:
if (isTemplateLiteralKind(token)) {
return TokenClass.StringLiteral;
return ClassificationType.stringLiteral;
}
return TokenClass.Identifier;
return ClassificationType.identifier;
}
}
return { getClassificationsForLine };
return {
getClassificationsForLine,
getEncodedLexicalClassifications
};
}
/// getDefaultLibraryFilePath
+83 -19
View File
@@ -99,6 +99,8 @@ module ts {
getSyntacticClassifications(fileName: string, start: number, length: number): string;
getSemanticClassifications(fileName: string, start: number, length: number): string;
getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string;
getEncodedSemanticClassifications(fileName: string, start: number, length: number): string;
getCompletionsAtPosition(fileName: string, position: number): string;
getCompletionEntryDetails(fileName: string, position: number, entryName: string): string;
@@ -130,6 +132,14 @@ module ts {
*/
getDefinitionAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string }
*
* Or undefined value if no definition can be found.
*/
getTypeDefinitionAtPosition(fileName: string, position: number): string;
/**
* Returns a JSON-encoded value of the type:
* { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[]
@@ -189,6 +199,7 @@ module ts {
}
export interface ClassifierShim extends Shim {
getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string;
}
@@ -199,7 +210,9 @@ module ts {
}
function logInternalError(logger: Logger, err: Error) {
logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
if (logger) {
logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message);
}
}
class ScriptSnapshotShimAdapter implements IScriptSnapshot {
@@ -321,25 +334,32 @@ module ts {
}
}
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any): any {
logger.log(actionDescription);
var start = Date.now();
var result = action();
var end = Date.now();
logger.log(actionDescription + " completed in " + (end - start) + " msec");
if (typeof (result) === "string") {
var str = <string>result;
if (str.length > 128) {
str = str.substring(0, 128) + "...";
}
logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, noPerfLogging: boolean): any {
if (!noPerfLogging) {
logger.log(actionDescription);
var start = Date.now();
}
var result = action();
if (!noPerfLogging) {
var end = Date.now();
logger.log(actionDescription + " completed in " + (end - start) + " msec");
if (typeof (result) === "string") {
var str = <string>result;
if (str.length > 128) {
str = str.substring(0, 128) + "...";
}
logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'");
}
}
return result;
}
function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any): string {
function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, noPerfLogging: boolean): string {
try {
var result = simpleForwardCall(logger, actionDescription, action);
var result = simpleForwardCall(logger, actionDescription, action, noPerfLogging);
return JSON.stringify({ result: result });
}
catch (err) {
@@ -387,7 +407,7 @@ module ts {
}
public forwardJSONCall(actionDescription: string, action: () => any): string {
return forwardJSONCall(this.logger, actionDescription, action);
return forwardJSONCall(this.logger, actionDescription, action, /*noPerfLogging:*/ false);
}
/// DISPOSE
@@ -457,6 +477,26 @@ module ts {
});
}
public getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
"getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
return convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length)));
});
}
public getEncodedSemanticClassifications(fileName: string, start: number, length: number): string {
return this.forwardJSONCall(
"getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
// directly serialize the spans out to a string. This is much faster to decode
// on the managed side versus a full JSON array.
return convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length)));
});
}
private getNewLine(): string {
return this.host.getNewLine ? this.host.getNewLine() : "\r\n";
}
@@ -557,6 +597,20 @@ module ts {
});
}
/// GOTO Type
/**
* Computes the definition location of the type of the symbol
* at the requested position.
*/
public getTypeDefinitionAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getTypeDefinitionAtPosition('" + fileName + "', " + position + ")",
() => {
return this.languageService.getTypeDefinitionAtPosition(fileName, position);
});
}
public getRenameInfo(fileName: string, position: number): string {
return this.forwardJSONCall(
"getRenameInfo('" + fileName + "', " + position + ")",
@@ -736,14 +790,24 @@ module ts {
}
}
function convertClassifications(classifications: Classifications): { spans: string, endOfLineState: EndOfLineState } {
return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState };
}
class ClassifierShimObject extends ShimBase implements ClassifierShim {
public classifier: Classifier;
constructor(factory: ShimFactory) {
constructor(factory: ShimFactory, private logger: Logger) {
super(factory);
this.classifier = createClassifier();
}
public getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string {
return forwardJSONCall(this.logger, "getEncodedLexicalClassifications",
() => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)),
/*noPerfLogging:*/ true);
}
/// COLORIZATION
public getClassificationsForLine(text: string, lexState: EndOfLineState, classifyKeywordsInGenerics?: boolean): string {
var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics);
@@ -765,7 +829,7 @@ module ts {
}
private forwardJSONCall(actionDescription: string, action: () => any): any {
return forwardJSONCall(this.logger, actionDescription, action);
return forwardJSONCall(this.logger, actionDescription, action, /*noPerfLogging:*/ false);
}
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
@@ -858,7 +922,7 @@ module ts {
public createClassifierShim(logger: Logger): ClassifierShim {
try {
return new ClassifierShimObject(this);
return new ClassifierShimObject(this, logger);
}
catch (err) {
logInternalError(logger, err);
+1 -1
View File
@@ -200,7 +200,7 @@ module ts {
function nodeEndsWith(n: Node, expectedLastToken: SyntaxKind, sourceFile: SourceFile): boolean {
let children = n.getChildren(sourceFile);
if (children.length) {
let last = children[children.length - 1];
let last = lastOrUndefined(children);
if (last.kind === expectedLastToken) {
return true;
}
@@ -21,7 +21,7 @@ module A {
//// [ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -25,7 +25,7 @@ module A {
//// [ExportClassWithInaccessibleTypeInTypeParameterConstraint.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -16,7 +16,7 @@ class ColoredPoint extends Point {
//// [accessOverriddenBaseClassMember1.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -25,7 +25,7 @@ class LanguageSpec_section_4_5_inference {
}
//// [accessors_spec_section-4.5_inference.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -35,7 +35,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsage1_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -29,7 +29,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInArray_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -28,7 +28,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInFunctionExpression_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -32,7 +32,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInGenericFunction_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -34,7 +34,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInIndexerOfClass_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -29,7 +29,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInObjectLiteral_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -32,7 +32,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInOrExpression_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -32,7 +32,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInTypeArgumentOfExtendsClause_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -48,7 +48,7 @@ var VisualizationModel = (function (_super) {
})(Backbone.Model);
exports.VisualizationModel = VisualizationModel;
//// [aliasUsageInTypeArgumentOfExtendsClause_main.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -28,7 +28,7 @@ var Model = (function () {
})();
exports.Model = Model;
//// [aliasUsageInVarAssignment_moduleA.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -0,0 +1,24 @@
tests/cases/conformance/ambient/ambientEnumDeclaration1.ts(5,5): error TS1066: Ambient enum elements can only have integer literal initializers.
tests/cases/conformance/ambient/ambientEnumDeclaration1.ts(6,5): error TS1066: Ambient enum elements can only have integer literal initializers.
tests/cases/conformance/ambient/ambientEnumDeclaration1.ts(7,5): error TS1066: Ambient enum elements can only have integer literal initializers.
tests/cases/conformance/ambient/ambientEnumDeclaration1.ts(8,5): error TS1066: Ambient enum elements can only have integer literal initializers.
==== tests/cases/conformance/ambient/ambientEnumDeclaration1.ts (4 errors) ====
// In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions.
declare enum E {
a = 10,
b = 10 + 1,
~
!!! error TS1066: Ambient enum elements can only have integer literal initializers.
c = b,
~
!!! error TS1066: Ambient enum elements can only have integer literal initializers.
d = (c) + 1,
~
!!! error TS1066: Ambient enum elements can only have integer literal initializers.
e = 10 << 2 * 8,
~
!!! error TS1066: Ambient enum elements can only have integer literal initializers.
}
@@ -0,0 +1,13 @@
//// [ambientEnumDeclaration1.ts]
// In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions.
declare enum E {
a = 10,
b = 10 + 1,
c = b,
d = (c) + 1,
e = 10 << 2 * 8,
}
//// [ambientEnumDeclaration1.js]
// In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions.
@@ -0,0 +1,17 @@
//// [ambientEnumDeclaration2.ts]
// In ambient enum declarations that specify no const modifier, enum member declarations
// that omit a value are considered computed members (as opposed to having auto- incremented values assigned).
declare enum E {
a, // E.a
b, // E.b
}
declare const enum E1 {
a, // E.a = 0
b, // E.b = 1
}
//// [ambientEnumDeclaration2.js]
// In ambient enum declarations that specify no const modifier, enum member declarations
// that omit a value are considered computed members (as opposed to having auto- incremented values assigned).
@@ -0,0 +1,23 @@
=== tests/cases/conformance/ambient/ambientEnumDeclaration2.ts ===
// In ambient enum declarations that specify no const modifier, enum member declarations
// that omit a value are considered computed members (as opposed to having auto- incremented values assigned).
declare enum E {
>E : Symbol(E, Decl(ambientEnumDeclaration2.ts, 0, 0))
a, // E.a
>a : Symbol(E.a, Decl(ambientEnumDeclaration2.ts, 3, 16))
b, // E.b
>b : Symbol(E.b, Decl(ambientEnumDeclaration2.ts, 4, 6))
}
declare const enum E1 {
>E1 : Symbol(E1, Decl(ambientEnumDeclaration2.ts, 6, 1))
a, // E.a = 0
>a : Symbol(E1.a, Decl(ambientEnumDeclaration2.ts, 8, 23))
b, // E.b = 1
>b : Symbol(E1.b, Decl(ambientEnumDeclaration2.ts, 9, 6))
}
@@ -0,0 +1,23 @@
=== tests/cases/conformance/ambient/ambientEnumDeclaration2.ts ===
// In ambient enum declarations that specify no const modifier, enum member declarations
// that omit a value are considered computed members (as opposed to having auto- incremented values assigned).
declare enum E {
>E : E
a, // E.a
>a : E
b, // E.b
>b : E
}
declare const enum E1 {
>E1 : E1
a, // E.a = 0
>a : E1
b, // E.b = 1
>b : E1
}
@@ -9,7 +9,7 @@ var x: B;
var t: number = f(x, x); // Not an error
//// [ambiguousOverloadResolution.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -24,7 +24,7 @@ class Derived2<U extends String> extends Base2 { // error because of the prototy
//// [apparentTypeSubtyping.js]
// subtype checks use the apparent type of the target type
// S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S:
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -14,7 +14,7 @@ class Derived<U extends String> extends Base { // error
//// [apparentTypeSupertype.js]
// subtype checks use the apparent type of the target type
// S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S:
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -0,0 +1,38 @@
tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(16,5): error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'.
Property '0' is missing in type '(string | number | boolean)[]'.
tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(17,5): error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'.
tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(18,5): error TS2345: Argument of type '{ x: (string | number)[]; y: { c: boolean; d: string; e: number; }; }' is not assignable to parameter of type '{ x: [any, any]; y: { c: any; d: any; e: any; }; }'.
Types of property 'x' are incompatible.
Type '(string | number)[]' is not assignable to type '[any, any]'.
Property '0' is missing in type '(string | number)[]'.
==== tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts (3 errors) ====
// In a typed function call, argument expressions are contextually typed by their corresponding parameter types.
function foo({x: [a, b], y: {c, d, e}}) { }
function bar({x: [a, b = 10], y: {c, d, e = { f:1 }}}) { }
function baz(x: [string, number, boolean]) { }
var o = { x: ["string", 1], y: { c: true, d: "world", e: 3 } };
var o1: { x: [string, number], y: { c: boolean, d: string, e: number } } = { x: ["string", 1], y: { c: true, d: "world", e: 3 } };
foo(o1); // Not error since x has contextual type of tuple namely [string, number]
foo({ x: ["string", 1], y: { c: true, d: "world", e: 3 } }); // Not error
var array = ["string", 1, true];
var tuple: [string, number, boolean] = ["string", 1, true];
baz(tuple);
baz(["string", 1, true]);
baz(array); // Error
~~~~~
!!! error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'.
!!! error TS2345: Property '0' is missing in type '(string | number | boolean)[]'.
baz(["string", 1, true, ...array]); // Error
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'.
foo(o); // Error because x has an array type namely (string|number)[]
~
!!! error TS2345: Argument of type '{ x: (string | number)[]; y: { c: boolean; d: string; e: number; }; }' is not assignable to parameter of type '{ x: [any, any]; y: { c: any; d: any; e: any; }; }'.
!!! error TS2345: Types of property 'x' are incompatible.
!!! error TS2345: Type '(string | number)[]' is not assignable to type '[any, any]'.
!!! error TS2345: Property '0' is missing in type '(string | number)[]'.
@@ -0,0 +1,40 @@
//// [argumentExpressionContextualTyping.ts]
// In a typed function call, argument expressions are contextually typed by their corresponding parameter types.
function foo({x: [a, b], y: {c, d, e}}) { }
function bar({x: [a, b = 10], y: {c, d, e = { f:1 }}}) { }
function baz(x: [string, number, boolean]) { }
var o = { x: ["string", 1], y: { c: true, d: "world", e: 3 } };
var o1: { x: [string, number], y: { c: boolean, d: string, e: number } } = { x: ["string", 1], y: { c: true, d: "world", e: 3 } };
foo(o1); // Not error since x has contextual type of tuple namely [string, number]
foo({ x: ["string", 1], y: { c: true, d: "world", e: 3 } }); // Not error
var array = ["string", 1, true];
var tuple: [string, number, boolean] = ["string", 1, true];
baz(tuple);
baz(["string", 1, true]);
baz(array); // Error
baz(["string", 1, true, ...array]); // Error
foo(o); // Error because x has an array type namely (string|number)[]
//// [argumentExpressionContextualTyping.js]
// In a typed function call, argument expressions are contextually typed by their corresponding parameter types.
function foo(_a) {
var _b = _a.x, a = _b[0], b = _b[1], _c = _a.y, c = _c.c, d = _c.d, e = _c.e;
}
function bar(_a) {
var _b = _a.x, a = _b[0], _c = _b[1], b = _c === void 0 ? 10 : _c, _d = _a.y, c = _d.c, d = _d.d, _e = _d.e, e = _e === void 0 ? { f: 1 } : _e;
}
function baz(x) { }
var o = { x: ["string", 1], y: { c: true, d: "world", e: 3 } };
var o1 = { x: ["string", 1], y: { c: true, d: "world", e: 3 } };
foo(o1); // Not error since x has contextual type of tuple namely [string, number]
foo({ x: ["string", 1], y: { c: true, d: "world", e: 3 } }); // Not error
var array = ["string", 1, true];
var tuple = ["string", 1, true];
baz(tuple);
baz(["string", 1, true]);
baz(array); // Error
baz(["string", 1, true].concat(array)); // Error
foo(o); // Error because x has an array type namely (string|number)[]
@@ -86,7 +86,7 @@ arr_any = c3; // should be an error - is
arr_any = i1; // should be an error - is
//// [arrayAssignmentTest1.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -60,7 +60,7 @@ arr_any = i1; // should be an error - is
//// [arrayAssignmentTest2.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -108,7 +108,7 @@ module NonEmptyTypes {
//// [arrayBestCommonTypes.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -0,0 +1,34 @@
tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts(8,5): error TS2322: Type '[number, number, number, string]' is not assignable to type '[number, number, number]'.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts(14,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
Property '0' is missing in type 'number[]'.
==== tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts (2 errors) ====
// In a contextually typed array literal expression containing no spread elements, an element expression at index N is contextually typed by
// the type of the property with the numeric name N in the contextual type, if any, or otherwise
// the numeric index type of the contextual type, if any.
var array = [1, 2, 3];
var array1 = [true, 2, 3]; // Contextual type by the numeric index type of the contextual type
var tup: [number, number, number] = [1, 2, 3, 4];
var tup1: [number|string, number|string, number|string] = [1, 2, 3, "string"];
var tup2: [number, number, number] = [1, 2, 3, "string"]; // Error
~~~~
!!! error TS2322: Type '[number, number, number, string]' is not assignable to type '[number, number, number]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
// In a contextually typed array literal expression containing one or more spread elements,
// an element expression at index N is contextually typed by the numeric index type of the contextual type, if any.
var spr = [1, 2, 3, ...array];
var spr1 = [1, 2, 3, ...tup];
var spr2:[number, number, number] = [1, 2, 3, ...tup]; // Error
~~~~
!!! error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
!!! error TS2322: Property '0' is missing in type 'number[]'.
@@ -0,0 +1,31 @@
//// [arrayLiteralExpressionContextualTyping.ts]
// In a contextually typed array literal expression containing no spread elements, an element expression at index N is contextually typed by
// the type of the property with the numeric name N in the contextual type, if any, or otherwise
// the numeric index type of the contextual type, if any.
var array = [1, 2, 3];
var array1 = [true, 2, 3]; // Contextual type by the numeric index type of the contextual type
var tup: [number, number, number] = [1, 2, 3, 4];
var tup1: [number|string, number|string, number|string] = [1, 2, 3, "string"];
var tup2: [number, number, number] = [1, 2, 3, "string"]; // Error
// In a contextually typed array literal expression containing one or more spread elements,
// an element expression at index N is contextually typed by the numeric index type of the contextual type, if any.
var spr = [1, 2, 3, ...array];
var spr1 = [1, 2, 3, ...tup];
var spr2:[number, number, number] = [1, 2, 3, ...tup]; // Error
//// [arrayLiteralExpressionContextualTyping.js]
// In a contextually typed array literal expression containing no spread elements, an element expression at index N is contextually typed by
// the type of the property with the numeric name N in the contextual type, if any, or otherwise
// the numeric index type of the contextual type, if any.
var array = [1, 2, 3];
var array1 = [true, 2, 3]; // Contextual type by the numeric index type of the contextual type
var tup = [1, 2, 3, 4];
var tup1 = [1, 2, 3, "string"];
var tup2 = [1, 2, 3, "string"]; // Error
// In a contextually typed array literal expression containing one or more spread elements,
// an element expression at index N is contextually typed by the numeric index type of the contextual type, if any.
var spr = [1, 2, 3].concat(array);
var spr1 = [1, 2, 3].concat(tup);
var spr2 = [1, 2, 3].concat(tup); // Error
@@ -52,7 +52,7 @@ var z3: { id: number }[] =
//// [arrayLiteralTypeInference.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
+1 -1
View File
@@ -38,7 +38,7 @@ var context4: Base[] = [new Derived1(), new Derived1()];
//// [arrayLiterals.js]
// Empty array literal with no contextual type has type Undefined[]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -0,0 +1,104 @@
//// [arrayLiterals2ES5.ts]
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [,, 2, 3, 4]
var a1 = ["hello", "world"]
var a2 = [, , , ...a0, "hello"];
var a3 = [,, ...a0]
var a4 = [() => 1, ];
var a5 = [...a0, , ]
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0: [any, any, any] = [undefined, null, undefined];
var b1: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
var temp3 = [undefined, null, undefined];
var temp4 = [];
interface myArray extends Array<Number> { }
interface myArray2 extends Array<Number|String> { }
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
var d1 = [...temp]; // has type string[]
var d2: number[] = [...temp1];
var d3: myArray = [...temp1];
var d4: myArray2 = [...temp, ...temp1];
var d5 = [...temp3];
var d6 = [...temp4];
var d7 = [...[...temp1]];
var d8: number[][] = [[...temp1]]
var d9 = [[...temp1], ...["hello"]];
//// [arrayLiterals2ES5.js]
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [, , 2, 3, 4];
var a1 = ["hello", "world"];
var a2 = [, , ].concat(a0, ["hello"]);
var a3 = [, ].concat(a0);
var a4 = [function () { return 1; },];
var a5 = a0.concat([,]);
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0 = [undefined, null, undefined];
var b1 = [[1, 2, 3], ["hello", "string"]];
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var _a = [1, 2], c0 = _a[0], c1 = _a[1]; // tuple type [number, number]
var _b = [1, 2, true], c2 = _b[0], c3 = _b[1]; // tuple type [number, number, boolean]
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2 = [[1, 2, 3], ["hello", "string"]];
var temp3 = [undefined, null, undefined];
var temp4 = [];
var d0 = [1, true].concat(temp); // has type (string|number|boolean)[]
var d1 = temp; // has type string[]
var d2 = temp1;
var d3 = temp1;
var d4 = temp.concat(temp1);
var d5 = temp3;
var d6 = temp4;
var d7 = temp1;
var d8 = [temp1];
var d9 = [temp1].concat(["hello"]);
@@ -0,0 +1,134 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES5.ts ===
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [,, 2, 3, 4]
>a0 : Symbol(a0, Decl(arrayLiterals2ES5.ts, 9, 3))
var a1 = ["hello", "world"]
>a1 : Symbol(a1, Decl(arrayLiterals2ES5.ts, 10, 3))
var a2 = [, , , ...a0, "hello"];
>a2 : Symbol(a2, Decl(arrayLiterals2ES5.ts, 11, 3))
>a0 : Symbol(a0, Decl(arrayLiterals2ES5.ts, 9, 3))
var a3 = [,, ...a0]
>a3 : Symbol(a3, Decl(arrayLiterals2ES5.ts, 12, 3))
>a0 : Symbol(a0, Decl(arrayLiterals2ES5.ts, 9, 3))
var a4 = [() => 1, ];
>a4 : Symbol(a4, Decl(arrayLiterals2ES5.ts, 13, 3))
var a5 = [...a0, , ]
>a5 : Symbol(a5, Decl(arrayLiterals2ES5.ts, 14, 3))
>a0 : Symbol(a0, Decl(arrayLiterals2ES5.ts, 9, 3))
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0: [any, any, any] = [undefined, null, undefined];
>b0 : Symbol(b0, Decl(arrayLiterals2ES5.ts, 25, 3))
>undefined : Symbol(undefined)
>undefined : Symbol(undefined)
var b1: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>b1 : Symbol(b1, Decl(arrayLiterals2ES5.ts, 26, 3))
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
>c0 : Symbol(c0, Decl(arrayLiterals2ES5.ts, 32, 5))
>c1 : Symbol(c1, Decl(arrayLiterals2ES5.ts, 32, 8))
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
>c2 : Symbol(c2, Decl(arrayLiterals2ES5.ts, 33, 5))
>c3 : Symbol(c3, Decl(arrayLiterals2ES5.ts, 33, 8))
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
>temp : Symbol(temp, Decl(arrayLiterals2ES5.ts, 38, 3))
var temp1 = [1, 2, 3];
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>temp2 : Symbol(temp2, Decl(arrayLiterals2ES5.ts, 40, 3))
var temp3 = [undefined, null, undefined];
>temp3 : Symbol(temp3, Decl(arrayLiterals2ES5.ts, 41, 3))
>undefined : Symbol(undefined)
>undefined : Symbol(undefined)
var temp4 = [];
>temp4 : Symbol(temp4, Decl(arrayLiterals2ES5.ts, 42, 3))
interface myArray extends Array<Number> { }
>myArray : Symbol(myArray, Decl(arrayLiterals2ES5.ts, 42, 15))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES5.ts, 44, 43))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11))
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES5.ts, 46, 3))
>temp : Symbol(temp, Decl(arrayLiterals2ES5.ts, 38, 3))
var d1 = [...temp]; // has type string[]
>d1 : Symbol(d1, Decl(arrayLiterals2ES5.ts, 47, 3))
>temp : Symbol(temp, Decl(arrayLiterals2ES5.ts, 38, 3))
var d2: number[] = [...temp1];
>d2 : Symbol(d2, Decl(arrayLiterals2ES5.ts, 48, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
var d3: myArray = [...temp1];
>d3 : Symbol(d3, Decl(arrayLiterals2ES5.ts, 49, 3))
>myArray : Symbol(myArray, Decl(arrayLiterals2ES5.ts, 42, 15))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
var d4: myArray2 = [...temp, ...temp1];
>d4 : Symbol(d4, Decl(arrayLiterals2ES5.ts, 50, 3))
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES5.ts, 44, 43))
>temp : Symbol(temp, Decl(arrayLiterals2ES5.ts, 38, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
var d5 = [...temp3];
>d5 : Symbol(d5, Decl(arrayLiterals2ES5.ts, 51, 3))
>temp3 : Symbol(temp3, Decl(arrayLiterals2ES5.ts, 41, 3))
var d6 = [...temp4];
>d6 : Symbol(d6, Decl(arrayLiterals2ES5.ts, 52, 3))
>temp4 : Symbol(temp4, Decl(arrayLiterals2ES5.ts, 42, 3))
var d7 = [...[...temp1]];
>d7 : Symbol(d7, Decl(arrayLiterals2ES5.ts, 53, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
var d8: number[][] = [[...temp1]]
>d8 : Symbol(d8, Decl(arrayLiterals2ES5.ts, 54, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
var d9 = [[...temp1], ...["hello"]];
>d9 : Symbol(d9, Decl(arrayLiterals2ES5.ts, 55, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES5.ts, 39, 3))
@@ -0,0 +1,225 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES5.ts ===
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [,, 2, 3, 4]
>a0 : number[]
>[,, 2, 3, 4] : number[]
> : undefined
> : undefined
>2 : number
>3 : number
>4 : number
var a1 = ["hello", "world"]
>a1 : string[]
>["hello", "world"] : string[]
>"hello" : string
>"world" : string
var a2 = [, , , ...a0, "hello"];
>a2 : (string | number)[]
>[, , , ...a0, "hello"] : (string | number)[]
> : undefined
> : undefined
> : undefined
>...a0 : number
>a0 : number[]
>"hello" : string
var a3 = [,, ...a0]
>a3 : number[]
>[,, ...a0] : number[]
> : undefined
> : undefined
>...a0 : number
>a0 : number[]
var a4 = [() => 1, ];
>a4 : (() => number)[]
>[() => 1, ] : (() => number)[]
>() => 1 : () => number
>1 : number
var a5 = [...a0, , ]
>a5 : number[]
>[...a0, , ] : number[]
>...a0 : number
>a0 : number[]
> : undefined
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0: [any, any, any] = [undefined, null, undefined];
>b0 : [any, any, any]
>[undefined, null, undefined] : [undefined, null, undefined]
>undefined : undefined
>null : null
>undefined : undefined
var b1: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>b1 : [number[], string[]]
>[[1, 2, 3], ["hello", "string"]] : [number[], string[]]
>[1, 2, 3] : number[]
>1 : number
>2 : number
>3 : number
>["hello", "string"] : string[]
>"hello" : string
>"string" : string
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
>c0 : number
>c1 : number
>[1, 2] : [number, number]
>1 : number
>2 : number
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
>c2 : number
>c3 : number
>[1, 2, true] : [number, number, boolean]
>1 : number
>2 : number
>true : boolean
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
>temp : string[]
>["s", "t", "r"] : string[]
>"s" : string
>"t" : string
>"r" : string
var temp1 = [1, 2, 3];
>temp1 : number[]
>[1, 2, 3] : number[]
>1 : number
>2 : number
>3 : number
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>temp2 : [number[], string[]]
>[[1, 2, 3], ["hello", "string"]] : [number[], string[]]
>[1, 2, 3] : number[]
>1 : number
>2 : number
>3 : number
>["hello", "string"] : string[]
>"hello" : string
>"string" : string
var temp3 = [undefined, null, undefined];
>temp3 : any[]
>[undefined, null, undefined] : null[]
>undefined : undefined
>null : null
>undefined : undefined
var temp4 = [];
>temp4 : any[]
>[] : undefined[]
interface myArray extends Array<Number> { }
>myArray : myArray
>Array : T[]
>Number : Number
interface myArray2 extends Array<Number|String> { }
>myArray2 : myArray2
>Array : T[]
>Number : Number
>String : String
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
>d0 : (string | number | boolean)[]
>[1, true, ...temp,] : (string | number | boolean)[]
>1 : number
>true : boolean
>...temp : string
>temp : string[]
var d1 = [...temp]; // has type string[]
>d1 : string[]
>[...temp] : string[]
>...temp : string
>temp : string[]
var d2: number[] = [...temp1];
>d2 : number[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d3: myArray = [...temp1];
>d3 : myArray
>myArray : myArray
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d4: myArray2 = [...temp, ...temp1];
>d4 : myArray2
>myArray2 : myArray2
>[...temp, ...temp1] : (string | number)[]
>...temp : string
>temp : string[]
>...temp1 : number
>temp1 : number[]
var d5 = [...temp3];
>d5 : any[]
>[...temp3] : any[]
>...temp3 : any
>temp3 : any[]
var d6 = [...temp4];
>d6 : any[]
>[...temp4] : any[]
>...temp4 : any
>temp4 : any[]
var d7 = [...[...temp1]];
>d7 : number[]
>[...[...temp1]] : number[]
>...[...temp1] : number
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d8: number[][] = [[...temp1]]
>d8 : number[][]
>[[...temp1]] : number[][]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d9 = [[...temp1], ...["hello"]];
>d9 : (string | number[])[]
>[[...temp1], ...["hello"]] : (string | number[])[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
>...["hello"] : string
>["hello"] : string[]
>"hello" : string
@@ -0,0 +1,100 @@
//// [arrayLiterals2ES6.ts]
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [, , 2, 3, 4]
var a1 = ["hello", "world"]
var a2 = [, , , ...a0, "hello"];
var a3 = [, , ...a0]
var a4 = [() => 1, ];
var a5 = [...a0, , ]
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0: [any, any, any] = [undefined, null, undefined];
var b1: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
interface myArray extends Array<Number> { }
interface myArray2 extends Array<Number|String> { }
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
var d1 = [...temp]; // has type string[]
var d2: number[] = [...temp1];
var d3: myArray = [...temp1];
var d4: myArray2 = [...temp, ...temp1];
var d5 = [...a2];
var d6 = [...a3];
var d7 = [...a4];
var d8: number[][] = [[...temp1]]
var d9 = [[...temp1], ...["hello"]];
//// [arrayLiterals2ES6.js]
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [, , 2, 3, 4];
var a1 = ["hello", "world"];
var a2 = [, , , ...a0, "hello"];
var a3 = [, , ...a0];
var a4 = [() => 1,];
var a5 = [...a0, ,];
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0 = [undefined, null, undefined];
var b1 = [[1, 2, 3], ["hello", "string"]];
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2 = [[1, 2, 3], ["hello", "string"]];
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
var d1 = [...temp]; // has type string[]
var d2 = [...temp1];
var d3 = [...temp1];
var d4 = [...temp, ...temp1];
var d5 = [...a2];
var d6 = [...a3];
var d7 = [...a4];
var d8 = [[...temp1]];
var d9 = [[...temp1], ...["hello"]];
@@ -0,0 +1,126 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES6.ts ===
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [, , 2, 3, 4]
>a0 : Symbol(a0, Decl(arrayLiterals2ES6.ts, 9, 3))
var a1 = ["hello", "world"]
>a1 : Symbol(a1, Decl(arrayLiterals2ES6.ts, 10, 3))
var a2 = [, , , ...a0, "hello"];
>a2 : Symbol(a2, Decl(arrayLiterals2ES6.ts, 11, 3))
>a0 : Symbol(a0, Decl(arrayLiterals2ES6.ts, 9, 3))
var a3 = [, , ...a0]
>a3 : Symbol(a3, Decl(arrayLiterals2ES6.ts, 12, 3))
>a0 : Symbol(a0, Decl(arrayLiterals2ES6.ts, 9, 3))
var a4 = [() => 1, ];
>a4 : Symbol(a4, Decl(arrayLiterals2ES6.ts, 13, 3))
var a5 = [...a0, , ]
>a5 : Symbol(a5, Decl(arrayLiterals2ES6.ts, 14, 3))
>a0 : Symbol(a0, Decl(arrayLiterals2ES6.ts, 9, 3))
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0: [any, any, any] = [undefined, null, undefined];
>b0 : Symbol(b0, Decl(arrayLiterals2ES6.ts, 25, 3))
>undefined : Symbol(undefined)
>undefined : Symbol(undefined)
var b1: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>b1 : Symbol(b1, Decl(arrayLiterals2ES6.ts, 26, 3))
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
>c0 : Symbol(c0, Decl(arrayLiterals2ES6.ts, 32, 5))
>c1 : Symbol(c1, Decl(arrayLiterals2ES6.ts, 32, 8))
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
>c2 : Symbol(c2, Decl(arrayLiterals2ES6.ts, 33, 5))
>c3 : Symbol(c3, Decl(arrayLiterals2ES6.ts, 33, 8))
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
>temp : Symbol(temp, Decl(arrayLiterals2ES6.ts, 38, 3))
var temp1 = [1, 2, 3];
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES6.ts, 39, 3))
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>temp2 : Symbol(temp2, Decl(arrayLiterals2ES6.ts, 40, 3))
interface myArray extends Array<Number> { }
>myArray : Symbol(myArray, Decl(arrayLiterals2ES6.ts, 40, 67))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11), Decl(lib.d.ts, 1439, 1))
>Number : Symbol(Number, Decl(lib.d.ts, 456, 40), Decl(lib.d.ts, 518, 11))
>String : Symbol(String, Decl(lib.d.ts, 275, 1), Decl(lib.d.ts, 443, 11), Decl(lib.d.ts, 1538, 1))
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES6.ts, 44, 3))
>temp : Symbol(temp, Decl(arrayLiterals2ES6.ts, 38, 3))
var d1 = [...temp]; // has type string[]
>d1 : Symbol(d1, Decl(arrayLiterals2ES6.ts, 45, 3))
>temp : Symbol(temp, Decl(arrayLiterals2ES6.ts, 38, 3))
var d2: number[] = [...temp1];
>d2 : Symbol(d2, Decl(arrayLiterals2ES6.ts, 46, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES6.ts, 39, 3))
var d3: myArray = [...temp1];
>d3 : Symbol(d3, Decl(arrayLiterals2ES6.ts, 47, 3))
>myArray : Symbol(myArray, Decl(arrayLiterals2ES6.ts, 40, 67))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES6.ts, 39, 3))
var d4: myArray2 = [...temp, ...temp1];
>d4 : Symbol(d4, Decl(arrayLiterals2ES6.ts, 48, 3))
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43))
>temp : Symbol(temp, Decl(arrayLiterals2ES6.ts, 38, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES6.ts, 39, 3))
var d5 = [...a2];
>d5 : Symbol(d5, Decl(arrayLiterals2ES6.ts, 49, 3))
>a2 : Symbol(a2, Decl(arrayLiterals2ES6.ts, 11, 3))
var d6 = [...a3];
>d6 : Symbol(d6, Decl(arrayLiterals2ES6.ts, 50, 3))
>a3 : Symbol(a3, Decl(arrayLiterals2ES6.ts, 12, 3))
var d7 = [...a4];
>d7 : Symbol(d7, Decl(arrayLiterals2ES6.ts, 51, 3))
>a4 : Symbol(a4, Decl(arrayLiterals2ES6.ts, 13, 3))
var d8: number[][] = [[...temp1]]
>d8 : Symbol(d8, Decl(arrayLiterals2ES6.ts, 52, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES6.ts, 39, 3))
var d9 = [[...temp1], ...["hello"]];
>d9 : Symbol(d9, Decl(arrayLiterals2ES6.ts, 53, 3))
>temp1 : Symbol(temp1, Decl(arrayLiterals2ES6.ts, 39, 3))
@@ -0,0 +1,212 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES6.ts ===
// ElementList: ( Modified )
// Elisionopt AssignmentExpression
// Elisionopt SpreadElement
// ElementList, Elisionopt AssignmentExpression
// ElementList, Elisionopt SpreadElement
// SpreadElement:
// ... AssignmentExpression
var a0 = [, , 2, 3, 4]
>a0 : number[]
>[, , 2, 3, 4] : number[]
> : undefined
> : undefined
>2 : number
>3 : number
>4 : number
var a1 = ["hello", "world"]
>a1 : string[]
>["hello", "world"] : string[]
>"hello" : string
>"world" : string
var a2 = [, , , ...a0, "hello"];
>a2 : (string | number)[]
>[, , , ...a0, "hello"] : (string | number)[]
> : undefined
> : undefined
> : undefined
>...a0 : number
>a0 : number[]
>"hello" : string
var a3 = [, , ...a0]
>a3 : number[]
>[, , ...a0] : number[]
> : undefined
> : undefined
>...a0 : number
>a0 : number[]
var a4 = [() => 1, ];
>a4 : (() => number)[]
>[() => 1, ] : (() => number)[]
>() => 1 : () => number
>1 : number
var a5 = [...a0, , ]
>a5 : number[]
>[...a0, , ] : number[]
>...a0 : number
>a0 : number[]
> : undefined
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var b0: [any, any, any] = [undefined, null, undefined];
>b0 : [any, any, any]
>[undefined, null, undefined] : [undefined, null, undefined]
>undefined : undefined
>null : null
>undefined : undefined
var b1: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>b1 : [number[], string[]]
>[[1, 2, 3], ["hello", "string"]] : [number[], string[]]
>[1, 2, 3] : number[]
>1 : number
>2 : number
>3 : number
>["hello", "string"] : string[]
>"hello" : string
>"string" : string
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [c0, c1] = [1, 2]; // tuple type [number, number]
>c0 : number
>c1 : number
>[1, 2] : [number, number]
>1 : number
>2 : number
var [c2, c3] = [1, 2, true]; // tuple type [number, number, boolean]
>c2 : number
>c3 : number
>[1, 2, true] : [number, number, boolean]
>1 : number
>2 : number
>true : boolean
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
>temp : string[]
>["s", "t", "r"] : string[]
>"s" : string
>"t" : string
>"r" : string
var temp1 = [1, 2, 3];
>temp1 : number[]
>[1, 2, 3] : number[]
>1 : number
>2 : number
>3 : number
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
>temp2 : [number[], string[]]
>[[1, 2, 3], ["hello", "string"]] : [number[], string[]]
>[1, 2, 3] : number[]
>1 : number
>2 : number
>3 : number
>["hello", "string"] : string[]
>"hello" : string
>"string" : string
interface myArray extends Array<Number> { }
>myArray : myArray
>Array : T[]
>Number : Number
interface myArray2 extends Array<Number|String> { }
>myArray2 : myArray2
>Array : T[]
>Number : Number
>String : String
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : (string | number | boolean)[]
>[1, true, ...temp, ] : (string | number | boolean)[]
>1 : number
>true : boolean
>...temp : string
>temp : string[]
var d1 = [...temp]; // has type string[]
>d1 : string[]
>[...temp] : string[]
>...temp : string
>temp : string[]
var d2: number[] = [...temp1];
>d2 : number[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d3: myArray = [...temp1];
>d3 : myArray
>myArray : myArray
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d4: myArray2 = [...temp, ...temp1];
>d4 : myArray2
>myArray2 : myArray2
>[...temp, ...temp1] : (string | number)[]
>...temp : string
>temp : string[]
>...temp1 : number
>temp1 : number[]
var d5 = [...a2];
>d5 : (string | number)[]
>[...a2] : (string | number)[]
>...a2 : string | number
>a2 : (string | number)[]
var d6 = [...a3];
>d6 : number[]
>[...a3] : number[]
>...a3 : number
>a3 : number[]
var d7 = [...a4];
>d7 : (() => number)[]
>[...a4] : (() => number)[]
>...a4 : () => number
>a4 : (() => number)[]
var d8: number[][] = [[...temp1]]
>d8 : number[][]
>[[...temp1]] : number[][]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
var d9 = [[...temp1], ...["hello"]];
>d9 : (string | number[])[]
>[[...temp1], ...["hello"]] : (string | number[])[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
>...["hello"] : string
>["hello"] : string[]
>"hello" : string
@@ -0,0 +1,86 @@
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(10,5): error TS2322: Type 'undefined[]' is not assignable to type '[any, any, any]'.
Property '0' is missing in type 'undefined[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,5): error TS2322: Type '[string, number, boolean]' is not assignable to type '[boolean, string, number]'.
Types of property '0' are incompatible.
Type 'string' is not assignable to type 'boolean'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'.
Types of property 'pop' are incompatible.
Type '() => string | number | boolean' is not assignable to type '() => number'.
Type 'string | number | boolean' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2322: Type '(string[] | number[])[]' is not assignable to type 'tup'.
Property '0' is missing in type '(string[] | number[])[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
Property '0' is missing in type 'number[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'.
Types of property 'push' are incompatible.
Type '(...items: (string | number)[]) => number' is not assignable to type '(...items: Number[]) => number'.
Types of parameters 'items' and 'items' are incompatible.
Type 'string | number' is not assignable to type 'Number'.
Type 'string' is not assignable to type 'Number'.
Property 'toFixed' is missing in type 'String'.
==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts (6 errors) ====
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var a0: [any, any, any] = []; // Error
~~
!!! error TS2322: Type 'undefined[]' is not assignable to type '[any, any, any]'.
!!! error TS2322: Property '0' is missing in type 'undefined[]'.
var a1: [boolean, string, number] = ["string", 1, true]; // Error
~~
!!! error TS2322: Type '[string, number, boolean]' is not assignable to type '[boolean, string, number]'.
!!! error TS2322: Types of property '0' are incompatible.
!!! error TS2322: Type 'string' is not assignable to type 'boolean'.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [b1, b2]: [number, number] = [1, 2, "string", true];
~~~~~~~~
!!! error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number | boolean' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number | boolean' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
interface tup {
0: number[]|string[];
1: number[]|string[];
}
interface myArray extends Array<Number> { }
interface myArray2 extends Array<Number|String> { }
var c0: tup = [...temp2]; // Error
~~
!!! error TS2322: Type '(string[] | number[])[]' is not assignable to type 'tup'.
!!! error TS2322: Property '0' is missing in type '(string[] | number[])[]'.
var c1: [number, number, number] = [...temp1]; // Error cannot assign number[] to [number, number, number]
~~
!!! error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
!!! error TS2322: Property '0' is missing in type 'number[]'.
var c2: myArray = [...temp1, ...temp]; // Error cannot assign (number|string)[] to number[]
~~
!!! error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'.
!!! error TS2322: Types of property 'push' are incompatible.
!!! error TS2322: Type '(...items: (string | number)[]) => number' is not assignable to type '(...items: Number[]) => number'.
!!! error TS2322: Types of parameters 'items' and 'items' are incompatible.
!!! error TS2322: Type 'string | number' is not assignable to type 'Number'.
!!! error TS2322: Type 'string' is not assignable to type 'Number'.
!!! error TS2322: Property 'toFixed' is missing in type 'String'.
@@ -0,0 +1,60 @@
//// [arrayLiterals3.ts]
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var a0: [any, any, any] = []; // Error
var a1: [boolean, string, number] = ["string", 1, true]; // Error
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var [b1, b2]: [number, number] = [1, 2, "string", true];
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
interface tup {
0: number[]|string[];
1: number[]|string[];
}
interface myArray extends Array<Number> { }
interface myArray2 extends Array<Number|String> { }
var c0: tup = [...temp2]; // Error
var c1: [number, number, number] = [...temp1]; // Error cannot assign number[] to [number, number, number]
var c2: myArray = [...temp1, ...temp]; // Error cannot assign (number|string)[] to number[]
//// [arrayLiterals3.js]
// Each element expression in a non-empty array literal is processed as follows:
// - If the array literal contains no spread elements, and if the array literal is contextually typed (section 4.19)
// by a type T and T has a property with the numeric name N, where N is the index of the element expression in the array literal,
// the element expression is contextually typed by the type of that property.
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is contextually typed by a tuple-like type,
// the resulting type is a tuple type constructed from the types of the element expressions.
var a0 = []; // Error
var a1 = ["string", 1, true]; // Error
// The resulting type an array literal expression is determined as follows:
// - If the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section 4.17.1),
// the resulting type is a tuple type constructed from the types of the element expressions.
var _a = [1, 2, "string", true], b1 = _a[0], b2 = _a[1];
// The resulting type an array literal expression is determined as follows:
// - the resulting type is an array type with an element type that is the union of the types of the
// non - spread element expressions and the numeric index signature types of the spread element expressions
var temp = ["s", "t", "r"];
var temp1 = [1, 2, 3];
var temp2 = [[1, 2, 3], ["hello", "string"]];
var c0 = temp2; // Error
var c1 = temp1; // Error cannot assign number[] to [number, number, number]
var c2 = temp1.concat(temp); // Error cannot assign (number|string)[] to number[]
@@ -26,7 +26,7 @@ var myDerivedList: DerivedList<number>;
var as = [list, myDerivedList]; // List<number>[]
//// [arrayLiteralsWithRecursiveGenerics.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -97,7 +97,7 @@ var asserted2: any;
//// [arrowFunctionContexts.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -101,7 +101,7 @@ b18 = a18; // ok
//// [assignmentCompatWithCallSignatures3.js]
// these are all permitted with the current rules, since we do not do contextual signature instantiation
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -100,7 +100,7 @@ module Errors {
//// [assignmentCompatWithCallSignatures4.js]
// These are mostly permitted with the current loose rules. All ok unless otherwise noted.
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -67,7 +67,7 @@ b18 = a18; // ok
//// [assignmentCompatWithCallSignatures5.js]
// checking assignment compat for function types. No errors in this file
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -44,7 +44,7 @@ b16 = x.a16;
//// [assignmentCompatWithCallSignatures6.js]
// checking assignment compatibility relations for function types. All valid
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -101,7 +101,7 @@ b18 = a18; // ok
//// [assignmentCompatWithConstructSignatures3.js]
// checking assignment compatibility relations for function types. All of these are valid.
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -100,7 +100,7 @@ module Errors {
//// [assignmentCompatWithConstructSignatures4.js]
// checking assignment compatibility relations for function types.
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -67,7 +67,7 @@ b18 = a18; // ok
//// [assignmentCompatWithConstructSignatures5.js]
// checking assignment compat for function types. All valid
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -44,7 +44,7 @@ b16 = x.a16;
//// [assignmentCompatWithConstructSignatures6.js]
// checking assignment compatibility relations for function types. All valid.
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -45,7 +45,7 @@ module Generics {
//// [assignmentCompatWithNumericIndexer.js]
// Derived type indexer must be subtype of base type indexer
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -42,7 +42,7 @@ module Generics {
//// [assignmentCompatWithNumericIndexer3.js]
// Derived type indexer must be subtype of base type indexer
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -93,7 +93,7 @@ module WithBase {
//// [assignmentCompatWithObjectMembers4.js]
// members N and M of types S and T have the same name, same accessibility, same optionality, and N is not assignable M
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -90,7 +90,7 @@ module SourceHasOptional {
//// [assignmentCompatWithObjectMembersOptionality.js]
// Derived member is not optional but base member is, should be ok
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -92,7 +92,7 @@ module SourceHasOptional {
//// [assignmentCompatWithObjectMembersOptionality2.js]
// M is optional and S contains no property with the same name as M
// N is optional and T contains no property with the same name as N
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -55,7 +55,7 @@ module Generics {
//// [assignmentCompatWithStringIndexer.js]
// index signatures must be compatible in assignments
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
@@ -71,7 +71,7 @@ foo() = value;
(foo()) = value;
//// [assignmentLHSIsValue.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
+1 -1
View File
@@ -24,7 +24,7 @@ class Point3D extends Point {
//// [autolift4.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
+1 -1
View File
@@ -30,7 +30,7 @@ function f() {
//// [baseCheck.js]
var __extends = this.__extends || function (d, b) {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;

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